gpt4 book ai didi

java - 对齐 JButton

转载 作者:行者123 更新时间:2023-12-01 18:05:45 28 4
gpt4 key购买 nike

This is the output I want pretty much我必须将程序上的按钮对齐到中间,我运行的当前代码但显示的按钮与程序一样大,我想要一个特定大小的中心按钮,这是我尝试过的

/**
* Created by Timk9 on 11/04/2016.
*/
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {

{
JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
window.setSize(600, 600);
window.setVisible(true);
window.setLocationRelativeTo(null);

JPanel p = new JPanel(new GridBagLayout());
//Button does not appear until I resize the program?
JButton b1 = new JButton("Click here");
GridBagConstraints c = new GridBagConstraints();

p.add(b1);
window.add(p);

}

public static void main(String[] args) {
new Test();

}

}

最佳答案

JPanel p = new JPanel(new GridBagLayout());

您可以使用 GridBagLayout 创建一个面板,它是一个很好的布局管理器,可用于使组件居中。

p.add(b1);

但是您可以在不使用任何约束的情况下将按钮添加到面板。

代码应该是:

p.add(b1, c);

//Button does not appear until I resize the program?

所有组件都应在框架可见之前添加到框架中。 setVisible(...) 语句应该是构造函数的最后一个语句。

Also could you point out which part is an instance initializer block, I thought I was using a constructor

请参阅 How to Make Frames 上 Swing 教程中的 FrameDemo 示例。以获得更好的方式来构建代码,以便您遵循 Swing 约定。从工作代码开始并进行更改以添加包含按钮的面板,而不是使用 JLabel。请注意,您不再需要使用 getContentPane() 方法,只需将面板直接添加到框架即可。

关于java - 对齐 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552836/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com