我正在尝试向JTable添加一个删除所选行的侦听器。
我有一个ToolBar类,其中包含所有按钮, 但我的所有JTable设置都在另一个类:TablePanel。
我希望能够在用户点击ToolBar Class中的按钮时删除行。
ToolBar.java
public class ToolBar extends JPanel
{
TablePanel tablePane;
JButton openButton, saveButton, addButton, delButton;
ImageIcon openIcon, saveIcon, addIcon, delIcon;
Image openImage, saveImage, addImage, delImage;
Image openImage2, saveImage2, addImage2, delImage2;
ButtonListener listener;
public ToolBar(TablePanel tablePane)
{
this.tablePane = tablePane;
//Bunch of codes here to initialize all the buttons and icons
}
//Button Listener
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == openButton)
JOptionPane.showMessageDialog(null, "hello");
if (event.getSource() == saveButton)
tablePane.saveData();
if (event.getSource() == addButton)
tablePane.addRow();
if (event.getSource() == delButton)
tablePane.delRow();
}
}
}
TablePanel
public class TablePanel extends JPanel
{
//Table's column name
private ArrayList<String> columnNames = new ArrayList<String>();
//List of data, later needs to be change
//so that it will be editable on the go
//It starts with 5 columns
//User can add more columns
private ArrayList<Object[]> data = new ArrayList<Object[]>();
//DefaultTableModel is needed for adding new rows
private JTable table;
private TModel tModel;
private JScrollPane scrollPane;
//For importing & exporting data
JFileChooser fileChooser;
public TablePanel()
{
//Column Names:
columnNames.add("Date");
columnNames.add("Category");
columnNames.add("Details");
columnNames.add("Add/Subtract");
columnNames.add("Total");
//Example data:
data.add(new Object[]{20140925, "Grocery", "Supermarket", -5.23,600.00});
data.add(new Object[]{20141013,"Car Maintenance", "Changing Tires", -200.00, 400.00});
//Some codes here
}
private class TModel extends AbstractTableModel implements TableModelListener
{
//Bunch of codes(methods) in here such as:
//public voide setValueAt, public Boolean isCellEditable, getColumnCount etc.
//Method for deleting row
public void delRow()
{
public void tableChanged(TableModelEvent event)
{
int row = event.getFirstRow();
fireTableRowsDeleted(row, row);
}
}
} //End of TModel class
} //End of TablePanel Class
我应该如何实现listener和fireTableDeleted(int row)? 我应该在 public void delRow()?
中添加什么
答案 0 :(得分:2)
有人需要引用其他人,但您也希望保持一定程度的分离,这样您就不会将组件紧密耦合在一起
您可以使用某种类型的控制器,该控制器具有对该表的引用,并且可以直接监听工具栏上的按钮或工具栏可以调用它并指示它想要执行的操作。
例如,单击时,删除按钮将简单地指示控制器删除所选行&#34;。控制器会要求TablePane
删除选定的行&#34;并且TablePane
会遵守。
这可以通过Actions API实现,其中Action
将充当控制器。
基本上你会创建一个新的DeleteRowAction
(这是你必须要创建的类),它引用了TablePane
并将你传递给ToolBar
窗格。然后,您可以将Action
应用于删除按钮(JButton#setAction
)并让它为您处理其他所有事情