2012-03-19 173 views
3

這是我第一次使用GUI,所以我不確定是什麼導致了問題。我有一份來自我的Uni的作業。該項目旨在爲各種目的制定一種「產品管理」計劃。除了GUI之外,整個事情都完成了,這就是我不明白爲什麼JTable不顯示列標題的原因。下面的代碼(順便說一句,使用MIGLayout)JTable不顯示列標題

package sepm.s2012.e0727422.gui; 

import sepm.s2012.e0727422.service.*; 

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

import net.miginfocom.swing.MigLayout; 


public class MainFrame { 

    /** Start all services **/ 
// IProductService ps = new ProductService(); 
// IInvoiceService is = new InvoiceService(); 
// IOrderService os = new OrderService(); 

    /** Frame **/ 
    private JFrame frame; 
    private JTabbedPane tab; 

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


    public MainFrame() { 

     frame = new JFrame("Product control and management system"); 
     frame.setVisible(true); 
     frame.setSize(800, 600); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     /** TABBED PANE options and parameters **/ 
     tab = new JTabbedPane(); 
     ImageIcon icon = null; // TODO 
     tab.addTab("Products", icon, tabProducts(), "Add/Update/Delete products"); 
     tab.addTab("Invoices", icon, tabInvoices(), "Overview of invoices"); 
     tab.addTab("Cart", icon, tabCart(), "Order new products"); 
     tab.setSelectedIndex(0); 

     frame.add(tab, BorderLayout.CENTER); 

    }  
    /** 
    * Products Panel tab 
    * @return panel 
    */ 
    public JPanel tabProducts() { 
     JPanel panel = new JPanel(new MigLayout("","20 [] 20", "10 [] 10 [] 10 [] 10")); 

     JLabel label = new JLabel("List of all available products"); 
     JButton add = new JButton("Add product"); 
     JButton update = new JButton("Update product"); 
     // Below is a test table, will be replace by products in DB 
     String[] tableTitle = new String[] {"ID", "Name", "Type", "Price", "In stock"}; 
     String[][] tableData = new String[][] {{"1", "Item 1", "Type 1", "0.00", "0"}, {"2", "Item 2", "Type 2", "0.00", "0"}, 
               {"3", "Item 3", "Type 3", "0.00", "0"}, {"4", "Item 4", "Type 4", "0.00", "0"}}; 
     JTable table = new JTable(tableData, tableTitle); 

     panel.add(label, "wrap, span"); 
     panel.add(table, "wrap, span"); 
     panel.add(add); 
     panel.add(update); 

     return panel; 
    } 

    public JPanel tabInvoices() { 
     JPanel panel = new JPanel(new MigLayout()); 
     return panel; 
    } 

    public JPanel tabCart() { 
     JPanel panel = new JPanel(new MigLayout()); 
     return panel; 
    } 
} 

回答

4

起初你的表添加到一個JScrollPane:

JScrollPane scrollpane = new JScrollPane(table); 

然後滾動面板添加到您的佈局:

panel.add(scrollpane, "wrap, span"); 

其次,所有的組件添加到框架並使其可見在您的方法結束時:

//... 
frame.add(tab, BorderLayout.CENTER); 

frame.validate(); 
frame.setVisible(true); 
+0

比你多,這個固定的問題。 – vedran 2012-03-19 11:56:26

8

表添加到JScrollPane

該文檔爲JTable狀態:

..請注意,如果你想使用一個JTable獨立視圖JScrollPane之外)並且希望顯示標題,您可以使用getTableHeader()獲取並單獨顯示。