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 JLabels 及其 JTextFields 居中。还将“输入玩家姓名”JLabel 居中,这似乎已经与更改中断。