简体   繁体   English

在 JTable 中使 JButton 可点击

[英]Making a JButton clickable inside a JTable

Here is the screenshot of what I want to do :这是我想要做的截图:

在此处输入图像描述

What's happening there is the JButton shows correctly but nothing happens when I click on it.那里发生的事情是 JButton 正确显示,但是当我单击它时没有任何反应。 After some search, I've found that the Object returned by table.getValueAt() is a String instead of a JButton...经过一番搜索,我发现table.getValueAt()返回的Object是 String 而不是 JButton ...

Here is the code :这是代码:

tblResult = new JTable(data,cols) {
    public TableCellRenderer getCellRenderer( int row, int column ) {
        return new ClientsTableRenderer();
    }
};

I use this for populating at run-time the JTable : ( tblResult is now Clients.rblResult )我使用它在运行时填充 JTable :( tblResult现在是Clients.rblResult

SwingUtilities.invokeLater( new Runnable() {
    public void run() { 

        DefaultTableModel aModel = new DefaultTableModel() {
            //setting the jtable read only
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }               
        };


    String[] cols = {"N°","Société", "TVA", "CP", "Ville", ""};
    aModel.setColumnIdentifiers(cols);

    Object[] temp = new Object[6];
    for(int i=0;i<result.length;i++) {

        temp[0] = result[i].custNumber;
        temp[1] = result[i].name;
        temp[2] = result[i].tva;
        temp[3] = result[i].cp;
        temp[4] = result[i].city;
        temp[5] = "Consulter";

        aModel.addRow(temp);

    }

    Clients.tblResult.setModel(aModel);

    Clients.tblResult.addMouseListener(new JTableButtonMouseListener(Clients.tblResult));
    }}  
); 

Here the ClientsTableRenderer class这里是ClientsTableRenderer

public class ClientsTableRenderer extends JPanel implements TableCellRenderer {
    @Override
    public Component getTableCellRendererComponent( final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        setBackground(Color.WHITE);
        if(column < 5) {
            JLabel label =  new JLabel(value.toString());
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,0,9));
            panel.setBackground(Color.WHITE);
            panel.add(label);
            this.add( panel);
        } else {

            JButton button = new JButton(value.toString());
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    System.out.println("Clicked !");
                }
            });
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,0,3));
            panel.setBackground(Color.WHITE);
            panel.add(button);
            this.add(panel);
        }


        return this;
    }


}

And finaly, the JTableButtonMouseListener() :最后, JTableButtonMouseListener() :

public class JTableButtonMouseListener extends MouseAdapter {
      private final JTable table;

      public JTableButtonMouseListener(JTable table) {
        this.table = table;
      }

      @Override public void mouseClicked(MouseEvent e) {
        int column = table.getColumnModel().getColumnIndexAtX(e.getX());
        int row    = e.getY()/table.getRowHeight(); 
        System.out.println("Col :"+column + "row:"+row);

        if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
          Object value = table.getValueAt(row, column);
          System.out.println("Value :"+value.getClass().getName());
          if (value instanceof JButton) {
            ((JButton)value).doClick();
          }

        }
      }
    }

I'm kindly new to Java, help would be very much appreciated :)我是Java的新手,非常感谢您的帮助:)

Thanks in advance !提前致谢 !

这个来自 Rob Camick 的 表格按钮列可能适合您的需求。

The problem is that the JButton no longer exists when painted in the table.问题是JButton在表格中绘制时不再存在。 Those components are only used to create a 'stamp' when the table is rendered.这些组件仅用于在呈现表格时创建“印章”。 There is no actual button present.没有实际的按钮。

There is a way to allow you to click on the button, and still keep your table non-editable , but it is far from proper code.有一种方法可以让您单击按钮,并且仍然保持表格不可编辑,但它与正确的代码相去甚远。 Just a quick outline for a possible solution (I do not have the time at this moment to give a full code example)只是一个可能的解决方案的简要概述(我现在没有时间给出完整的代码示例)

  • attach a mouse listener to the table将鼠标侦听器附加到表格
  • when you receive a mouse click, determine the cell in which the mouse click occurred当您收到鼠标点击时,确定发生鼠标点击的单元格
  • ask the table renderer for the component for that cell向表格渲染器询问该单元格的组件
  • use the location of the mouse click to determine whether a button is present in the component from the previous step at that particular location使用鼠标单击的位置来确定按钮是否存在于上一步的组件中的特定位置
  • if so, do the click through the button api (the doClick method)如果是这样,请通过按钮 api 进行单击( doClick方法)

And this is not even the dirty part of the code.这甚至不是代码的脏部分。 Since your renderer (hopefully) does not return a new JButton each time, you should in your ActionListener which is attached to the JButton keep track of for which component the click actually occurred.由于您的渲染器(希望)不会每次都返回一个新的JButton ,因此您应该在附加到JButtonActionListener中跟踪实际发生单击的组件。 A possible solution is to keep a reference to the table model value for which you the last time created a JButton (so in the getCellRendererComponent method keep track of the row/column), but I am unsure whether this is the best approach.一种可能的解决方案是保留对您上次为其创建JButton的表模型值的引用(因此在getCellRendererComponent方法中跟踪行/列),但我不确定这是否是最佳方法。

As said, a possible solution but far from elegant.如前所述,一个可能的解决方案,但远非优雅。

