2013-03-23 71 views
0
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(); 
     } 
    } 

嘗試的風格,這是導致我有些疼痛now..Want居中PLAYER1,Player2,Player3,Player4的JLabel與他們一起JTextField的。同樣居中'輸入玩家姓名'JLabel,這似乎已經破壞了這些變化。GUI佈局加成

+0

_GridBagLayout(我一直試圖避免)._不能使用它的人的話。它非常靈活和強大。然而,它需要一點點經驗才能完全理解它(這與編寫HTML中的'

'相當難以理解)。 – 2013-03-23 23:30:49

+0

現在做到了GridBagLayout方式,因爲我無法以其他方式工作。然而,現在我試圖去設計它,簡單的東西已經停止工作myPanel.add(新的JLabel(「ENTER PLAYER NAMES」,JLabel.CENTER),grid); IE瀏覽器。這不再是JLabel的中心。更新了上面的代碼,以便您可以看到我所做的事情。 – 2013-03-24 01:00:48

+0

增加了grid.anchor = GridBagConstraints.CENTER; 似乎與JTextFields有關,爲什麼事物不能在中心完美對齊,因爲當我從10縮小到1時,所有東西都靠近中心。任何人有任何想法? – 2013-03-24 01:56:12

回答

0

我可以建議嵌套佈局(未經測試)嗎?

------------------------- 
| panel with JLabel | 
------------------------- 
| panel with GridLayout | 
------------------------- 
+0

剛剛去過那裏,加入: JPanel myPanel2 = new JPanel(); myPanel2.add(new JLabel(「Enter Player Names」)); myPanel.add(myPanel2); 正好在myPanel的初始化之下。它將標籤置於頂部,但出於某種原因,for循環中的JLabel現在不顯示在屏幕上,但是JTextFields卻可以。猜猜我做錯了什麼? – 2013-03-23 22:46:43

+0

應該有三個面板:''topPanel''帶''(2,1)''的GridLayout'',''添加'labelPanel',然後'add's'TablePanelPanel',就像您的舊面板一樣。 – personak 2013-03-23 22:58:23