我的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,并使用了一个私有类MyTableModel,该类继承了AbstractTableModel,以便我创建一个不可编辑的表。
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 放到 JScrollPane
-
不要忘记使用适当的布局管理器将
JScrollPane
放入 JPanel,我看不到您在那里添加了JTable
到JPanel
,不确定新GridLayout(3,2)
是否适合LayoutManager
JTable view