How to divide a frame into two parts

2020-05-04 08:35发布

问题:

This is for Tetris. The glass (blue) is left, and the controls (red panel) are situated in the right. In other words, now I would like just to have a frame divided into two parts: left (wider) part is blue, right part is red. Nothing more. But I seem to fail to do this.

So, my logic is: let the frame have FlowLayout. Then I add two panels which means that they are expected to be put in a row.

I prepared this:

public class GlassView extends JFrame{
    public GlassView(){
        this.setSize(600, 750);
        this.setVisible(true);
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


        JPanel glass = new JPanel();
        glass.setLayout(new BoxLayout(glass, BoxLayout.Y_AXIS));
        glass.setSize(450, 750);
        glass.setBackground(Color.BLUE);
        glass.setVisible(true);
        this.add(glass);

        JPanel controls = new JPanel();
        controls.setLayout(new BoxLayout(controls, BoxLayout.Y_AXIS));
        controls.setSize(150, 750);
        controls.setBackground(Color.RED);
        controls.setVisible(true);
        this.add(controls);
    }
}

But only a gray frame is visible on the screen. Could you help me understand why?

回答1:

As Amir said you want to use a JSplitPane for this. I have added this in your code. Have a look at this.

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    GlassView view = new GlassView();
}

private static class GlassView extends JFrame {

    private int width = 600;
    private int height = 750;

    public GlassView() {
        this.setSize(width, height);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel glass = new JPanel();
        glass.setSize(450, 750);
        glass.setBackground(Color.BLUE);
        glass.setVisible(true);

        JPanel controls = new JPanel();
        controls.setSize(150, 750);
        controls.setBackground(Color.RED);
        controls.setVisible(true);

        JSplitPane splitPane = new JSplitPane();
        splitPane.setSize(width, height);
        splitPane.setDividerSize(0);
        splitPane.setDividerLocation(150);
        splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setLeftComponent(controls);
        splitPane.setRightComponent(glass);

        this.add(splitPane);
    }
}


回答2:

How to divide a frame into two parts ... I would like just to have a frame divided into two parts: left (wider) part is blue, right part is red.

You want to use is a SplitPane.