Java Reference
In-Depth Information
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("My First Frame");
JPanel bluePanel = new JPanel();
JPanel redPanel = new JPanel();
JLabel label = new JLabel("<-- pick your side -->");
frame.getContentPane().add(label, BorderLayout.CENTER);
bluePanel.setBackground(Color.blue);
redPanel.setBackground(Color.red);
frame.getContentPane().add(bluePanel, BorderLayout.LINE_START);
frame.getContentPane().add(redPanel, BorderLayout.LINE_END);
JButton blueButton = new JButton("PICK BLUE TEAM");
JButton redButton = new JButton("PICK RED TEAM");
bluePanel.add(blueButton);
redPanel.add(redButton);
frame.pack();
frame.setVisible(true);
}
}
3.
Run the project from Eclipse. You should see the window shown in Figure 11-1.
figure 11-1  
How It Works
This is how it works:
1.
The window you see is your actual JFrame , a container for other components or containers. The
getContentPane() method gives you access to the actual container to which you can add() other
components (or containers). Note the setTitle() method allows you to set the title, and the
setDefaultCloseOperation() method allows you to specify what the Java program should do
(in this case, stop completely) when the user closes this JFrame object.
2.
You also constructed two JPanel containers and set their background colors. They are added to the
left and right sides of the JFrame content pane. The default layout for a JFrame content pane is a so‐
called border layout. Don't worry about this too much, as you will see layouts in more detail soon.
3.
Next, two buttons are created with different text labels, and they are added to the JPanels .
4.
Finally, calling the pack() method of JFrame ensures everything is laid out correctly and then
shows the frame to the user.
Search WWH ::




Custom Search