我有两个问题
1.我想在鼠标单击时更改 JTable 单元格的颜色。我添加了一个监听器,比如在两种颜色之间切换,如果当前它是绿色,它应该在其他点击时转向吹气
String[][] data = new String[rows][columns];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
table.addMouseListener(new CellClickListener());
// Using following MouseListener
public class CellClickListener extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
// How to getCell object here and change its background color to clicked cell
}
}
2.如何设置不同的列宽,如firstColumn.setWidth(20)
, secondColumn.setWidth(40)
。我已经禁用了自动调整大小 table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
最佳答案
您必须创建自己的 CellRenderer 并使用 MouseAdapter
这是一个 SSCCE 来阐明我的意思:
希望对您有所帮助 =)
public class JTableTest extends JFrame {
private JPanel contentPane;
private JScrollPane scrollPane;
private JTable table;
private int col;
private int rowz;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
teste frame = new teste();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTableTest() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
table = new JTable();
table.setModel(new DefaultTableModel(new Object[][] { { "", null, null, "" }, { null, null, null, null }, { null, null, null, "" },
{ null, null, null, null }, }, new String[] { "Column 0", "Column 1", "Column 2", "Column 3" }));
table.getColumnModel().getColumn(0).setMinWidth(200); // Here's how to
// change a
// column width
scrollPane.setViewportView(table);
table.setDefaultRenderer(Object.class, new CustomModel());
table.addMouseListener(new CustomListener());
}
public class CustomListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
super.mouseClicked(arg0);
// Select the current cell
rowz = table.getSelectedRow();
col = table.getSelectedColumn();
// Repaints JTable
table.repaint();
}
}
public class CustomModel extends DefaultTableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Color c = Color.WHITE;
if (isSelected && row == rowz & column == col)
c = Color.GREEN;
label.setBackground(c);
return label;
}
}
}
关于java - 更改单击的 JTable 单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22226575/