2012-11-30 52 views
1

嗨,我是初學者到Java和使用GridBagLayout做小GUI。見附件的代碼和輸出。我想要的是按照gridx和gridy中指定的位置將JButton放置在左上角。但它放置元件在中心而不是左上角的預期,如果我使用插圖,爲gridx/gridy所有的工作,但不能從正確的座標,所以請參閱附帶的代碼和圖像,並指導我一下GridBagLayout compnent的位置不起作用

public rect() 
{  

     JPanel panel = new JPanel(new GridBagLayout()); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     JButton nb1= new JButton("Button1 "); 
     JButton nb2= new JButton("Button2 "); 

     gbc.gridx=0; 
     gbc.gridy=0 ; 
     panel.add(nb1, gbc); 
     gbc.gridx=1; 
     gbc.gridy=1; 
     panel.add(nb2, gbc); 
     panel.setVisible(true); 
     JFrame frame = new JFrame("Address Book "); 
     frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     frame.setSize(300, 300); 
     frame.add(panel); 

     frame.setVisible(true); 


} 

輸出:希望在左上角這些按鈕請指導我

enter image description here

回答

1

我認爲這個問題是更多的使用setSize(..),你應該寧願使用適當LayoutManager和0123調用pack()將所有的組件JFrame後設置JFrame可見的,也沒有必要panel.setVisible(..)前例如:

enter image description here

public static void main(String[] args) { 

    SwingUtilities.invokeLater(new Runnable() { 
     @Override 

     public void run() { 
      JPanel panel = new JPanel(new GridBagLayout()); 

      JButton nb1 = new JButton("Button1 "); 
      JButton nb2 = new JButton("Button2 "); 

      GridBagConstraints gbc = new GridBagConstraints(); 

      gbc.gridx = 0; 
      gbc.gridy = 0; 
      panel.add(nb1, gbc); 

      gbc.gridx = 1; 
      gbc.gridy = 1; 
      panel.add(nb2, gbc); 

      JFrame frame = new JFrame("Address Book "); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      frame.add(panel); 

      frame.pack(); 
      frame.setVisible(true); 
     } 
    }); 
} 
+1

非常感謝先生 –