繁体   English   中英

单击jitem后更改jtable单元格颜色

[英]Changing jtable cell color after jitem click

我是Java Swing的新手。 我有一个jtable,在第2列中,当右键单击一个单元格时,jpopmenu显示带有两个选项(进行中/已解决)的jtable,并且我想在单击选项“已解决”时将单元格颜色修改为绿色。 我知道我需要一个单元格渲染器。 怎么放呢?

有我的源代码:

public class logaff {

static File font_file = new File("font/MYRIADPRO-REGULAR.ttf");
static JPopupMenu pm;
static JMenuItem one = new JMenuItem();
static JMenuItem two = new JMenuItem();
static JTable table;

public static void main(String[] args) throws FontFormatException,
        IOException {
    Font fontt = Font.createFont(Font.TRUETYPE_FONT, font_file);
    Font sizedFont = fontt.deriveFont(Font.PLAIN, 15);
    JPanel logaffich = new JPanel();
    logaffich.setBackground(Color.black);
    logaffich.setLayout(null);

    JPanel tableau = new JPanel();
    tableau.setLocation(5, 15);
    tableau.setSize(790, 520);
    tableau.setBackground(Color.white);

    JButton a = new JButton("fg");
    String[] columnNames = { "ID", "Description", "Status", "Cam",
            "Elapsed Time" };
    String[][] data = new String[10][5];

    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            data[i][j] = "Table " + i + ", " + j;

        }
    }

    int[] columnsWidth = { 158, 450, 60, 40, 80 };

    table = new JTable(data, columnNames);
    int k = 0;
    for (int width : columnsWidth) {
        TableColumn column = table.getColumnModel().getColumn(k++);
        column.setMinWidth(width);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        table.setRowHeight(55);
    }

    JScrollPane scrollPane = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    tableau.setLayout(new BorderLayout());
    tableau.add(scrollPane, BorderLayout.CENTER);

    pm = new JPopupMenu();
    pm.add(one);
    pm.add(two);

    table.addMouseListener(new MouseAdapter() {

        public void mouseReleased(MouseEvent me) {
            try {
                showPopup(me);
            } catch (FontFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    logaffich.add(tableau);
    TitledBorder title1;

    title1 = BorderFactory.createTitledBorder(null, "New Log Alert",
            TitledBorder.LEFT, TitledBorder.TOP, sizedFont, Color.white);
    logaffich.setBorder(title1);

    // panel pour le formulaire
    JFrame frame = new JFrame();
    frame.setContentPane(logaffich);
    // Create and set up the content pane.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(808, 565);
    frame.setResizable(false);
    frame.setVisible(true);

}

private static void showPopup(MouseEvent me) throws FontFormatException,
        IOException {
    // is this event a popup trigger?
    if (pm.isPopupTrigger(me)) {
        Point p = me.getPoint();
        final int row = table.rowAtPoint(p);
        final int col = table.columnAtPoint(p);
        // if we've clicked on a row in the second column
        if (row != -1 && col == 1) {
            File font_file = new File("font/MYRIADPRO-REGULAR.ttf");

            Font fontt = Font.createFont(Font.TRUETYPE_FONT,font_file);
            Font sizedFont = fontt.deriveFont(Font.BOLD, 17);
            final ImageIcon progress = new ImageIcon("images/progress.png");
            one.setIcon(progress);
            one.setFont(sizedFont);
            final ImageIcon ok = new ImageIcon("images/ok.png");
            two.setIcon(ok);
            two.setFont(sizedFont);

            one.setText("In progress " + row + ".");
            two.setText("Solved " + row + ".");
            pm.show(table, p.x, p.y);

        }
        one.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent me) {
                System.out.println("sfsdf" + row);

            }

        });
    }
}
 }

您需要阅读有关Renderers的文档。 为了正确使用它。

接下来的代码将自定义单元格渲染器添加到您的列中:

 TableColumn column = table.getColumnModel().getColumn(1);
 column.setCellRenderer(getRenderer());

getRenderer方法的示例代码:

private static TableCellRenderer getRenderer() {
return new DefaultTableCellRenderer(){
    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
            boolean solved = false;
            if (value.toString().endsWith("Solved")) {
                solved = true;
                value = value.toString().replace("Solved", "");
            }
            Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value,isSelected, hasFocus, row, column);
            if (solved) {
                tableCellRendererComponent.setBackground(Color.GREEN);
            } else {
                tableCellRendererComponent.setBackground(table.getBackground());
            }
            return tableCellRendererComponent;
    }
};
}

该方法返回DefaultTableCellRenderer if-else语句中,您可以确定单元格的背景。

编辑:1)更改了getRenderer方法。

2)以以下方式创建弹出窗口:

 pm = new JPopupMenu();
pm.add(one);
pm.add(two);
one.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent me) {
        if(row != -1)
        System.out.println("sfsdf" + row);

    }

});

two.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent me) {
        if(row != -1){
            Object valueAt = table.getValueAt(row,1);
            table.setValueAt(valueAt+"Solved", row,1);
            ((DefaultTableModel)table.getModel()).fireTableDataChanged();
        }
    }

});

因为您每次调用showPopup方法时都添加了侦听器,而不是像我的示例中那样仅添加一次。 row字段我设置为静态字段。

3)您的方法showPopup更改了:

private static void showPopup(MouseEvent me) throws FontFormatException,
    IOException {

// is this event a popup trigger?
if (pm.isPopupTrigger(me)) {
    Point p = me.getPoint();
    row = table.rowAtPoint(p);
    final int col = table.columnAtPoint(p);
    // if we've clicked on a row in the second column
    if (row != -1 && col == 1) {
        final ImageIcon progress = new ImageIcon("images/progress.png");
        one.setIcon(progress);
        final ImageIcon ok = new ImageIcon("images/ok.png");
        two.setIcon(ok);

        one.setText("In progress " + row + ".");
        two.setText("Solved " + row + ".");
        pm.show(table, p.x, p.y);

    } 

}
}

4)以另一种方式创建表table = new JTable(new DefaultTableModel(data, columnNames));

如果按照我的建议更改代码,则在弹出窗口中按“已解决”时 ,单元格将带有绿色背景。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM