简体   繁体   中英

How do I use nested panels in my GUI application?

I created a drawing application that lets a user choose pen colors but I have having trouble with the layout. I created multiple panels but when I run it, all the buttons are still in one panel. Is there a way to fix this?

public class DrawingGUI extends JPanel {

private JRadioButton penColor1, penColor2, penColor3, randomPenColor, eraser;
private JButton clearButton;
private static Color defaultColor = Color.BLACK;
private static boolean isRandomSelected = false;
private final static int DIAMETER = 12;
protected static boolean canDraw;
private ArrayList<PointTracker> points;

public DrawingGUI() {
    setBackground(Color.WHITE);
    points = new ArrayList<PointTracker>();

    JPanel drawPanel = new JPanel();

    JLabel instructions = new JLabel("Enter your information:");
    JPanel instructionsPanel = new JPanel();
    instructionsPanel.add(instructions);
    drawPanel.add(instructionsPanel);

    JPanel colorPanel1 = new JPanel();
    penColor1 = new JRadioButton("Red");
    drawPanel.add(penColor1);
    penColor1.addActionListener(new ToolListener());
    drawPanel.add(colorPanel1);

    JPanel colorPanel2 = new JPanel();
    penColor2 = new JRadioButton("Blue");
    drawPanel.add(penColor2);
    penColor2.addActionListener(new ToolListener());
    drawPanel.add(colorPanel2);

    JPanel colorPanel3 = new JPanel();
    penColor3 = new JRadioButton("Yellow");
    drawPanel.add(penColor3);
    penColor3.addActionListener(new ToolListener());
    drawPanel.add(colorPanel3);...(So on)

all the buttons are still in one panel

Why is that a problem. That is what I would expect to happen.

Why are you creating a separate panel for each button? The whole point of using panel is to logically group components.

So I would expect you should have something like:

JPanel buttonsPanel = new JPanel();
buttonsPanel.add( button1 );
buttonsPanel.add( button2 );
buttonsPanel.add( button3 );

JPanel drawPanel = new JPanel();
drawPanel.add( component1 );
drawPanel.add( component2 );

frame.add(drawPanel, BorderLayout.PAGE_START);
frame.add(buttonsPanel, BorderLayout.PAGE_END);

Above is a simple example of "nesting" two panels on a frame. Each of the panel can use a different layout manager as required.

For a working example of this approach you can check out Custom Painting Approaches . Both code examples show how you can "nest" a drawing panel and a buttons panel in a frame.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM