请解释为什么它不起作用,也可以发布解决方案来解决这个问题.非常感谢你提前.
public class Run extends JFrame{
/** Fields **/
static JPanel jpanel;
private int x,y;
/** Constructor **/
public Run() {
/** Create & Initialise Things **/
jpanel = new JPanel();
x = 400; y = 400;
/** JPanel Properties **/
jpanel.setBackground(Color.red);
jpanel.setPreferredSize(new Dimension(20,30));
/** Add things to JFrame and JPanel **/
add(jpanel);
/** JFrame Properties **/
setTitle("Snake Game");
setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
setCursor(null);
setResizable(false);
setSize(new Dimension(x,y));
setLocationRelativeto(null);
setVisible(true);
}
/** Set the Cursor **/
public void setCursor() {
setCursor (Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
/** Main Method **/
public static void main(String [ ] args) {
Run run = new Run();
run.setCursor();
}
}
解决方法
问题是,JFrame使用BorderLayout,它将尝试调整内容大小以适合父容器.虽然BorderLayout将尝试使用首选大小作为提示,但如果可用空间大于或小于,则它将自动调整以允许中心内容(默认位置)填充父容器的整个可用空间.
您可以尝试使用FlowLayout或GridBagLayout,它更有可能在更多情况下遵循首选大小
有关详细信息,请查看How to layout components on containers