如何将Java窗口(实际上是JFrame)设置为正确的分辨率?

时间:2015-07-06 00:04:29

标签: java jframe window size

我正在通过修改Jamal's pong game来解决Java问题,现在我注意到entire window实际上是800x600,但这不是我想要的! 我希望框架为800x600 围绕作为窗口8的花式边框。向Java询问800x600 JFrame,然后使用794x571框架对我来说没什么意义!

设置窗口的主要代码:

public Main() {
    // cvars contains variables from JPong.ini (It's an extended class from the ini4j library)
    cvars = CVarList.getInstance();

    // get(sectionName, optionName, classtype, defaultValue)
    setSize(cvars.get("Window", "width", int.class, 800),
            cvars.get("Window", "height", int.class, 600));
    setTitle(cvars.get("Window", "title", String.class, "JPong"));
    setResizable(cvars.get("Window", "resizable", boolean.class, false));
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    table = new Table(this);
    add(table);
}

我发现的原因是因为我改变了球拍/桨的速度,并且球拍/拨片卡在窗户的两端,因此在修改代码后,拨片不再粘住,但现在他们移动了一点位于可见帧之外(因为我在逻辑中使用了0和窗口的高度来停止球拍/球拍)

现在我想知道有多少Java窗口实际上是错误的...

2 个答案:

答案 0 :(得分:0)

尝试getContentPane().setPreferredSize(cvars.get("Window", "width", int.class, 800),cvars.get("Window", "height", int.class, 600));并在显示窗口后调用pack()

或者您也可以设置表格的首选大小。

答案 1 :(得分:0)

创建一个JPanel,其中包含Table,覆盖它的getPreferredSize方法并返回所需的大小

public class TableWrapperPanel extends JPanel {
    private Table table;
    public TableWrapperPanel(Table table) {
        setLayout(new BorderLayout());
        this.table = table;
        add(table);
    }

    public Dimension getPreferredSize() {
        cvars = CVarList.getInstance();
        return new Dimension(cvars.get("Window", "width", int.class, 800),
            cvars.get("Window", "height", int.class, 600));
    }
}

现在,在您的main方法中,创建一个TableWrapperPanel的实例并将其添加到您的"窗口",在您完成此操作后调用pack,这将打包窗口周围的内容。

public Main() {
    // cvars contains variables from JPong.ini (It's an extended class from the ini4j library)
    cvars = CVarList.getInstance();

    // get(sectionName, optionName, classtype, defaultValue)
    setSize(cvars.get("Window", "width", int.class, 800),
            cvars.get("Window", "height", int.class, 600));
    setTitle(cvars.get("Window", "title", String.class, "JPong"));
    setResizable(cvars.get("Window", "resizable", boolean.class, false));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    TableWrapperPanel wrapper = new TableWrapper(table);
    add(wrapper );
    pack();
    setVisible(true);
}

或者,您可以创建Table的自定义版本,该版本会覆盖getPreferredSize方法本身

public class SizableTable extends Table { 
    //... Constructors ...

    public Dimension getPreferredSize() {
        cvars = CVarList.getInstance();
        return new Dimension(cvars.get("Window", "width", int.class, 800),
            cvars.get("Window", "height", int.class, 600));
    }
}

而不是在Table方法中创建main的实例,而是创建SizableTable的实例,将其添加到窗口然后调用pack