JTable行选择后台问题。

发布于 2024-11-27 03:10:23 字数 2043 浏览 1 评论 0原文

我有一个 JTable 并在 JTable 和其他属性中设置图片作为背景,我使用了此代码。

tblMainView= new JTable(dtModel){
        public Component prepareRenderer(TableCellRenderer renderer, int row, 
                   int column) 
        {
        Component c = super.prepareRenderer( renderer, row, column);
        // We want renderer component to be transparent so background image 
        // is visible
        if( c instanceof JComponent )
        ((JComponent)c).setOpaque(false);
        return c;
        }
        ImageIcon image = new ImageIcon( "images/watermark.png" );          
          public void paint( Graphics g )
        {
        // First draw the background image - tiled 
        Dimension d = getSize();
        for( int x = 0; x < d.width; x += image.getIconWidth() )
        for( int y = 0; y < d.height; y += image.getIconHeight() )
        g.drawImage( image.getImage(), x, y, null, null );
        // Now let the regular paint code do it's work
        super.paint(g);
        }       

        public boolean isCellEditable(int rowIndex, int colIndex) {
          return false;
        }
        public Class getColumnClass(int col){
            if (col == 0)  
            {  
            return Icon.class;  
            }else if(col==7){
                return String.class;
            } else
            return String.class; 
        }   
        public boolean getScrollableTracksViewportWidth() {
            if (autoResizeMode != AUTO_RESIZE_OFF) {
                if (getParent() instanceof JViewport) {
                return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
                }
            } 
            return false;
            }

    };

    tblMainView.setOpaque(false);

每件事都工作正常。但是当我选择一行时,行数据隐藏。它显示我的行,如 this

我希望结果与此相同, 在此处输入图像描述 dtModel 是我名为 tblMainViewJTabledeafultTableModel

I have a JTable and to set a picture as background in JTable and other properties i used this code.

tblMainView= new JTable(dtModel){
        public Component prepareRenderer(TableCellRenderer renderer, int row, 
                   int column) 
        {
        Component c = super.prepareRenderer( renderer, row, column);
        // We want renderer component to be transparent so background image 
        // is visible
        if( c instanceof JComponent )
        ((JComponent)c).setOpaque(false);
        return c;
        }
        ImageIcon image = new ImageIcon( "images/watermark.png" );          
          public void paint( Graphics g )
        {
        // First draw the background image - tiled 
        Dimension d = getSize();
        for( int x = 0; x < d.width; x += image.getIconWidth() )
        for( int y = 0; y < d.height; y += image.getIconHeight() )
        g.drawImage( image.getImage(), x, y, null, null );
        // Now let the regular paint code do it's work
        super.paint(g);
        }       

        public boolean isCellEditable(int rowIndex, int colIndex) {
          return false;
        }
        public Class getColumnClass(int col){
            if (col == 0)  
            {  
            return Icon.class;  
            }else if(col==7){
                return String.class;
            } else
            return String.class; 
        }   
        public boolean getScrollableTracksViewportWidth() {
            if (autoResizeMode != AUTO_RESIZE_OFF) {
                if (getParent() instanceof JViewport) {
                return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
                }
            } 
            return false;
            }

    };

    tblMainView.setOpaque(false);

Every thing is working correctly. But when i select a row, the row data hides.it shows my row like this

i want the result same like this,enter image description here
dtModel is the deafultTableModel for my JTable named tblMainView

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尝蛊 2024-12-04 03:10:23

推荐重写 prepareRenderer()为整个表行进行自定义渲染的方法,但您不能让它完成所有操作。特别是 默认渲染器 Icon 应该做你想要的事情,并且根本没有理由重写 paint()

附录:仔细观察,您选择的字段显示为空,因为 setOpaque(false) 干扰 DefaultTableCellRenderer API。您复制的示例将不起作用。

作为参考,下面的示例覆盖 DefaultTableModelgetColumnClass() 以获取 IconDate 类型的默认渲染器

Java GUI

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.Calendar;
import java.util.Date;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** @see https://stackoverflow.com/questions/6873665 */
public class JavaGUI extends JPanel {

    private static final int ICON_COL = 0;
    private static final int DATE_COL = 1;
    private static final Icon icon = UIManager.getIcon("Tree.closedIcon");
    private final Calendar calendar = Calendar.getInstance();

    public JavaGUI() {
        CustomModel model = new CustomModel();
        JTable table = new JTable(model) {

            @Override
            public Component prepareRenderer(
                    TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                if (isRowSelected(row)) {
                    c.setBackground(Color.blue);
                } else {
                    c.setBackground(Color.white);
                }
                return c;
            }
        };
        for (int i = 1; i <= 16; i++) {
            model.addRow(newRow(i));
        }
        this.add(table);
    }

    private Object[] newRow(int i) {
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return new Object[]{icon, calendar.getTime()};
    }

    private static class CustomModel extends DefaultTableModel {

        private final String[] columnNames = {"Icon", "Date"};

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == ICON_COL) {
                return Icon.class;
            } else if (col == DATE_COL) {
                return Date.class;
            }
            return super.getColumnClass(col);
        }

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

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

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }

    private void display() {
        JFrame f = new JFrame("JavaGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JavaGUI().display();
            }
        });
    }
}

Overriding prepareRenderer() is a recommended way to do custom rendering for an entire table row, but you can't make it do everything. In particular, the default renderer for Icon should do what you want, and there's no reason to override paint(), at all.

Addendum: Looking closer, your selected field appears empty because setOpaque(false) interferes with the optimization mentioned in the DefaultTableCellRenderer API. The example you copied won't work.

For reference, the example below overrides the getColumnClass() of DefaultTableModel to obtain the default renderer for types Icon and Date.

Java GUI

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.Calendar;
import java.util.Date;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** @see https://stackoverflow.com/questions/6873665 */
public class JavaGUI extends JPanel {

    private static final int ICON_COL = 0;
    private static final int DATE_COL = 1;
    private static final Icon icon = UIManager.getIcon("Tree.closedIcon");
    private final Calendar calendar = Calendar.getInstance();

    public JavaGUI() {
        CustomModel model = new CustomModel();
        JTable table = new JTable(model) {

            @Override
            public Component prepareRenderer(
                    TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                if (isRowSelected(row)) {
                    c.setBackground(Color.blue);
                } else {
                    c.setBackground(Color.white);
                }
                return c;
            }
        };
        for (int i = 1; i <= 16; i++) {
            model.addRow(newRow(i));
        }
        this.add(table);
    }

    private Object[] newRow(int i) {
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return new Object[]{icon, calendar.getTime()};
    }

    private static class CustomModel extends DefaultTableModel {

        private final String[] columnNames = {"Icon", "Date"};

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == ICON_COL) {
                return Icon.class;
            } else if (col == DATE_COL) {
                return Date.class;
            }
            return super.getColumnClass(col);
        }

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

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

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }

    private void display() {
        JFrame f = new JFrame("JavaGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JavaGUI().display();
            }
        });
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文