JPanel无法使用setSize& setPrefferedSize [英] JPanel not working with setSize & setPrefferedSize
问题描述
请解释为什么它不起作用,也可以发布解决方案来解决此问题.提前非常感谢您.
Please explain why it does not work, also could you post a solution to solve this issue. Thank you very mucho in advance.
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
会尝试使用首选大小作为提示,但是如果可用空间更大或更小,它将自动调整以允许中心内容(默认位置)填充父容器的整个可用空间.
The problem is, JFrame
uses a BorderLayout
, which will try and size the content to fit the parent container. While BorderLayout
will try and use the preferred size as a hint, if the available space is greater or less then, it will automatically adjust to allow the center content (the default position) to fill the entire available space of the parent container.
您可以尝试使用FlowLayout
或GridBagLayout
,这在更多情况下更可能遵循首选大小
You could try using a FlowLayout
or GridBagLayout
which is more likely to honour the preferred size in more situations
看看如何在容器上布局组件了解更多详情
这篇关于JPanel无法使用setSize& setPrefferedSize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!