简体   繁体   English

在JTable(JAVA)的列中添加JButton

[英]Adding JButton in a column in JTable (JAVA)

I am currently reading an excel sheet ( .xls ) and placing it in a JTable . 我目前正在阅读Excel工作表( .xls ),并将其放置在JTable The excel sheet consists of 3 columns. Excel工作表由3列组成。 I am successfully able to read it. 我可以成功阅读。 However, when reading the excel sheet, I want to add an extra fourth column in the JTable that includes JButtons (One button for each row). 但是,在阅读excel工作表时,我想在JTable中添加额外的第四列,其中包括JButtons (每行一个按钮)。 When JButton is clicked in a row, I want to take the content of the third column and perform some action. 当连续单击JButton ,我想获取第三列的内容并执行一些操作。
I am currently using the code from here . 我目前正在从这里使用代码。

What is the best way to add JButtons in a JTable column? JTable列中添加JButtons的最佳方法是什么?

You can add your button this way. 您可以通过这种方式添加按钮。

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;
    }

and to add action listener do this 并添加动作监听器

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));

You can create a class extending JButton. 您可以创建一个扩展JButton的类。 Then add property to that class.(field with getter and setter) when you adding data to the table, add JButton instance for each row using your custom JButton class and set value in the third column using setter method. 然后在向表中添加数据时,向该类中添加属性。 So you can use that value in processing in the click event. 因此,您可以在click事件中使用该值进行处理。 Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM