gpt4 book ai didi

java - 如何设置 JTable 列和行的颜色?

转载 作者:搜寻专家 更新时间:2023-11-01 02:33:36 25 4
gpt4 key购买 nike

如何设置JTable列和行的颜色?

最佳答案

这是一个简短的example .

Output

import java.awt.Color;
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class JTableExample extends JFrame {

String[][] data = {{"John", "Sutherland", "Student"},
{"George", "Davies", "Student"},
{"Melissa", "Anderson", "Associate"},
{"Stergios", "Maglaras", "Developer"},
};

String[] fields = {"Name", "Surname", "Status"};

public static void main(String[] args) {
new JTableExample();
}

public JTableExample() {
super();
setSize(150, 150);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
System.exit(0);
}
});
init();
pack();
setVisible(true);
}

private void init() {
final CustomCellRenderer renderer = new CustomCellRenderer();
JTable jt = new JTable(data, fields) {

@Override
public TableCellRenderer getCellRenderer(int row, int column) {
return renderer;
}

};
JScrollPane pane = new JScrollPane(jt);
getContentPane().add(pane);
}


/**
* @author suhas, orwellophile
*
*/
private class CustomCellRenderer extends DefaultTableCellRenderer {

/**
* @see javax.swing.table.DefaultTableCellRenderer#getTableCellRendererComponent(JTable, Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {

Component rendererComp = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);

// Very important to handle selected items (render them inversely colored)
if (isSelected) {
rendererComp.setBackground(getHuedColor(row).darker().darker());
rendererComp.setForeground(getHuedColor(row).brighter().brighter());
}
else {
rendererComp.setBackground(getHuedColor(row).brighter().brighter());
rendererComp.setForeground(getHuedColor(row).darker().darker());
}

return rendererComp;
}

public Color getHuedColor(int hue) {
return new Color(
Color.HSBtoRGB(85 / 360f * hue, 0.7f, 1.0f
));
}
}
}

关于java - 如何设置 JTable 列和行的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3548986/

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