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

新手上路,请多包涵

我想在 JButton 的特定 坐标 处放置一个 JFrame 。 I used setBounds() for the JPanel (which I placed on the JFrame ) and also setBounds() for the JButton .但是,它们似乎没有按预期运行。

我的输出:

替代文字

这是我的代码:

 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) 处?

原文由 Haxed 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 663
2 个回答

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

pnlButton.setLayout(null);

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

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

原文由 Eugene Ryzhikov 发布,翻译遵循 CC BY-SA 2.5 许可协议

在按钮上使用 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);

原文由 Chadwick 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题