java AbstractTableModel 2 每行不同的颜色 [英] java AbstractTableModel 2 Different Color For Each Row

查看:29
本文介绍了java AbstractTableModel 2 每行不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提高我的 jtable 的可读性,下面是 MyTableModel.java 类,如何使每一行具有 2 种不同的颜色 如图所示.我可以为每一行赋予不同的颜色以增加用户的可读性应该是什么具体方法.

I want to increase readability of my jtable , here is MyTableModel.java class below , how to make each row with 2 different color shown in this picture . What should be the specific method that I can give different color to each row to increase readability of the user.

      public class MyTableModel extends AbstractTableModel{

   String [] columnNames;
   Vector<Vector<Object>> data;
   public DataAccessObject  ObjDb = new DataAccessObject ();


   public  MyTableModel(String [] coln , Vector<Vector<Object>>  data)
   {

       columnNames = coln;
       this.data =data;

   }

   @Override
        public int getColumnCount() {
            return columnNames.length;
        }

   @Override
        public int getRowCount() {
            return data.size();
        }

   @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data.get(row).get(col);
        }

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }


        public boolean isCellEditable(int row, int col) {

            if (col <= 0) {
                return true;
            } else {
                return true;
            }
        }


        public void setValueAt(Object value, int row, int col) {
            data.get(row).set(col, value);
            fireTableCellUpdated(row, col);
        }




      private class RowListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent event) {
            if (event.getValueIsAdjusting()) {
                return;
            }
//            output.append("ROW SELECTION EVENT. ");
//            outputSelection();
        }
    }

    private class ColumnListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent event) {
            if (event.getValueIsAdjusting()) {
                return;
            }
//            output.append("COLUMN SELECTION EVENT. ");
//            outputSelection();
        }
    }

}

Netbeans 自动创建了我的 jtable,我设置的变量名是 mytable 然后我在下面定义 prepareRenderer 时有问题,我错过了这里的步骤吗?我想做
每一行都有不同的颜色 下面是我的示例代码.

Netbeans automatically created my jtable with variable name I set is mytable then I have problem with defining prepareRenderer below , do I miss step here ? I wanna make
each row with different color Here is my sample code below.

       mytable.prepareRenderer(TableCellRenderer renderer, int row, int column)
        {
            Component c = super.prepareRenderer(renderer, row, column);

            //  Alternate row color

            if (!isRowSelected(row))
                c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);

            return c;
        }
    };

我也用过这个,但这设置了 5 列,我有 7 列,剩下的两列不是
最后着色,当我单击白色行时,文本颜色消失.

I have also use this one but this sets 5 columns i have 7 columns remaining two is not
colored at the end , when I click the white colored row the text color disappears.

 mytable.setDefaultRenderer(Object.class, new TableCellRenderer() {
    private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean      
  isSelected, boolean hasFocus, int row, int column) {
        Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value,             


isSelected, hasFocus, row, column);


        System.out.println(column);

        if (row % 2 == 0) {
            c.setBackground(Color.WHITE);
        } else {
            c.setBackground(Color.LIGHT_GRAY);
        }
        return c;
    }

});

推荐答案

你可以...

使用 SwingLabs、SwingX 库 中的 JXTable,它的功能可以这样做...如果您可以使用 3rd 方库,这将是我的首选解决方案...

You could...

Use JXTable from SwingLabs, SwingX library which has functionality which could do this...this would be my preferred solution if you can use 3rd party libraries...

使用 Nimbus 外观和感觉来实现这一点……但这会妨碍您使用其他外观(如系统外观)

Use Nimbus look and feel which does this...but this precludes you from using other look and feels (like the system look and feel)

创建您自己的一系列自定义 TableCellRenderer 根据当前行为其背景着色...这很乏味,因为您可能需要的每个单元格渲染器都需要能够执行此操作...

Create your own series of custom TableCellRenderers which color their background based on the current row...this is tedious as EVERY cell renderer you might need, needs to be able to perform this operation...

覆盖JTableprepareCellRenderer方法,并根据行强行自己设置单元格渲染器的背景......我不喜欢这个解决方案,因为它将设计选择强加到渲染器上,这可能不符合它的要求(覆盖单元渲染器可能想要的值)并将您锁定到表的特定实现中...

Override the prepareCellRenderer method of the JTable and forcefully set the background of the cell renderer yourself, based on the row...I'm not a fan of this solution, as it's forcing a design choice onto the renderer which might not fit it's requirements (overriding values the cell renderer might want) and locks you into a particular implementation of the table...

创建一个能够与 JTable 对话的 JViewport 并渲染桌子下面的糖果剥离,但是桌子和渲染器需要是透明的......我已经这样做了,它......复杂......但允许我继续剥离视口的整个长度(超出表格的可渲染区域)......

