gpt4 book ai didi

java - 在 JTable 中使 JButton 可点击

转载 作者:IT老高 更新时间:2023-10-28 20:45:34 26 4
gpt4 key购买 nike

这是我想做的截图:

enter image description here

那里发生的事情是 JButton 正确显示,但是当我单击它时没有任何反应。经过一番搜索,我发现 table.getValueAt() 返回的 Object 是 String 而不是 JButton...

代码如下:

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

我使用它在运行时填充 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));
}}
);

这里是 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;
}


}

最后,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();
}

}
}
}

我是 Java 新手,非常感谢您的帮助 :)

提前致谢!

最佳答案

这个 Table Button Column Rob Camick 提供的可能满足您的需求。

关于java - 在 JTable 中使 JButton 可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10347983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com