Add Multiple Panels, Set Size, and Change Text's Color
Learn how to add multiple panels to one panel, set panel size, and change the color of text displayed on any component.
A panel is a container component. A container component can hold more than one component. They’re often a combination of labels, buttons, input fields, and other components.
When a window is packed, all of its components are reduced to their preferred size. You can change the component’s preferred size with a new dimension, which includes width and height.
Adding two panels to one panel
Guess My Color will need two panels to show the sample color and target color. Other methods will use these panels, so they should be defined as instance variables.
- Create private
JPanel
instance variables calledsamplePanel
andtargetPanel
, initialized by calling theJPanel
constructor.
...
private JPanel samplePanel = new JPanel();
private JPanel targetPanel = new JPanel();
public GuessMyColor() {
...
Now, add the two panels to the center of the window.
- In
initGUI()
, after addingcenterPanel
to the window, set the color ofsamplePanel
to black using JPanel’ssetBackground()
method with Color’sBLACK
variable. - Add
samplePanel
tocenterPanel
using JPanel’sadd()
method with only the Component parameter value. - Set the
color
oftargetPanel
to cyan using JPanel’ssetBackground()
method with Color’sCYAN
variable. - Add
targetPanel
tocenterPanel
using JPanel’sadd()
method with only the Component parameter value.
...
public void initGUI() {
...
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.BLUE);
add(centerPanel, BorderLayout.CENTER);
samplePanel.setBackground(____________);
centerPanel.add(samplePanel);
targetPanel.setBackground(____________);
centerPanel.add(__________________);
JPanel leftPanel = new JPanel();
...
Get hands-on with 1200+ tech skills courses.