The easiest way is to just make that one column editable and use an editor, as pointed out in other answers正如其他答案中所指出的那样,最简单的方法是使一列可编辑并使用编辑器

Try this:尝试这个:

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

public class TableWithButtonDemo
{
  private JFrame frame = new JFrame("Table Demo");
  private String[] columnNames = { "String", "Integer", "Float", "" };
  private Object[][] data = { { "Dummy", new Integer(12), new Float(12.15), "Consulter" } };
  private TableModel model = new DefaultTableModel(data, columnNames)
  {
    private static final long serialVersionUID = 1L;

    public boolean isCellEditable(int row, int column)
    {
      return column == 3;
    }
  };
  private JTable table = new JTable(model);

  public TableWithButtonDemo()
  {
    table.getColumnModel().getColumn(3).setCellRenderer(new ClientsTableButtonRenderer());
    table.getColumnModel().getColumn(3).setCellEditor(new ClientsTableRenderer(new JCheckBox()));
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    table.setShowHorizontalLines(true);
    table.setShowVerticalLines(false);

    JScrollPane scroll = new JScrollPane(table);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(scroll);
    frame.pack();
    frame.setLocation(150, 150);
    frame.setVisible(true);
  }

  public static void main(String[] args) throws Exception
  {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    EventQueue.invokeLater(new Runnable()
    {
      public void run()
      {
        new TableWithButtonDemo();
      }
    });
  }

  class ClientsTableButtonRenderer extends JButton implements TableCellRenderer
  {
    public ClientsTableButtonRenderer()
    {
      setOpaque(true);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
      setForeground(Color.black);
      setBackground(UIManager.getColor("Button.background"));
      setText((value == null) ? "" : value.toString());
      return this;
    }
  }
  public class ClientsTableRenderer extends DefaultCellEditor
  {
    private JButton button;
    private String label;
    private boolean clicked;
    private int row, col;
    private JTable table;

    public ClientsTableRenderer(JCheckBox checkBox)
    {
      super(checkBox);
      button = new JButton();
      button.setOpaque(true);
      button.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          fireEditingStopped();
        }
      });
    }
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    {
      this.table = table;
      this.row = row;
      this.col = column;

      button.setForeground(Color.black);
      button.setBackground(UIManager.getColor("Button.background"));
      label = (value == null) ? "" : value.toString();
      button.setText(label);
      clicked = true;
      return button;
    }
    public Object getCellEditorValue()
    {
      if (clicked)
      {
        JOptionPane.showMessageDialog(button, "Column with Value: "+table.getValueAt(row, 1) + " -  Clicked!");
      }
      clicked = false;
      return new String(label);
    }

    public boolean stopCellEditing()
    {
      clicked = false;
      return super.stopCellEditing();
    }

    protected void fireEditingStopped()
    {
      super.fireEditingStopped();
    }
  }

}

This articles provides an easier approach to your problem without adding MouseListeners and computing if the click is actually on the button or not:本文提供了一种更简单的方法来解决您的问题,而无需添加 MouseListener 并计算单击是否实际在按钮上:

http://web.archive.org/web/20100623105810/http://ivolo.mit.edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx http://web.archive.org/web/20100623105810/http://ivolo.mit.edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx

Overload your Table model, and set isCellEditable(int, int) return false for the cells with buttons.重载您的 Table 模型,并为带有按钮的单元格设置 isCellEditable(int, int) return false。

It works great in with a MouseListener added to the table.它非常适合添加到表中的 MouseListener。

Here is my solution这是我的解决方案

ButtonEditor.java按钮编辑器.java

public abstract class ButtonEditor extends DefaultCellEditor implements ActionListener {
private static final long serialVersionUID = 1L;

/** The cell's row. */
protected int row;

/** The cell's column. */
protected int column;

/** The cell's column. */
protected JTable table;

/** The button we are editing. */
protected JButton button;

/** The panel used when editing. */
protected JPanel panel = new JPanel(new GridBagLayout());

/** Constructor */
public ButtonEditor() {super(new JCheckBox());}

/**
 * This method is called when the user try to modify a cell. 
 * In this case it will be called whenever the user click on the cell.
 * @param table
 * @param value
 * @param isSelected
 * @param row
 * @param column
 * @return JPanel The JPanel returned contains a JButton with an ActionListener. 
 */
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
    this.row = row;
    this.column = column;
    this.table = table;
    button = (JButton) value;

    //prevent to add the action listener everytime the user click on the cell.
    if(button.getActionListeners().length == 0) button.addActionListener(this); 

    panel.add(button);
    panel.setBackground(table.getGridColor());
    return panel;
}

/**
 * Return a renderer for JButtons. The result is a button centered in the table's cell.
 * @return
 */
public static TableCellRenderer getRenderer() {
    return new TableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            JPanel panel = new JPanel(new GridBagLayout());
            panel.add((JButton) value);
            panel.setBackground(table.getGridColor());
            return panel;
        }
    };
}

} }

And here is how to use it:以下是如何使用它:

Demo.java演示.java

    table.setDefaultRenderer(JButton.class, ButtonEditor.getRenderer()); 
    table.setDefaultEditor(JButton.class, new ButtonEditor() {
        @Override
        public void actionPerformed(ActionEvent e) {

            //handle clicks here. for example:   
            if(column == 5) {
                System.out.Println(row);
                button.setFocusPainted(false);                  
            }
        }
    });

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

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