2012-04-09 81 views
1

我加入一個JTable到一個JPanel至極使用網格佈局,但我不明白,當你添加一個JButton喜歡同樣的行爲......如何將JTable放入JPanel並使其可自動調整大小?

我想知道我怎樣才能得到相同的自動調整大小行爲與我的JTable一樣,當您將JButton添加到使用GridLayout的JPanel中時,同時我希望該表使用面板的整個空間。

對不起拼寫,英語不是我的母語。希望你們能幫助我!

這是我的代碼:

import javax.swing.*; 
    import java.awt.*; 

    class Frame extends JFrame { 

     private JPanel center; 
     private JTable table; 

     public Frame(){ 
      super("Test Jtable"); 
      this.setLayout(new BorderLayout());   

      this.center = new JPanel(); 
      this.center.setLayout(new GridLayout()); 

      this.table = new JTable(50,50); 
      this.table.setGridColor(Color.black); 
      this.table.setCellSelectionEnabled(true);      

      this.center.add(this.table); 
      this.add(this.center,BorderLayout.CENTER); 
     } 
    } 

    public class TestFrame { 

     public static void main(String... args) { 
      Frame f =new Frame(); 
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      f.setSize(400,400); 
      f.setVisible(true); 
     } 
    } 

回答

1

你的表添加到滾動窗格,如本example

this.center.add(new JScrollPane(this.table)); 

附錄:我主張像這樣使用pack();其他安排是可能的,但可用性較差。 setPreferredScrollableViewportSize()方法也可能有幫助。

import javax.swing.*; 
import java.awt.*; 

class Frame extends JFrame { 

    private JPanel center; 
    private JTable table; 

    public Frame() { 
     super("Test Jtable"); 
     this.setLayout(new BorderLayout()); 
     this.center = new JPanel(); 
     this.center.setLayout(new GridLayout()); 
     this.table = new JTable(50, 10); 
     this.table.setGridColor(Color.black); 
     this.table.setCellSelectionEnabled(true); 
     this.center.add(this.table); 
     this.add(new JScrollPane(this.center), BorderLayout.CENTER); 
    } 
} 

public class TestFrame { 

    public static void main(String... args) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       Frame f = new Frame(); 
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       f.pack(); 
       f.setVisible(true); 
      } 
     }); 
    } 
+0

請注意您的(顯式)'GridLayout'和示例(隱式)'FlowLayout'之間的區別。 – trashgod 2012-04-09 09:15:24

+1

如果將JButton添加到JPanel中,則JButton將佔用JPanel的整個空間,並且在調整窗口大小時,JButton也會自動調整佔用大小。我想對我的JTable做同樣的事情,完全適合JPanel並獲得自動調整大小。 – mrgamertag 2012-04-09 16:29:10

+0

您可能需要組件網格;更上面。 – trashgod 2012-04-09 17:34:03