マウスをテーブルに向けます。
package test;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class SingleCellColor {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String[][] data = {
{"a", "1","2","3"},
{"b", "3","4","5"},
{"c", "6","7","8"}
};
String[] columns = {
"Letter", "Num 1", "Num2 ", "Num 3"
};
DefaultTableModel tableModel = new DefaultTableModel(data, columns);
final SingleCellRenderer renderer = new SingleCellRenderer();
final JTable table = new JTable(tableModel);
table.setDefaultRenderer(new Object().getClass(), renderer);
table.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent me) {
Point p = me.getPoint();
renderer.setColumnHightlight(table.columnAtPoint(p));
renderer.setRowHighlight(table.rowAtPoint(p));
table.repaint();
}
});
JScrollPane tableScroll = new JScrollPane(table);
JOptionPane.showMessageDialog(null, tableScroll);
}
});
}
}
class SingleCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
int rowHighlight = -1;
int colHighlight = -1;
@Override
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
c.setBackground(Color.ORANGE);
if (c instanceof JComponent) {
boolean isFocused = (colHighlight == column && rowHighlight == row);
((JComponent)c).setOpaque(isFocused);
}
return c;
}
public void setColumnHightlight(int colHighlight) {
this.colHighlight = colHighlight;
}
public void setRowHighlight(int rowHighlight) {
this.rowHighlight = rowHighlight;
}
}
prepareRendererできること+1 – mKorbel
これにはどのような解決策がありますか?レンダラーをテーブル全体ではなく1つのセルだけに設定する方法はありますか? – Dave
私は居住者のJTableの専門家、@ mKorbelに、気にしなければこれに対処するように頼むつもりです。 –