在 Swing(NetBeans 15,Sun JDK 19.0.1)中制作 GUI,我正在嘗試為 JTable 行設定自定義背景顏色并遇到布爾單元格的問題,我似乎無法使背景統一所有細胞。請注意,以下代碼嘗試為整個表格繪制背景,但我的目標是一次為一行設定背景;這段代碼的唯一目的是突出 Nimbus 交替行著色和我個人遇到的自定義渲染器之間的奇怪互動。
這個問題似乎已經大量記錄,這是我嘗試過的:
第一次嘗試
c.setOpaque(true);
第二次嘗試,通過
奇怪的是,如果我選擇一個單元格,整行都會得到正確的背景,包括布爾單元格:

我發現的最后一條相關資訊是,在 setBackground() 方法的 javadoc 中:It is up to the look and feel to honor this property, some may choose to ignore it.這讓我懷疑這甚至可以在沒有將 Nimbus 換成其他東西的情況下作業。
我的結論:無論我將渲染指令放在哪里,我都只能設法更改不在交替行之一上的布林值的背景,除非選擇了該行。
問題:我是否錯過了一些明顯的主要配置步驟?或者也許有辦法禁用 Nimbus 的表格交替行顏色?或者,這是某種已知問題嗎?
(更多的答案: 這不相關; 這不起作用;)
編輯:添加了 SSCCE,盡管從 IDE 制作的 GUI 代碼遠非短。
package tabletest;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
// attempt #1
/*
jTable1.setDefaultRenderer(Boolean.class, new MyTableRenderer(jTable1.getDefaultRenderer(Boolean.class)));;
jTable1.setDefaultRenderer(String.class, new MyTableRenderer(jTable1.getDefaultRenderer(String.class)));;
*/
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable() {
//attempt #2
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
//((JComponent)c).setOpaque(true);
c.setBackground(Color.red);
return c;
}
}
;
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{ new Boolean(true), new Integer(1), new Float(0.1), "asd"},
{ new Boolean(true), new Integer(2), new Float(0.2), "lol"},
{null, new Integer(3), new Float(0.3), "xd"},
{null, new Integer(4), new Float(0.4), "ftw"},
{null, new Integer(5), new Float(0.5), "wtf"}
},
new String [] {
"bool", "int", "float", "string"
}
) {
Class[] types = new Class [] {
java.lang.Boolean.class, java.lang.Integer.class, java.lang.Float.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(174, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(100, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
//attempt #1
class MyTableRenderer implements TableCellRenderer {
private final TableCellRenderer renderer;
public MyTableRenderer(TableCellRenderer renderer) {
this.renderer = renderer;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
//c.setOpaque(true);
c.setBackground(Color.red);
return c;
}
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
uj5u.com熱心網友回復:
您在問題中寫道(關于您問題中的代碼):
以下代碼嘗試為整個表格繪制背景
這就是我打算做的。但是,您還寫道:
我的目標是一次為一行設定背景
然后我嘗試了一種不同的方法——它仍然將整個背景涂成紅色,但我希望你能夠調整下面的代碼以滿足你的要求。
第一種方法
詳見此處:
https
://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/color.html
和此處:
https ://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/_nimbusDefaults.html
只需在 class 中設定適當的屬性,就UIManager可以實作[我認為是]您想要的結果,即使整個JTable背景變為紅色。JTable這適用于除顯示Boolean值的第一列之外的所有列。為此,我創建了一個自定義 [table] 單元格渲染器,基于Nimbus外觀使用的渲染器,即:
javax.swing.plaf.synth.SynthTableUI.SynthBooleanTableCellRenderer
這是該渲染器的代碼:
class BoolTableCellRenderer extends JCheckBox implements TableCellRenderer {
private boolean isRowSelected;
public BoolTableCellRenderer() {
setHorizontalAlignment(JLabel.CENTER);
setName("Table.cellRenderer");
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
isRowSelected = isSelected;
if (isSelected) {
setForeground(unwrap(table.getSelectionForeground()));
setBackground(unwrap(Color.red));
}
else {
setForeground(unwrap(table.getForeground()));
setBackground(unwrap(Color.red));
}
setSelected((value != null && ((Boolean)value).booleanValue()));
return this;
}
private Color unwrap(Color c) {
if (c instanceof UIResource) {
return new Color(c.getRGB());
}
return c;
}
public boolean isOpaque() {
return true;
}
}
我還寫了一個自定義TableModel。
class PrimitivesTableModel extends DefaultTableModel {
public PrimitivesTableModel(Object[][] data, Object[] columnNames) {
super(data, columnNames);
}
public Class<?> getColumnClass(int columnIndex) {
Class<?> columnClass;
switch (columnIndex) {
case 0:
columnClass = Boolean.class;
break;
case 1:
columnClass = Integer.class;
break;
case 2:
columnClass = Float.class;
break;
case 3:
columnClass = String.class;
break;
default:
columnClass = Object.class;
}
return columnClass;
}
}
這是第一種方法的代碼:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class NewsFram {
private void buildAndDisplayGui() {
JFrame frame = new JFrame("NewsFram");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTable(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTable() {
Object[][] data = new Object[][]{{Boolean.valueOf(true), Integer.valueOf(1), Float.valueOf(0.1f), "asd"},
{Boolean.valueOf(true), Integer.valueOf(2), Float.valueOf(0.2f), "lol"},
{null, Integer.valueOf(3), Float.valueOf(0.3f), "xd"},
{null, Integer.valueOf(4), Float.valueOf(0.4f), "ftw"},
{null, Integer.valueOf(5), Float.valueOf(0.5f), "wtf"}};
String[] columnNames = new String[]{"bool", "int", "float", "string"};
PrimitivesTableModel model = new PrimitivesTableModel(data, columnNames);
JTable table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(Boolean.class, new BoolTableCellRenderer());
JScrollPane scrollPane = new JScrollPane(table);
return scrollPane;
}
public static void main(String[] args) {
UIManager.put("Table:\"Table.cellRenderer\".background", Color.red);
UIManager.put("Table.alternateRowColor", Color.red);
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
break;
}
catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
UnsupportedLookAndFeelException x) {
x.printStackTrace();
}
}
}
EventQueue.invokeLater(() -> new NewsFram().buildAndDisplayGui());
}
}
第二種方法
這種方法不會修改UIManager默認值,而是覆寫方法prepareRenderer(在類中JTable)。請注意,此方法還使用與TableModel第一種方法相同的自定義渲染器。
我覆寫了方法prepareRenderer,而不是創建另一個基于NimbusJTable外觀使用的通用單元格渲染器的自定義渲染器,因為該渲染器比.SynthBooleanTableCellRenderer
這是第二種方法的代碼:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.UIResource;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class NewFrame {
private void buildAndDisplayGui() {
JFrame frame = new JFrame("NewFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTable(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JScrollPane createTable() {
Object[][] data = new Object[][]{{Boolean.valueOf(true), Integer.valueOf(1), Float.valueOf(0.1f), "asd"},
{Boolean.valueOf(true), Integer.valueOf(2), Float.valueOf(0.2f), "lol"},
{null, Integer.valueOf(3), Float.valueOf(0.3f), "xd"},
{null, Integer.valueOf(4), Float.valueOf(0.4f), "ftw"},
{null, Integer.valueOf(5), Float.valueOf(0.5f), "wtf"}};
String[] columnNames = new String[]{"bool", "int", "float", "string"};
PrimitivesTableModel model = new PrimitivesTableModel(data, columnNames);
@SuppressWarnings("serial")
JTable table = new JTable(model) {
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Object value = getValueAt(row, column);
boolean isSelected = false;
boolean hasFocus = false;
// Only indicate the selection and focused cell if not printing
if (!isPaintingForPrint()) {
isSelected = isCellSelected(row, column);
boolean rowIsLead = (selectionModel.getLeadSelectionIndex() == row);
boolean colIsLead = (columnModel.getSelectionModel().getLeadSelectionIndex() == column);
hasFocus = (rowIsLead && colIsLead) && isFocusOwner();
}
Component cmpt = renderer.getTableCellRendererComponent(this,
value,
isSelected,
hasFocus,
row,
column);
if (!(value instanceof Boolean)) {
cmpt.setBackground(Color.red);
}
return cmpt;
}
};
table.setDefaultRenderer(Boolean.class, new BoolTableCellRenderer());
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
return scrollPane;
}
public static void main(String[] args) {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
break;
}
catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
UnsupportedLookAndFeelException x) {
x.printStackTrace();
}
}
}
EventQueue.invokeLater(() -> new NewFrame().buildAndDisplayGui());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529939.html
標籤:爪哇摇摆布尔值表雨云
