2014-10-29 68 views
-3

我想作一個簡單的佈局,像這樣:簡單的佈局 - 的Java Swing

enter image description here

http://i.stack.imgur.com/7AIvt.png/

我能做到這一點沒有佈局管理器,但我需要使用它。我試圖自己做,但我失敗了。

+1

所有你需要知道: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html – 2014-10-29 13:53:24

+2

*「我試圖自己做,但我失敗了「* - 好吧,[你有什麼嘗試?](http://mattgemmell.com/what-have-you-tried/) – dic19 2014-10-29 14:02:39

回答

1

閱讀關於LayoutManager's

嘗試下一個:

import java.awt.Color; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.Insets; 

import javax.swing.BorderFactory; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class TestFrame extends JFrame { 

    public TestFrame() { 
     init(); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     pack(); 
     setLocationRelativeTo(null); 
     setVisible(true); 
    } 

    private void init() { 
     setLayout(new GridBagLayout()); 

     GridBagConstraints c = new GridBagConstraints(); 
     c.insets = new Insets(5, 5, 5, 5); 
     c.gridx=0; 
     c.gridy=0; 

     c.gridwidth = 2; 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.weightx = 1; 
     add(getLbl(),c); 


     JPanel left = new JPanel(new GridLayout(3,3,5,5)); 
     for(int i =0;i<9;i++){ 
      left.add(getLbl()); 
     } 

     JPanel right = new JPanel(new GridLayout(3,2,5,5)); 
     for(int i =0;i<6;i++){ 
      right.add(getLbl()); 
     } 

     c.weightx = 0; 
     c.gridwidth = 1; 
     c.gridy++; 
     c.fill = GridBagConstraints.NONE; 
     c.anchor = GridBagConstraints.WEST; 
     add(left,c); 

     c.anchor = GridBagConstraints.EAST; 
     c.gridx++; 
     add(right,c); 
    } 


    private JLabel getLbl() { 
     JLabel l = new JLabel(" "); 
     l.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 
     return l; 
    } 

    public static void main(String args[]) { 
     new TestFrame(); 
    } 

} 

enter image description here

+0

我忘了寫這可能是一個簡單的GUI計算器 - 位於JButton下面的頂層JTextField中。其實我正在學習和測試網格和流佈局。 – daryl691 2014-10-29 14:59:50

+0

現在您已經知道如何佈置組件,將標籤更改爲文本框/按鈕 – alex2410 2014-10-29 15:01:54