【发布时间】:2014-08-27 00:12:12
【问题描述】:
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.setResizable(false); 时,当我拉伸屏幕时,按钮的高度会增加,但它的宽度仍然保持不变。
所以请告诉我出了什么问题?
【问题讨论】:
-
不相关,硬编码系统路径,可能会在部署应用时出现麻烦,考虑如何add images to Java Project,为项目结构组织的方式。此外,在将所有组件添加到
JFrame后,尝试将frame.setVisible(true)作为最后一行,前面是frame.pack()。在此之前不要调用它,这不是一个好习惯,也是你必须再次设置大小的原因,而是调用frame.pack()