Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning a JPanel in a JFrame at specific position

Tags:

java

swing

jpanel

I need an help for positioning a JPanel in a specific position into a Jframe.

I have a JPanel in a class who extends JFrame, and I need to put this JPanel in a specific x,y position.

It's something like this:

public class Frame extends JFrame {

    public Frame(){

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocation(250, 250);
        this.setSize(300,300);
        this.setVisible(true);

        JPanel panel = new JPanel();
        this.add(panel);
        panel.setLocation(150, 150);
        panel.add(new JButton("Hello!")); // just to show JPanel

    }//Frame()
}//Frame

I don't need a LayoutManager for the position of the JPanel, because I need to put that JPanel in a specific position (like 150,150 of the example). But if I do panel.setLocation(150,150) like in the code above, nothing happens, and JPanel remain in the north-centre of the frame (also if I change x,y number instead of 150,150).

And it shows like this:

http://i.imgur.com/Te3z0kv.png

like image 948
alecarnevale Avatar asked Nov 25 '13 15:11

alecarnevale


People also ask

How do I change JPanel in JFrame?

Just call the method pack() after setting the ContentPane , ( java 1.7 , maybe older) like this: JFrame frame = new JFrame(); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); .... frame. setContentPane(panel1); frame.

How do I change the layout of a JPanel in Java?

The most common JPanel constructor has no parameters. This creates a panel with the default layout (FlowLayout). Call setLayout() to change the layout. JPanel p = new JPanel(); p.


2 Answers

Of the frame's content panel, the layout manager by default is a BorderLayout (NWSE+C). Do:

this.getContentPanel().setLayout(null);
like image 188
Joop Eggen Avatar answered Oct 28 '22 04:10

Joop Eggen


using setBounds(new Rectangle(96, 67, 98, 41)); you can do this... just see the example

/**
 * This method initializes this
 *
 * @return void
 */
private void initialize() {
    this.setSize(300, 200);
    this.setContentPane(getJContentPane());
    this.setTitle("JFrame");
}

/**
 * This method initializes jContentPane
 *
 * @return javax.swing.JPanel
 */
private JPanel getJContentPane() {
    if (jContentPane == null) {
        jContentPane = new JPanel();
        jContentPane.setLayout(null);
        jContentPane.add(getLoginButton(), null);
    }
    return jContentPane;
}

}

like image 37
Konzern Avatar answered Oct 28 '22 05:10

Konzern