GUI布局添加

时间:2013-03-23 22:27:38

标签: swing user-interface layout grid-layout

public void testDialog()
    {
        JPanel myPanel =  new JPanel(new GridBagLayout());
        GridBagConstraints grid = new GridBagConstraints();
        grid.gridx=0; //Moves Things across
        grid.gridy=0; //Moves things down
        myPanel.add(new JLabel("ENTER PLAYER NAMES", JLabel.CENTER), grid);
        grid.gridy++;
        JTextField tfNames [] = new JTextField[getNumOfPlayers()];
        //Loops through the number of players, initialising and adding a JLabel and JTextField to the JPanel
        for(int i=0;i < getNumOfPlayers();i++)
        {
            grid.gridx = 0;
            tfNames[i] = new JTextField(10);
            myPanel.add(new JLabel("Player " + (i+1), JLabel.CENTER), grid);
            grid.gridx ++;
            myPanel.add(tfNames[i], grid);
            grid.gridy+=1;
        }

        int result = JOptionPane.showConfirmDialog(null, myPanel,
               "Initial Dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null);
         //Declaring the array of strings which holds the players name
         playerNames = new String [getNumOfPlayers()];
        //If the 'OK' button is clicked loop through the number of players checking to see if all the JTextFields aren't empty
        //If they are recall this method otherwise store the input player names in the playerName array.
       if(result == JOptionPane.OK_OPTION)
       {
            for(int i=0;i < getNumOfPlayers();i++)
            {
                if(tfNames[i].getText().equals(""))
                {
                    testDialog();
                }
                else
                {
                    playerNames[i] = tfNames[i].getText();
                }
            }
       }
       //If 'Cancel' button is clicked go back to the previous dialog
       else if (result == JOptionPane.CANCEL_OPTION)
       {
            numPlayersDialog();
       }
       //If 'x' in top right hand corner of the screen is clicked go back to previous dialog
       else
       {
            numPlayersDialog();
       }
    }

尝试设置这个样式现在让我有些痛苦。想要将Player1,Player2,Player3,Player4 JLabel及其JTextField集中在一起。同时将“输入玩家名称”JLabel置于中心位置,这似乎打破了这些变化。

1 个答案:

答案 0 :(得分:0)

我可以建议嵌套布局(未经测试)吗?

-------------------------
|   panel with JLabel   |
-------------------------
| panel with GridLayout |
-------------------------