简体   繁体   中英

How to set the location of a button anywhere in your JFrame

What I want to do is put the button down the bottom left of the application. Could somebody just give me an example of how to do it?

This is what I have:

应用图片

Here's my code:

        super("Test");

    /**Create Components**/
    JPanel addPanel = new JPanel();
    JButton addButton= new JButton("Add");

    /**Add Components**/
    addPanel.add(addButton);
    this.add(addPanel);

    /**Set Components Properties**/
    addButton.setLocation(12, 371);
    addButton.setPreferredSize(new Dimension(116, 40));
    addPanel.setLocation(12, 371);
    addPanel.setPreferredSize(new Dimension(116, 40));

    /**Frame Properties**/
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setPreferredSize(new Dimension(dimension1, dimension2));
    this.setResizable(false);   
    this.pack();
    this.setVisible(true);

Firstly set the frame's layout to null if you are using JFrame, or set layout's panel to null if you are using panel,then use setBounds() method :

button.setBounds(x,y,width,height);

See this example I made for you :

import javax.swing.*;
import java.awt.*;
public class ButtonLocationDemo extends JFrame{

 private JButton button;
 public ButtonLocationDemo(){
      JPanel p = new JPanel();
      button = new JButton("Button");
      p.setLayout(null);
      button.setBounds(40,100,100,60);
      p.add(button);

      getContentPane().add(p);
      //setLayout(null);
      setDefaultCloseOperation(3);
      setSize(400,400);
      setVisible(true);

     }
   public static void main(String...args){
       new ButtonLocationDemo();
       }
}

Try BorderLayout

addPanel.setLayout(new BorderLayout());
addPanel.add(addButton,BorderLayout.SOUTH);

Even inside you addPanel you can have another panel(say bottomLeft) with Grid Layout

bottomLeft.setLayout(new GridLayout(1,3,200,0));
bottomLeft.add(addPanel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM