我的JTable沒有顯示出來。我不知道爲什麼。也許你可以幫助我。我有一個窗口類,它有一個右側面板,右側面板應該顯示一個包含模型數據的表格。我已經使用虛擬數據開始,如月和日。爲什麼我的JTable沒有顯示出來?
這裏是右側面板類
import model.*;
import java.awt.*;
import java.awt.event.*;
//import java.text.*;
import javax.swing.*;
public class RightPanel extends JPanel implements View
{
private TablePanel songsnartists = new TablePanel();
Shop shop;
public RightPanel(Shop ourShop)
{
shop = ourShop;
setup();
build();
setVisible(true);
}
private void setup()
{
setPreferredSize(new Dimension(300, 300));
setLayout(new GridLayout(3,2));
setBorder(BorderFactory.createLineBorder(Color.blue));
}
private void build()
{
add(songsnartists);
}
public void update()
{}
}
/*很簡單,到目前爲止只是想表面板添加到我的右側面板*/
這裏是我創建的TablePanel類。它繼承JTable並使用繼承AbstractTableModel的私有類MyTableModel,以便創建一個不可編輯的表。
import javax.swing.*;
import javax.swing.table.*;
public class TablePanel extends JTable
{
//private int ROWS = 3;
//private int COLUMNS = 2;
private final String [][] data = {{"Jan", "31"}, {"Feb","28"},{"Mar","31"}};
private final String[] headers = {"Month", "Days"};
JTable table;
public TablePanel()
{
table = new JTable(new MyTableModel(data, headers));
JTableHeader header = table.getTableHeader();
//header.setBackground(Color.blue);
setVisible(true);
}
private class MyTableModel extends AbstractTableModel
{
private String[] columnNames = {"Month", "Days"};
private String[][] data = {{"Jan", "31"}, {"Feb","28"},{"Mar","31"}};
public MyTableModel(String [][] data, String [] header)
{
int rows, cols, rowCounter, colCounter;
rows = getRowCount();
cols = getColumnCount();
for (rowCounter=0; rowCounter < rows; rowCounter++)
{
for (colCounter=0; colCounter < cols; colCounter++)
{
setValueAt(data[rowCounter][colCounter],rowCounter,colCounter);
}
}
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.length;
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int col)
{
return data[row][col];
}
public Class getColumnClass(int c)
{
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col)
{
return false;
}
}
}
正如您所見,抽象方法在私有類中被覆蓋。任何人都可以幫我指出爲什麼我的JTable沒有顯示出來嗎?
那麼......你想讓JTable出現在哪裏? – Tharwen
你是否將RightPanel的一個實例添加到你的框架中?就像現在一樣,您將TablePanel添加到RightPanel中,但是您沒有在任何地方添加RightPanel –