2017-03-06 68 views
0

我嘗試啓動一個「JTable」,我通過表單設計器添加了所有元素,並在GUI的主要功能中啓動了它們。Jtable不加載

該表放置在「JScrollPanel」中,並使用「DefaultTableModel」添加標題和行。

無論我做了什麼,我都無法讓表格顯示標題或行。
我在這裏錯過了什麼?

class Controls extends JPanel{ 
    private JButton compileButton; 
    private JPanel controls; 
    private JTabbedPane tabbedPane1; 

    private JButton insertButton; 
    private JTable insertedFilesTable; 
    private JScrollPane insertedFilesViewport; 
    private JPanel minify; 
    private JFileChooser insertChooser; 

    public Controls() { 
     insertChooser = new JFileChooser(); 

     compileButton.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       initCompile(); 
      } 
     }); 

     insertButton.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       buttonActionPerformed(e); 
      } 
     }); 
    } 

    public void main() { 
     JFrame frame = new JFrame("Controls"); 

     frame.setLayout(new SpringLayout()); 
     frame.setContentPane(new Controls().controls); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     DefaultTableModel model = new DefaultTableModel(); 

     model.addColumn("Files"); 
     model.addColumn("Status"); 

     insertedFilesTable = new JTable(model); 

     insertedFilesViewport = new JScrollPane(insertedFilesTable); 
     insertedFilesViewport.setViewportView(insertedFilesTable); 
     insertedFilesTable.setFillsViewportHeight(true); 

     String[] data = {"test","test"}; 
     model.addRow(data); 

     frame.add(insertedFilesViewport); 

     frame.setSize(500,500); 
     frame.setVisible(true); 
    } 

    private void buttonActionPerformed(ActionEvent evt) { 
     insertChooser.showSaveDialog(this); 
    } 
} 

My result

+0

你能否請包括完整的代碼? – frederick99

+0

@ frederick99我添加了全班 –

+1

您的圖片與您的代碼不符。您的代碼將JScrollPane直接添加到JFrame,但圖像清晰地顯示在JTabbedPane中。編輯你的問題,並顯示你實際使用的代碼來建立你的窗口。不要讓我們試圖排除你實際上沒有做的事情。 – VGR

回答

1
frame.setLayout(new SpringLayout()); 

.... 

frame.add(insertedFilesViewport); 

不要更改幀SpringLayout中的佈局。沒有理由這樣做。

您看不到滾動窗格包含表的原因是因爲您沒有對add(...)方法使用任何約束。閱讀Swing教程How to Use SpringLayout中的部分,瞭解添加組件的限制有多複雜。

如果離開了佈局作爲默認BorderLayout,則組件將被默認添加到BorderLayoutCENTER。上面的教程還有一個關於How to Use BorderLayout的部分,你應該閱讀。