簡體   English   中英

JTable 單元格渲染器

[英]JTable Cell Renderer

我正在關注我找到的一些代碼,(是的,我了解它是如何工作的)它來自這里: 代碼鏈接

如果單元格值設置為“黃色”,我想要做的是設置單元格前景色

這是我的代碼:

public class Board extends JPanel{

private static final long serialVersionUID = 1L;

int boardHeight = 20;
int boardWidth = 10;

JTable table;

public Board() {
    table = new JTable(this.boardHeight, this.boardWidth);
    table.setDefaultRenderer(String.class, new BoardTableCellRenderer());
    table.setFocusable(false);
    table.setShowGrid(false);
    table.setRowMargin(0);
    table.setIntercellSpacing(new Dimension(0,0));
    table.setRowSelectionAllowed(false);
    table.setVisible(true);
    this.add(table);
    this.setPreferredSize(new Dimension(table.getPreferredSize().width, (table.getPreferredSize().height + 85)));
}

public void paint(Graphics g) {
    table.setRowHeight(20);
    for (int x = 0; x < this.table.getColumnCount(); ++x) {
        TableColumn col = this.table.getColumnModel().getColumn(x);
        col.setPreferredWidth(20);
    }
}
}

和單元格渲染器

public class BoardTableCellRenderer extends DefaultTableCellRenderer {

private static final long serialVersionUID = 1L;

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row,int col) {

    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
    String s = table.getModel().getValueAt(row, col).toString();

    if (s.equalsIgnoreCase("yellow")) {
        c.setForeground(Color.YELLOW);
    }
    else {
        c.setForeground(Color.WHITE);
    }

    return c;
}
}

問題是它沒有改變,如果我將任何單元格值設置為“黃色”

提前致謝!

您的渲染器是否曾經使用過? 您將其設置為包含字符串的單元格的默認渲染器,但是您是否重載了模型的getColumnClass方法,以便它知道某些單元格包含字符串?

所以首先我會使用 println 語句來查看渲染器是否被調用,如果沒有,我會覆蓋我的模型的方法,如上所述。

編輯 1
你的 if 結果也一定很奇怪。 在 if 部分更改前景,在 else 更改背景 - 沒有意義。 您可能應該在 if 與 else 塊中對 state 進行補充更改,而不是正交更改。

編輯 2
例如:

import java.awt.*;
import java.util.Random;

import javax.swing.*;
import javax.swing.table.*;

public class Board extends JPanel {

   private static final long serialVersionUID = 1L;

   int boardHeight = 20;
   int boardWidth = 10;

   JTable table;
   Random random = new Random();

   public Board() {
      setLayout(new BorderLayout()); // !!
      DefaultTableModel model = new DefaultTableModel(boardHeight, boardWidth) {
         @Override
         public Class<?> getColumnClass(int columnIndex) {
            return String.class;
         }
      };
      // !! table = new JTable(this.boardHeight, this.boardWidth);
      table = new JTable(model);
      for (int row = 0; row < model.getRowCount(); row++) {
         for (int col = 0; col < model.getColumnCount(); col++) {
            String s = random.nextBoolean() ? "red" : "yellow";
            model.setValueAt(s, row, col);
         }
      }
      table.setDefaultRenderer(String.class, new BoardTableCellRenderer());

      table.setFocusable(false);
      table.setShowGrid(false);
      table.setRowMargin(0);
      table.setIntercellSpacing(new Dimension(0, 0));
      table.setRowSelectionAllowed(false);
      table.setVisible(true);
      this.add(table);
      this.setPreferredSize(new Dimension(table.getPreferredSize().width,
               (table.getPreferredSize().height + 85)));
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("Board");
      frame.getContentPane().add(new Board());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class BoardTableCellRenderer extends DefaultTableCellRenderer {

   private static final long serialVersionUID = 1L;

   public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int col) {

      Component c = super.getTableCellRendererComponent(table, value,
               isSelected, hasFocus, row, col);
      Object valueAt = table.getModel().getValueAt(row, col);
      String s = "";
      if (valueAt != null) {
         s = valueAt.toString();
      }

      if (s.equalsIgnoreCase("yellow")) {
         c.setForeground(Color.YELLOW);
         c.setBackground(Color.gray);
      } else {
         c.setForeground(Color.black);
         c.setBackground(Color.WHITE);
      }

      return c;
   }
}

添加這一行:

c.setOpaque(true);

getTableCellRendererComponent 返回的組件必須是不透明的,才能看到背景和前景色的變化。 這里的問題也是另一個問題:您正在擴展 DefaultTableCellRenderer(即一個 JComponent),但您正在返回一個沒有 setOpaque 方法的組件。 我會像這樣重構你的代碼:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row,int col) {

    String s = table.getModel().getValueAt(row, col).toString();
    this.setOpaque(true);
    if (s.equalsIgnoreCase("yellow")) {
        this.setForeground(Color.YELLOW);
    }
    else {
        this.setBackground(Color.WHITE);
    }

    return this;
}

這是一個簡單的解決方案,使用 TableCellRenderer 作為內部 class。

    myTable.setDefaultRenderer(Object.class, new TableCellRenderer()
    {
        JLabel comp = new JLabel();
        String val;

        @Override
        public Component getTableCellRendererComponent(
                             JTable table, 
                             Object value, 
                             boolean isSelected, 
                             boolean hasFocus, 
                             int row, 
                             int column)
        {
            comp.setOpaque(true);
            comp.setForeground(Color.BLACK); // text color

            if (value != null)
            {
                val = value.toString();
                comp.setText(val);

                if (val.equalsIgnoreCase("red"))
                {
                    comp.setBackground(Color.RED);
                }
                else if (val.equalsIgnoreCase("yellow"))
                {
                    comp.setBackground(Color.YELLOW);
                }
                else if (val.equalsIgnoreCase("green"))
                {
                    comp.setBackground(Color.GREEN);
                }
                else
                {
                    comp.setBackground(Color.WHITE);
                }
            }
            return comp;
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM