某些列中的某些单元格(但不是全部)中的复选框-JTable [英] Checkbox in some cells but not all, in a particular column - JTable

查看:42
本文介绍了某些列中的某些单元格(但不是全部)中的复选框-JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个模糊的查询,请原谅我.

This may be a vague query, so please pardon me.

定制的JTable(我已经修改了查询,并将基于提供的SSCCE进行讨论).我必须创建一个JTable,以根据JTable中选定的复选框提供授权

Customized JTable (I've modified the query and will discuss based on the SSCCE provided). I've to create a JTable to provide authorization based on selected checkboxes in JTable

此JTable的目的是向用户显示应用程序的所有菜单选项.此JTable具有三列: 第一列:Bollean类(复选框) 第二列:String类(主菜单项) 第三列:String类(子菜单项)

Purpose of this JTable is to show users with all of the menu options of the application. This JTable have three columns: First column: class Bollean (checkbox) Second column: class String (main menu items) Third column: class String (sub-menu items)

要提供授权,用户必须选中与子菜单项相对应的复选框,最后选择授权"按钮(由于我的授权功能正常,因此我未包括授权按钮)

To provide authorization user shall select checkbox corresponding to sub-menu items and finally select "Authorize" button (I haven't included authorize button in this as my authorize functionality is working fine)

现在,UI要求是,在JTable的第一列中,我应该只显示与子菜单项相对应的复选框,而不是在第一列的每个单元格中都显示复选框(换句话说,它不应显示与主菜单相对应的复选框)菜单项)

Now the UI requirement is that in the first column of JTable, I should display checkboxes corresponding to sub-menu items only instead of displaying checkbox in each cell of first column (in other words it should not display checkbox corresponding to main menu menu item)

下面的图片是预期的输出(尽管我在第一栏中的所有单元格都带有复选框)

Pic below is expected output (although I'm getting all cells in first column with checkbox)

public class SwingSolution extends JPanel {

    public SwingSolution() {
        super(new GridLayout(1,0));

        String[] columnNames = {"", "Main Menu", "Sub Menu"};

        Object[][] data = {
        {false, "File", ""},
        {false, "", "New"},
        {false, "", "Save"},
        {false, "", "Close"},
        {false, "Edit", ""},
        {false, "", "Delete"},
        {false, "", "Format"},
        {false, "Project", ""},
        {false, "", "Create New"},
        {false, "", "Delete"},
        {false, "", "Build"},
        {false, "", "Properties"},
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        final JTable table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return Boolean.class;
                    case 1:
                        return String.class;
                    case 2:
                        return String.class;
                    default:
                        return Boolean.class;
                }
            }
        };

        table.getColumnModel().getColumn(0).setMaxWidth(30);
        table.getColumnModel().getColumn(1).setMaxWidth(100);
        table.getColumnModel().getColumn(2).setMaxWidth(120);

        table.setPreferredScrollableViewportSize(new Dimension(250, 195));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        SwingSolution newContentPane = new SwingSolution();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

我尝试了一些使用单元格渲染器的方法,并搜索了有关JTable和自定义单元格的信息,但无法弄清楚.任何帮助将不胜感激

I tried various things with cell renderer and googled about JTable and custom cells but couldn't figured it out. Any help will be greatly appreciated

推荐答案

基本上,您将需要提供单元格渲染器和编辑器.

Basically, you're going to have supply you're cell renderer and editor.

在这种情况下,我将第一列的值/类型更改为int.这使我可以提供boolean以外的其他含义.

In this case, I changed the first columns value/type to int. This allows me to supply additional meaning beyond boolean.

如果列值是0,则该单元格不是可选"的,未选中1,已选中2.

If the column value is 0 then the cell is not "selectable", 1 is unchecked, 2 is checked.

我还更改了TableModelisCellEditable方法,以仅允许活动"单元格可编辑.

I also altered the isCellEditable method of the TableModel to only allow the "active" cells to be editable.

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class LimitedTableCellEditor extends JPanel {

    public LimitedTableCellEditor() {
        super(new GridLayout(1, 0));

        String[] columnNames = {"", "Main Menu", "Sub Menu",};

        Object[][] data = {
            {0, "File", ""},
            {1, "", "New"},
            {1, "", "Save"},
            {1, "", "Close"},
            {0, "Edit", ""},
            {1, "", "Delete"},
            {1, "", "Format"},
            {0, "Project", ""},
            {1, "", "Create New"},
            {1, "", "Delete"},
            {1, "", "Build"},
            {1, "", "Properties"},};

        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        final JTable table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return Integer.class;
                    case 1:
                        return String.class;
                    case 2:
                        return String.class;
                    default:
                        return Boolean.class;
                }
            }

            @Override
            public boolean isCellEditable(int row, int column) {
                boolean editable = false;
                if (column == 0) {
                    Object value = getValueAt(row, column);
                    if (value instanceof Integer) {
                        editable = ((int)value) != 0;
                    }
                }
                return editable;
            }
        };

        table.getColumnModel().getColumn(0).setMaxWidth(30);
        table.getColumnModel().getColumn(0).setCellRenderer(new ConditionalCheckBoxRenderer());
        table.getColumnModel().getColumn(1).setMaxWidth(100);
        table.getColumnModel().getColumn(2).setMaxWidth(120);

        table.setPreferredScrollableViewportSize(new Dimension(250, 195));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        LimitedTableCellEditor newContentPane = new LimitedTableCellEditor();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static class ConditionalCheckBoxRenderer extends JPanel implements TableCellRenderer {

        private static final Border NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
        private JCheckBox cb;

        public ConditionalCheckBoxRenderer() {
            setLayout(new GridBagLayout());
            setOpaque(false);
            cb = new JCheckBox();
            cb.setOpaque(false);
            cb.setContentAreaFilled(false);
            cb.setMargin(new Insets(0, 0, 0, 0));
            add(cb);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setOpaque(isSelected);
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
            }
            if (value instanceof Integer) {
                int state = (int) value;
                cb.setVisible(state != 0);
                cb.setSelected(state == 2);
            }
            if (hasFocus) {
                setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
            } else {
                setBorder(NO_FOCUS_BORDER);
            }
            return this;
        }
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

我还没有完成编辑器,但是基本概念是相同的...

I've not done the editor, but the basic concept is the same...

这篇关于某些列中的某些单元格(但不是全部)中的复选框-JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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