gpt4 book ai didi

java - 如何为 JButton 指定首选大小?

转载 作者:行者123 更新时间:2023-12-01 07:25:59 28 4
gpt4 key购买 nike

   import javax.swing.*;
import java.awt.*;
class MainGui{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JButton newBut = new JButton("New Game");
JButton continueBut = new JButton("Continue");
JButton exitBut = new JButton("Exit");
JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\game5.jpg"));
public MainGui(){
frame.setSize(600,800);
frame.setVisible(true);
frame.setResizable(false);
setButtonSize();
frame.setLayout(new BorderLayout());
frame.setContentPane(backImage);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
insertBlankArea(frame);
frame.getContentPane().add(newBut);
insertBlankArea(frame);
frame.getContentPane().add(continueBut);
insertBlankArea(frame);
frame.getContentPane().add(exitBut);
frame.setSize(799,800);

}
public void insertBlankArea(JFrame frame){
frame.getContentPane().add(Box.createRigidArea(new Dimension(280,155)));
}
public void setButtonSize(){
Dimension dim = new Dimension(100,100);//here is the problem,i am not getting the desired dimension and the size of buttons remains the default.
newBut.setPreferredSize(dim);
continueBut.setPreferredSize(dim);
exitBut.setPreferredSize(dim);
}

public static void main(String[] args) {
MainGui mainGui = new MainGui();
}
}

所以我没有获得按钮的定义大小,但是当我设置frame.setResizes(false);时,当我拉伸(stretch)屏幕时,按钮的高度增加,但其宽度仍然保持不变。< br/>那么请告诉我出了什么问题? this is the output

最佳答案

您应该看看A Visual Guide to Layout Managers并选择最适合您情况的一种。您还应该避免显式设置大小(即:setSizesetMinimumSizesetMaximumSizesetPreferredSize),因为这些方法是布局经理的职责。您可能还有兴趣阅读this question on whether or not the use of the different set size methods should be avoided or not .

最后,您不应该在 Event Dispatch Thread (EDT) 之外调用您的 MainGUI 类。 。大多数与 Swing GUI 相关的方法都不是线程安全的,因此需要在 EDT 中执行。以下是 main 方法的更正版本:

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MainGui mainGui = new MainGui();
}
});
}

关于java - 如何为 JButton 指定首选大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594887/

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