Create a JViewport which was capable of talking with the JTable and rendered the candy stripping underneath the table, but the table and renderers would need to be transparent...I've done this, it's...complicated...but allowed me to continue the candy stripping the full length of the view port (beyond the renderable area of the table)...

更新了 JViewport 示例

Updated with JViewport example

这是我不久前为一个项目实现的概念的一个例子(它实际上由一个 interface 管理,所以我可以包含 JListJTextArea 也是,但这是另一个问题)...

This is an example of a concept I implemented a while ago for a project (it is actually managed by an interface so I could include JList and JTextArea as well, but that's another question)...

基本上,它使出现在 JTable 下方的 JViewport 负责渲染实际的糖果剥离.

Basically, it makes the JViewport, which appears below the JTable, responsible for rendering the actual candy stripping.

但是为什么?"你问...因为它不会影响表格或单元格渲染器.这样做的唯一要求是表格和单元格渲染器都是透明的(除非它们必须是透明的).

But "why?" you ask...because it doesn't affect the table or cell renderer. The only requirement that this makes is that both the table and cell renderers are transparent (unless they have to be otherwise).

这意味着,您不需要在渲染器中放置糖果剥离逻辑,这意味着您不需要覆盖您创建的每个表的 prepareRenderer 并破坏单元渲染器的要求...

This means, you don't need to put candy stripping logic in your renderers, this means you don't need to override prepareRenderer of every table you create and mangle the requirements of the cell renderers...

它远非完美,但展示了基本思想...

It's far from perfect, but demonstrates the basic idea...

好吧,但为什么要麻烦呢?嗯,基本上,这种方法可以让你在桌子画的区域之外画画......

Okay, but why bother? Well, basically, this approach allows you to paint beyond the area painted by the table...

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class CandyStrippedTable {

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

    public CandyStrippedTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                Object[] columns = new Object[10];
                for (int col = 0; col < columns.length; col++) {
                    columns[col] = (char) (65 + col);
                }

                Object[][] data = new Object[10][10];
                for (int row = 0; row < data.length; row++) {
                    for (int col = 0; col < data[row].length; col++) {
                        data[row][col] = row + "x" + col;
                    }
                }

                DefaultTableModel model = new DefaultTableModel(data, columns);
                JTable table = new JTable(model);
                table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

                    @Override
                    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                        setOpaque(isSelected);
                        return this;
                    }
                    
                });
                table.setFillsViewportHeight(true);
                table.setOpaque(false);

                JScrollPane sp = new JScrollPane();
                sp.setViewport(new CandyStrippedViewPort(new Color(255, 0, 0, 128)));
                sp.setViewportView(table);

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(sp);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class CandyStrippedViewPort extends JViewport {

        private Color candyStrippedColor;

        public CandyStrippedViewPort(Color color) {
            candyStrippedColor = color;
        }

        public Color getCandyStrippedColor() {
            return candyStrippedColor;
        }

        public void setCandyStrippedColor(Color candyStrippedColor) {
            this.candyStrippedColor = candyStrippedColor;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(getCandyStrippedColor());
            Component view = getView();
            if (view instanceof JTable) {
                JTable table = (JTable) view;
                Rectangle viewRect = getViewRect();
                int y = 0;
                int row = 0;
                if (table.getRowCount() > 0) {
                    row = table.rowAtPoint(viewRect.getLocation());
                    while (row < table.getRowCount()) {
                        int rowHeight = table.getRowHeight(row);
                        Rectangle cellRect = table.getCellRect(row, 0, true);
                        if (row % 2 == 0) {
                            g2d.fillRect(0, cellRect.y - viewRect.y, getWidth(), cellRect.height);
                        }
                        y = cellRect.y + cellRect.height;
                        row++;
                    }
                }
                int rowHeight = table.getRowHeight();
                while (y < getHeight()) {
                    if (row % 2 == 0) {
                        g2d.fillRect(0, y, getWidth(), rowHeight);
                    }
                    row++;
                    y += rowHeight;
                }
            }
            g2d.dispose();
        }
    }
}

在单元格渲染器中格式化数字

你可以从类似...开始

You could start with something like...

obj.table.setDefaultRenderer(Double.class, 
    new DefaultTableCellRenderer() { 
        @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { 
            if (value instanceof Number) {
                value = NumberFormat.getNumberInstance().format(value);
            }
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
            setOpaque(isSelected); 
            return this; 
        } 
    });

如果出于某种原因,默认格式不合适,您可以执行以下操作...

If, for some reason, the default format instead suitable, you could do something like...

obj.table.setDefaultRenderer(Double.class, 
    new DefaultTableCellRenderer() { 
        @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { 
            if (value instanceof Number) {
                NumberFormat ni = NumberFormat.getNumberInstance();
                ni.setMaximumFractionDigits(2)
                value = ni.format(value);
            }
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
            setOpaque(isSelected); 
            return this; 
        } 
    });

代替

这篇关于java AbstractTableModel 2 每行不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