Question

I'm building my first Java swing GUI, but I cannot manage to have the layout as I wanted. Can you help me to understand how the layout should be set to have the desired result (see image below)?

This is what I get (wrong): This is what I get (wrong)

and if I resize it manually I get the desired result: nice!

Here is my code:

public class MainClass implements Runnable {

private JButton load = new JButton("Load..");
private JButton save = new JButton("Save..");
private JButton clear = new JButton("Clear");
private JLabel displayFile = new JLabel();
List<String> lines;

JFrame frame = new JFrame("SimpleDrawing");

public static void main(String[] args) {
    MainClass maincl = new MainClass();
    SwingUtilities.invokeLater(maincl);

    }

@Override
public void run() {
    DrawingArea area = new DrawingArea();
    frame.setLayout(new FlowLayout());

    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    //buttonPane.add(Box.createHorizontalGlue());
    buttonPane.add(load);

    //buttonPane.add(Box.createRigidArea(new Dimension(5,0)));
    buttonPane.add(save);

    //buttonPane.add(Box.createRigidArea(new Dimension(5,0)));
    buttonPane.add(clear);
    buttonPane.add(displayFile);

    frame.add(buttonPane, BorderLayout.PAGE_START);
    frame.add(area, BorderLayout.CENTER);

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}
Was it helpful?

Solution

Your Frame has the FlowLayout.

frame.setLayout(new FlowLayout());

Give it a BorderLayout.

frame.setLayout(new BorderLayout());

Layout- Informations: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top