java swing将背景更改为选定单元格(无列或行)

时间:2017-10-17 15:47:30

标签: java swing jtable

此代码更改了所有列的颜色,我需要在时间更改单个单元格颜色。此代码创建一个表并安装一个TableCellRenderer来修改列颜色。它有两个按钮来执行此操作。代码单独说话。

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

  import javax.swing.*;
  import javax.swing.table.*;
  import java.awt.event.*;

  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());
  BoardTableCellRenderer mcr = new BoardTableCellRenderer();
  table.setFocusable(true);
  table.setShowGrid(false);
  table.setRowMargin(0);
  table.setIntercellSpacing(new Dimension(0, 0));
  table.setRowSelectionAllowed(false);
    table.setFillsViewportHeight(true);
  table.setVisible(true);
  //this.add(table);
   this.setPreferredSize(new Dimension(table.getPreferredSize().width,
           (table.getPreferredSize().height + 85)));
  javax.swing.JButton b = new javax.swing.JButton("bottone");
  b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
          //table.setDefaultRenderer(String.class, new BoardTableCellRenderer());   
          table.getColumnModel().getColumn(table.getSelectedColumn()).setCellRenderer(mcr);
          table.revalidate(); table.repaint();  
    }
  });
  javax.swing.JButton b1 = new javax.swing.JButton("bottone default");
  b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
          table.setDefaultRenderer(String.class, new DefaultTableCellRenderer());   
          table.revalidate(); table.repaint();  
    }
  });

    /*for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex ++) {
        table.getColumnModel().getColumn(columnIndex).setCellRenderer(mcr);
    }*/
    //JScrollPane p1 = new JScrollPane();
    //p1.add(table);
  add(b, BorderLayout.SOUTH); // e.g. for the button
  add(b1, BorderLayout.NORTH); // e.g. for the button

    add(table, BorderLayout.CENTER); // e.g. for the button

  }

 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);
  TableModel t = table.getModel();
  Object valueAt = table.getModel().getValueAt(row, col);
  String s = "";
  if (valueAt != null) {
     s = valueAt.toString();
  }

//if (isSelected) {
//  System.out.println("row: "+row+" "+"col: "+col);
    if (col == 0 && row == 0) {
        c.setForeground(Color.YELLOW);
        c.setBackground(Color.gray); 
    }   
//}

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

1 个答案:

答案 0 :(得分:2)

  

此代码更改了所有列的颜色

列中的所有单元格都使用相同的渲染器。

所以你需要类似的代码:

if (!isSelected)
{
    if (your special condition)
    {
        c.setBackground(...);
    }
    else  // reset background to the default
    {
        c.setBackground(table.getBackground();
    }
}