【问题标题】:Returning a JTable from the JPanel class within the table从表中的 JPanel 类返回 JTable
【发布时间】:2013-09-14 18:47:40
【问题描述】:

我有追随者类,我想获得其中的JTable

public class TimeTable extends JPanel
{
private JTable table;

public TimeTable (int semestre)
{

    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 
    table = new JTable(new MyTableModel()); 
    table.setFillsViewportHeight(true);     
    table.setPreferredScrollableViewportSize(new Dimension(510, 350));  //imposta le dimensioni della tabella
    JScrollPane jps = new JScrollPane(table);
    add(jps);
    add(new JScrollPane(table));
    table.setCellSelectionEnabled(true);
    table.setRowHeight(40);
    TableColumn tcol;
    for (int i=0; i<table.getColumnCount(); i++)
    {
        tcol = table.getColumnModel().getColumn(i);
        tcol.setCellRenderer(new CustomTableCellRenderer());

    }
}
public class MyTableModel extends AbstractTableModel {//instructions that customize my table}
public class CustomTableCellRenderer extends DefaultTableCellRenderer{//other instructions that customize my table }
}

请注意,我不想在 Frame 中看到表格。我还没有这样做:现在我需要在表中添加一个MouseListener,而我拥有的类是一个JPanel 扩展。 我该怎么做?

【问题讨论】:

    标签: java swing object jtable jpanel


    【解决方案1】:

    TimeTable添加getter方法:

    public class TimeTable extends JPanel {
        private JTable table;
        ...
    
        public JTable getTable() {
            return table;
        }
        ...
    }
    

    如果你有 TimeTable 引用,那么你可以获得 JTable 实例:

    TimeTable timeTable = new TimeTable(42);
    ...
    JTable table = timeTable.getTable();
    

    【讨论】:

    • 这就是我所做的......但它被要求定义静态方法。现在不是......这很奇怪。顺便感谢(再次)你
    • 不客气。如果编译器告诉你一个方法不能被调用,因为它不是static,这意味着你试图从一个静态上下文中调用一个实例方法。通常不需要这样做,因为通常大多数代码属于对象(main() 是唯一的静态方法并不罕见)。
    猜你喜欢
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    相关资源
    最近更新 更多