请解释为什么它不起作用,也可以发布解决方案来解决这个问题.非常感谢你提前.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,JFrame使用a BorderLayout,它将尝试调整内容的大小以适应父容器.虽然BorderLayout将尝试使用首选大小作为提示,但如果可用空间大于或小于,则它将自动调整以允许中心内容(默认位置)填充父容器的整个可用空间.
您可以尝试使用a FlowLayout或GridBagLayout更有可能在更多情况下遵循首选大小
请查看如何在容器上布置组件以获取更多详细信息
你可以使用pack()方法.来自Java Docs:
public void pack():使此窗口的大小适合其子组件的首选大小和布局....
您应该在构造函数的末尾使用此方法:
...
setLocationRelativeTo(null);
setVisible(true);
pack();
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您希望JFrame保持大小,JPanel也要保持大小.您可以尝试以下方法:
像这样的东西:
public Run()
{
/** Create & Initialise Things **/
jpanel = new JPanel();
JPanel jpanel2 = new JPanel();
x = 400;
y = 400;
/** JPanel Properties **/
jpanel2.setBackground(Color.red);
jpanel2.setPreferredSize(new Dimension(50, 50));
jpanel.add(jpanel2);
/** Add things to JFrame and JPanel **/
add(jpanel);
/** JFrame Properties **/
...
}
Run Code Online (Sandbox Code Playgroud)
Edit2:你也可以尝试绝对定位:
public Run()
{
/** Create & Initialise Things **/
jpanel = new JPanel();
JPanel jpanel2 = new JPanel();
x = 400;
y = 400;
jpanel.setLayout(null);
Insets insets = jpanel2.getInsets();
Dimension size = jpanel2.getPreferredSize();
jpanel2.setBounds(125 + insets.left, 100 + insets.top, size.width, size.height);
/** JPanel Properties **/
jpanel2.setBackground(Color.red);
jpanel.add(jpanel2);
/** Add things to JFrame and JPanel **/
add(jpanel);
/** JFrame Properties **/
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11962 次 |
| 最近记录: |