I have a problem with Java GUI.
I want to create three JPanel
instances which have size different in one JFrame
. JFrame
size 300x800 and Panel1
300x200, Panel2
300x100 and Panel3
300x500. I want to add this panels under by under.
How to solve this problem?
Use a BorderLayout
1 .
panel1
to the NORTH
panel2
to the CENTER
panel3
to the SOUTH
Stretch your imagination that the heights are ten times bigger.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class ColoredPanels {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBackground(Color.BLUE);
gui.setBorder(new EmptyBorder(5,5,5,5));
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(300,20));
panel1.setBackground(Color.RED);
gui.add(panel1, BorderLayout.NORTH);
JPanel panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(300,10));
panel2.setBackground(Color.ORANGE);
gui.add(panel2, BorderLayout.CENTER);
JPanel panel3 = new JPanel();
panel3.setPreferredSize(new Dimension(300,50));
panel3.setBackground(Color.YELLOW);
gui.add(panel3, BorderLayout.SOUTH);
// a frame would need pack() etc.
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
BorderLayout
, .. or BoxLayout
as mentioned by Shakedown. camelCase
for attribute names. You can try sizing your panels with setPreferredSize()
and company. Then look into using a BoxLayout
on your frame, which will put your panels in a row or column.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.