调整窗口大小时不会调整JButtons的大小

时间:2017-11-26 19:08:16

标签: java swing layout-manager

我正在为一个刽子手游戏创建一个虚拟键盘并尝试设置它,以便在调整窗口大小时调整按钮的宽度。现在,当我启动程序时,我无法看到所有按钮 - 我需要调整窗口的宽度,以便我可以看到所有这些按钮。

我尝试在按钮上使用button.setPreferredSize(new Dimension(35, 35));,虽然这样可以正确调整按钮的大小,但是当我启动程序时,屏幕上出现任何按钮之前会有2秒的延迟。我已评论此行在createKeyboard()

中的位置

当调整窗口大小时,如何压缩按钮(保持按顺序相同)?或者,有没有办法使用setPreferredSize而不会导致延迟?

public GUI() {
    createWindow();
    createPanels();
    addPanels();
    createKeyboard();
    setMainFrameVisible();
}

public void createWindow() {
    mainFrame = new JFrame();
    mainFrame.setSize(500, 300); //500, 300
    mainFrame.setTitle("Hangman");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void createPanels() {
    pnlMain = new JPanel(new BorderLayout());
    pnlKeyboard = new JPanel(new GridLayout (4, 1)); 
    pnlKeyboardQP = new JPanel(new FlowLayout());
    pnlKeyboardAL = new JPanel(new FlowLayout());
    pnlKeyboardZM = new JPanel(new FlowLayout());
}

public void addPanels() {
    mainFrame.add(pnlMain);
    pnlMain.add(pnlKeyboard, BorderLayout.SOUTH);
    pnlKeyboard.add(pnlKeyboardQP);
    pnlKeyboard.add(pnlKeyboardAL);
    pnlKeyboard.add(pnlKeyboardZM);

}

public void createKeyboard() {
    String keyboardFormat = "QWERTYUIOPASDFGHJKLZXCVBNM";
    String buttonLabel;
    char buttonLabelChar;

    for (int i = 0; i < keyboardFormat.length(); i ++) {    
        buttonLabelChar = keyboardFormat.charAt(i);
        buttonLabel = "" + buttonLabelChar; 
        JButton button = new JButton(buttonLabel);
        button.setPreferredSize(new Dimension(35, 35)); // This is causing 2 second delay when game started
        button.addActionListener(
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    System.out.println("Button pressed");
                }
            }
        );
        addKeyboard(buttonLabelChar, button); 
    }
}


public void addKeyboard(char c, JButton button) {

    String QP = "QWERTYUIOP";
    String AL = "ASDFGHJKL";
    String ZM = "ZXCVBNM";

    if (QP.indexOf(c) >= 0) {
        pnlKeyboardQP.add(button);
    }
    else if (AL.indexOf(c) >= 0) {
        pnlKeyboardAL.add(button);
    }
    else if (ZM.indexOf(c) >= 0) {
        pnlKeyboardZM.add(button);
    }

0 个答案:

没有答案