以下类创建一个窗口/框架。
public class Window {
private int width, height;
private JFrame frame;
private Canvas canvas;
private String title;
private JButton button;
private JPanel panel;
public Window(String title){
System.out.println("Initialization Window...");
this.title = title;
width = Reference.width;
height = Reference.height;
button = new JButton("cool button");
CreateWindow();
}
private void CreateWindow(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
panel = new JPanel();
panel.add(button);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.add(panel);//my problem is in this line
frame.pack();
}
当我运行它时,我添加到框架画布和jpanel。框架的大小设置为我所制作的按钮的大小。但删除"frame.add(panel)
会使其恢复正常大小。我错过了什么吗?
以防我使用jpanel和canvas。我正在使用画布,因为我使用bufferstategy作为绘图图形,我需要jpanel添加按钮和其他东西。
答案 0 :(得分:3)
[...]
布局。答案 1 :(得分:0)
我必须说,如果您刚刚扩展JFrame
,除非您想扩展其他内容,否则会更简单。
您需要了解,为了代码可读性和可重用性,您需要遵循传统的Java规则和最佳实践。
@Hovercraft Full Of Eels已经解释了你上面所需要的一切。我在这里所做的就是通过榜样让你正确,所以不需要复制他所说的内容。
FlowLayout可能是Java中最简单,最简单的布局管理器,但与GridLayout
或GrdiBagLayout
相比,它并不是那么强大。
这是代码:
public class Window extends JFrame {
private int width, height;
private Canvas canvas;
private String title;
private JButton button;
private JPanel panel;
public Window(String title){
super( title );
System.out.println("Initialization Window...");
this.title = title;
setLayout( new FlowLayout() );
//width = Reference.width;
//height = Reference.height;
button = new JButton("cool button");
createWindow();
}
private void createWindow(){
setSize(width, height);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
panel = new JPanel();
panel.add(button);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(200, 200));
canvas.setMaximumSize(new Dimension(400, 400));
canvas.setMinimumSize(new Dimension(200, 200));
canvas.setFocusable(false);
add(canvas);
add(panel);//my problem is in this line
pack();
}
}