[英]Adding JButton in a column in JTable (JAVA)
我目前正在阅读Excel工作表( .xls ),并将其放置在JTable
。 Excel工作表由3列组成。 我可以成功阅读。 但是,在阅读excel工作表时,我想在JTable
中添加额外的第四列,其中包括JButtons
(每行一个按钮)。 当连续单击JButton
,我想获取第三列的内容并执行一些操作。
我目前正在从这里使用代码。
在JTable
列中添加JButtons
的最佳方法是什么?
您可以通过这种方式添加按钮。
class MyRenderer implements TableCellRenderer {
JButton button = new JButton();
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
button.setText(value.toString());
return button;
}
并添加动作监听器
class mybutttoneditor extends AbstractCellEditor implements TableCellEditor,
ActionListener {
JTable table;
JButton button = new JButton();
public mybutttoneditor(JTable table) {
this.table = table;
button.setFont(new Font("Serif", Font.BOLD, 14));
button.setForeground(Color.blue);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
final int row = table.getEditingRow();
String column3data=table.getValueAt(row, 2);
//do what you want with the data here
//hopefully this helps and if so accept the answer
}
//other abstract methods are here
}
}
DefaultTableModel md=(DefaultTableModel)mytable.getModel();
//do this while reading your excel sheet
Object row[]={"dataone","datatwo","data3","Open Button"};
md.addRow(row);
TableColumnModel colModel = mytable.getColumnModel();
colModel.getColumn(3).setCellRenderer(new MyRenderer());
colModel.getColumn(3).setCellEditor(new mybutttoneditor(mytable));
您可以创建一个扩展JButton的类。 然后在向表中添加数据时,向该类中添加属性。 因此,您可以在click事件中使用该值进行处理。 希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.