继续我之前的帖子,只是帮我提一下单击按钮选择单元格的想法。
我们的想法是使用getTableCellRendererComponent,但正在使用TableColumn类来选择整个Column。那么如何使用只突出显示单元格
Prob1:需要在按钮点击时突出显示一个单元格 问题2:在没有解决上述问题的情况下,我无法继续进行项目。请帮忙。
礼貌:@Zyion
包帮助;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Main extends JFrame {
public Main() {
super("Table Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setLocationRelativeTo(null);
setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.setColumnCount(5);
model.setRowCount(5);
JTable table = new JTable();
table.setModel(model);
//Get an instance of the column and the style to apply and hold a default style instance
final TableColumn column = table.getColumnModel().getColumn(1);
final CellHighlighterRenderer cellRenderer = new CellHighlighterRenderer();
final TableCellRenderer defaultRenderer = column.getCellRenderer();
//Now in your button listener you can toggle between the styles
JButton button = new JButton("Click!");
button.addActionListener(new ActionListener() {
private boolean clickedd = false;
public void actionPerformed(ActionEvent e) {
if (clickedd) {
column.setCellRenderer(cellRenderer);
clickedd = false;
} else {
column.setCellRenderer(defaultRenderer);
clickedd = true;
}
repaint(); //edit
}
});
getContentPane().add(table, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.NORTH);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
class CellHighlighterRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object obj,
boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, 1, 0);
//add condition for desired cell
// if (row == 1 && column == 1)
cell.setBackground(Color.YELLOW);
return cell;
}
}