I'm having a problem, i implemented a BorderLayout JPanel. And if i try to move a button for a example in the North section, it'll stay at a default location. Here's my code :
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time;
double temperature=0.0;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(700,400);
this.setLocationRelativeTo(null);
this.setResizable(true);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
ip = new JButton ("New");
ip.setPreferredSize(new Dimension(100,50));
ip.setLocation(0, 0);
north.add(ip);
print = new JButton ("Print");
north.add(print);
north.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("10",1,5);
north.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
north.add(start);
south = new JPanel();
legend = new JLabel("Legends are here");
south.add(legend);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
container.add(south, BorderLayout.SOUTH);
this.setContentPane(container);
this.setVisible(true);
}
I want for example my "New" button to be at the left top corner of my window by writing "ip.setLocation(0,0);"
And it stays by default to the center..
Any ideas ?
What you're trying to do is use an AbsoluteLayout instead of a BorderLayout, BorderLayout uses Cardinal directions to set objects on the pane, such as North, East, South, West, and Center. You may want to look at the JavaDoc for BorderLayout.
As an example, you need to set your
north
panel to aBorderLayout()
north.setLayout(new BorderLayout());
Oracle Documentation about BorderLayout
Solution
The north panel is now composed of the following two parts :
ip
(JButton
) andcenterPanel
(JPanel
) containing the rest of the components.Output