尝试了一切,但我无法在 JTable 标头中获取 JButton。我能够让它在那里显示并使用鼠标侦听器来捕获点击,但没有视觉点击效果。有人可以提供一个简单的例子吗?
问问题
1404 次
1 回答
0
你可以尝试使用这样的东西。此代码使用 JToggleButton 提供视觉效果。
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class Test {
private static JTable table;
public static void main(String[] args) {
table = new JTable(new Object[][]{{1,2},{2,3}},new Object[]
{"test", "test2"});
TableColumn column = table.getColumnModel().getColumn(0);
column.setHeaderRenderer(new BtnRenderer(column.getHeaderValue()));
column = table.getColumnModel().getColumn(1);
column.setHeaderRenderer(new BtnRenderer(column.getHeaderValue()));
table.getTableHeader().addMouseListener(getHeaderMouseListener());
JFrame f = new JFrame();
f.add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
}
private static MouseListener getHeaderMouseListener() {
return new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
if(arg0.getButton() == 1){
int columnAtPoint =
table.columnAtPoint(arg0.getPoint());
/* Get the header portion of the table, and its column model */
JTableHeader header = table.getTableHeader();
TableColumnModel columnModel = header.getColumnModel();
TableColumn column = columnModel.getColumn(columnAtPoint);
BtnRenderer headerRenderer =
(BtnRenderer) column.getHeaderRenderer();
headerRenderer.actionPerformed();
} else {
super.mousePressed(arg0);
}
}
};
}
}
class BtnRenderer implements TableCellRenderer {
private JToggleButton btn;
public BtnRenderer(Object headerValue) {
btn = new JToggleButton();
btn.addActionListener(System.out::println);
btn.setText(headerValue.toString());
}
@Override
public Component getTableCellRendererComponent(
JTable arg0,
Object arg1,
boolean arg2,
boolean arg3,
int arg4,
int arg5) {
return btn;
}
public void actionPerformed() {
btn.setSelected(!btn.isSelected());
}
}
于 2013-10-18T12:02:31.487 回答