简体   繁体   English

如何在JFrame中的任何位置设置按钮的位置

[英]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 : 首先设置帧的布局,以null如果正在使用的JFrame,或者设置布局的面板null如果使用的是面板,然后使用setBounds()方法:

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 尝试BorderLayout

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

Even inside you addPanel you can have another panel(say bottomLeft) with Grid Layout 即使在addPanel内部,您也可以使用网格布局创建另一个面板(例如bottomLeft)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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