tester7281
tester7281

Reputation: 13

JPanel button is not at the correct place

i made a custom JFrame for the desktop application and i added a JPanel on the very top of the app to serve as a subtitute of the title box. the problem is when i added a button it located right in the middle of the JPanel instead of the usual left top. AND it would not move even if i set it at a different location. here is the code:

        JFrame f = new JFrame("Hello");
        f.setResizable(true);
        JPanel pa = new JPanel();
        JButton btn = new JButton("Exit");

        btn.setBackground(Color.white);
        btn.setText("Button");
        btn.setSize(300, 80);
        btn.setLocation(50, 0);

        pa.setBackground(Color.red);
        pa.setPreferredSize(new Dimension(width,60));
        pa.add(btn);

        f.setBackground(Color.white);
        f.setUndecorated(true);
        f.getContentPane().add(pa, BorderLayout.NORTH);
        f.setSize(new Dimension(width,height));
        f.setLocation(200, 200);
        f.setVisible(true);

Upvotes: 0

Views: 112

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168845

that is one way to do it, but BorderLayout way is not very good way because i also want to add another button next to it.

Then what this might need is a FlowLayout using FlowLayout.LEADING as the alignment.

But as general tips:

  1. Provide ASCII art or a simple drawing of the intended layout of the GUI (showing all components) at minimum size, and if resizable, with more width and height - to show how the extra space should be used.
  2. For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example of your attempt.

Upvotes: 1

Silvio Mayolo
Silvio Mayolo

Reputation: 70387

You use a BorderLayout in the frame. You can do the same thing in the panel.

pa.setLayout(new BorderLayout());
pa.add(btn, BorderLayout.WEST);

In general, setLocation tends to fight against the layout manager, so you usually don't want to use it unless you're going to position everything by hand.

Upvotes: 1

Related Questions