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

use*_*200 1 java swing layout-manager

我想要做的是将按钮放在应用程序的左下角.有人可以给我一个如何做的例子吗?

这就是我所拥有的:

应用图片

这是我的代码:

        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);
Run Code Online (Sandbox Code Playgroud)

Aza*_*zad 7

首先将框架的布局设置为null如果使用JFrame,或者null如果使用面板则将布局面板设置为,然后使用setBounds()方法:

button.setBounds(x,y,width,height);
Run Code Online (Sandbox Code Playgroud)

看看我为你做的这个例子:

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();
       }
}
Run Code Online (Sandbox Code Playgroud)

  • Java GUI可能必须在许多平台上工作,在不同的屏幕分辨率和使用不同的PLAF.因此,它们不利于组件的精确放置.对于强大的GUI,而是使用布局管理器或它们的组合,以及用于空白区域的布局填充和边框来组织组件. (7认同)

Ani*_*kur 6

试试BorderLayout

addPanel.setLayout(new BorderLayout());
addPanel.add(addButton,BorderLayout.SOUTH);
Run Code Online (Sandbox Code Playgroud)

即使在你添加面板的内部,你也可以使用另一个面板(比如bottomLeft)和网格布局

bottomLeft.setLayout(new GridLayout(1,3,200,0));
bottomLeft.add(addPanel)
Run Code Online (Sandbox Code Playgroud)