如何使用Java将JButton放置在JFrame中的所需位置

我想将Jbutton放在JFrame中的特定坐标上。 我为JPanel(我放在JFrame上)设置了setBounds,并为JButton设置了setBounds。 但是,它们似乎没有按预期运行。

我的输出:

alt text http://sofzh.miximages.com/java/2d8kuah.jpg

这是我的代码:

import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Control extends JFrame { // JPanel JPanel pnlButton = new JPanel(); // Buttons JButton btnAddFlight = new JButton("Add Flight"); public Control() { // FlightInfo setbounds btnAddFlight.setBounds(60, 400, 220, 30); // JPanel bounds pnlButton.setBounds(800, 800, 200, 100); // Adding to JFrame pnlButton.add(btnAddFlight); add(pnlButton); // JFrame properties setSize(400, 400); setBackground(Color.BLACK); setTitle("Air Traffic Control"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new Control(); } } 

如何将JButton置于坐标(0,0)?

在添加组件之前,应调用以下行

 pnlButton.setLayout(null); 

上面将设置您的内容面板使用绝对布局。 这意味着您必须始终使用setBounds方法显式设置组件的边界。

一般来说,我不建议使用绝对布局。

在按钮上使用child.setLocation(0, 0) ,在parent.setLayout(null) 。 不要在JFrame上使用setBounds(…)来调整它的大小,而是考虑使用setSize(...)并让操作系统定位框架。

 //JPanel JPanel pnlButton = new JPanel(); //Buttons JButton btnAddFlight = new JButton("Add Flight"); public Control() { //JFrame layout this.setLayout(null); //JPanel layout pnlButton.setLayout(null); //Adding to JFrame pnlButton.add(btnAddFlight); add(pnlButton); // postioning pnlButton.setLocation(0,0); 

在某个地方定义consts:

 private static final int BUTTON_LOCATION_X = 300; // location x private static final int BUTTON_LOCATION_Y = 50; // location y private static final int BUTTON_SIZE_X = 140; // size height private static final int BUTTON_SIZE_Y = 50; // size width 

然后在下面:

  JButton startButton = new JButton("Click Me To Start!"); // startButton.setBounds(300, 50,140, 50 ); startButton.setBounds(BUTTON_LOCATION_X , BUTTON_LOCATION_Y, BUTTON_SIZE_X, BUTTON_SIZE_Y ); contentPane.add(startButton); 

其中contentPane是包含整个框架的Container对象:

  JFrame frame = new JFrame("Some name goes here"); Container contentPane = frame.getContentPane(); 

我希望这有帮助,对我有用…

您应首先通过语法pnlButton.setLayout()设置布局,然后选择您想要的最合适的布局。 例如: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5)); 。 然后,将JButton带入JPanel。

我已经弄明白了。 为按钮做.setBounds(0,0,220,30).setBounds布局是这样的(int x,int y,int width,int height)

首先,记住您的JPanel大小高度和大小宽度,然后观察:JButton坐标是(xo,yo,x length,y length)。 如果你的窗口是800×600,你只需要写:

 JButton.setBounds(0, 500, 100, 100); 

您只需使用坐标间隙来表示按钮,并知道窗口的结束位置和窗口的开始位置。