Hello,
I'm in Chapter 12 of Deitel's "Java How to Program" and there is an exercise where they show a screenshow of a JFrame and I have to write the appropriate code to create it.
I need to center either a JPanel or JComponent vertically and I can't figure out how to do it ( I can use a GridLayout layout with 3 rows and 1 column and leave the first row blank but I don't think this is how they intended the problem be done).
The following is my code ( I tried to use a BorderLayout layout to add a JPanel to the Center position but the problem with this is when there is only one component and it's added to the center, it takes up the whole Container, and then aligns the JPanel at the top rather than the center of the center position):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Prob128 extends JFrame {
private BorderLayout layout;
private JPanel leftPanel;
private JPanel rightPanel;
private JPanel centerPanel;
public Prob128()
{
super( "Align" );
layout = new BorderLayout( 10, 5 );
Container c = getContentPane();
c.setLayout( layout );
leftPanel = new JPanel();
rightPanel = new JPanel();
centerPanel = new JPanel();
rightPanel.setLayout( new GridLayout( 3, 1, 5, 5 ) );
leftPanel.setLayout( new GridLayout( 2, 1, 5, 5 ) );
centerPanel.setLayout( new BorderLayout( 5, 5 ) );
leftPanel.add( new JCheckBox( "Snap to Grid" ) );
leftPanel.add( new JCheckBox( "Show Grid" ) );
JPanel row1CenterPan = new JPanel( new FlowLayout() );
JPanel row2CenterPan = new JPanel( new FlowLayout() );
row1CenterPan.add( new JLabel( "X: " ) );
row1CenterPan.add( new JTextField( "8", 5 ) );
row2CenterPan.add( new JLabel( "Y: " ) );
row2CenterPan.add( new JTextField( "8", 5 ) );
JPanel centerOfCenter = new JPanel( new GridLayout( 2, 1, 5, 5 ) );
centerOfCenter.add( row1CenterPan );
centerOfCenter.add( row2CenterPan );
centerPanel.add( centerOfCenter, BorderLayout.CENTER );
rightPanel.add( new JButton( "Ok" ) );
rightPanel.add( new JButton( "Cancel" ) );
rightPanel.add( new JButton( "Help" ) );
c.add( leftPanel, BorderLayout.WEST );
c.add( rightPanel, BorderLayout.EAST );
c.add( centerPanel, BorderLayout.CENTER );
setSize( 300, 125 );
show();
}
public static void main( String args[] )
{
Prob128 app = new Prob128();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
Please try not to use something my textbook hasn't taught yet.
Thank you.