当前位置: 首页 > 知识库问答 >
问题:

将JComboBox项中的值设置为JTable中的CellEditor的工具提示

程祯
2023-03-14

我想为自定义组合框中的值设置一个工具提示值。基本上,我的组合框包含一个人的首字母列表——当他们悬停在上面时,我想让它显示这个人的全名。我的组合框基本上是一个JTable的单元格/列,它有自己的TableCellRenler和DefaultCellEditor。列表是一个JList(模型中的内部类)——我尝试过直接设置“setToolTipText”方法,但似乎不起作用。

下面是代码:

*JTable中的代码:*

public void setupUserCombo(Container container){
      TableColumn col = getColumnModel().getColumn(3);
      Set<ComboUser> values = new LinkedHashSet<ComboUser>();

      ComboUser comboUser = new ComboUser(new User("Test User"));
      values.add(comboUser);

      col.setCellEditor(new MyComboBoxEditor((ComboUser[])values.toArray(new ComboUser[0])));
      col.setCellRenderer(new MyComboBoxRenderer((ComboUser[])values.toArray(new ComboUser[0])));
      repaint();
}

public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    private static final long serialVersionUID = 1L;

    public MyComboBoxRenderer(ComboUser[] items) {
        super(items);
        repaint();
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        if (value != null){
            System.out.println("Setting tooltip");
            ((ComboUser)value).setToolTipText("TESTING!!");
        }
        setSelectedItem(value);

        return this;
    }
}

public class MyComboBoxEditor extends DefaultCellEditor {
    private static final long serialVersionUID = 1L;

    public MyComboBoxEditor(ComboUser[] items) {
        super(new JComboBox(items));
    }
}

*模型中的子类:*

public class ComboUser extends JLabel{

    private User user;

    public ComboUser(User user){
        if (user != null){
            this.user = user;
        } else {
            this.user = new User("");
        }
    }

    @Override
    public String toString() {
        return user.getInitials();
    }

共有2个答案

锺离德庸
2023-03-14

参见JTable教程,测试代码示例,例如

import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class TableRenderDemo extends JPanel {

    private static final long serialVersionUID = 1L;

    public TableRenderDemo() {
        super(new BorderLayout(5, 5));
        final JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setFillsViewportHeight(true);
        table.setRowHeight(20);
        JScrollPane scrollPane = new JScrollPane(table);
        initColumnSizes(table);
        setUpSportColumn(table, table.getColumnModel().getColumn(2));
        add(scrollPane, BorderLayout.CENTER);
        JButton resetButton = new JButton("Reset to default");
        resetButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < table.getRowCount(); i++) {
                    table.getModel().setValueAt("None of the above", i, 2);
                }
            }
        });
        add(resetButton, BorderLayout.SOUTH);
    }

    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel) table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);
            comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;
            comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }

    private void setUpSportColumn(JTable table, TableColumn sportColumn) {
        ArrayList<String> listSomeString = new ArrayList<String>();
        listSomeString.add("Snowboarding");
        listSomeString.add("Rowing");
        listSomeString.add("Knitting");
        listSomeString.add("Speed reading");
        listSomeString.add("Pool");
        listSomeString.add("None of the above");
        JComboBox comboBox = new JComboBox();
        comboBox.addItem(new Item(1, "-"));
        comboBox.addItem(new Item(2, "Snowboarding"));
        comboBox.addItem(new Item(3, "Rowing"));
        comboBox.addItem(new Item(4, "Knitting"));
        comboBox.addItem(new Item(5, "Speed reading"));
        comboBox.addItem(new Item(6, "Pool"));
        comboBox.addItem(new Item(7, "None of the above"));
        comboBox.setMaximumRowCount(3);
        comboBox.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JComboBox comboBox = (JComboBox) e.getSource();
                Item item = (Item) comboBox.getSelectedItem();
                System.out.println(item.getId() + " : " + item.getDescription());
            }
        });
        //comboBox.setRenderer(new ItemRenderer());
        sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);
    }

    class ItemRenderer extends BasicComboBoxRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value != null) {
                Item item = (Item) value;
                setText(item.getDescription().toUpperCase());
            }
            if (index == -1) {
                Item item = (Item) value;
                setText("" + item.getId());
            }
            return this;
        }
    }

    class Item {

        private int id;
        private String description;

        public Item(int id, String description) {
            this.id = id;
            this.description = description;
        }

        public int getId() {
            return id;
        }

        public String getDescription() {
            return description;
        }

        @Override
        public String toString() {
            return description;
        }
    }

    class MyTableModel extends AbstractTableModel {

        private static final long serialVersionUID = 1L;
        private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
        private Object[][] data = {{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
            {"John", "Doe", "Rowing", new Integer(3), true}, {"Sue", "Black", "Knitting", new Integer(2), false},
            {"Jane", "White", "Speed reading", new Integer(20), true}, {"Joe", "Brown", "Pool", new Integer(10), false}};
        public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};

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

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

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

        @Override
        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        @Override
        public Class<?> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
            System.out.println("New value of data: " + getValueAt(row, col));
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TableRenderDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableRenderDemo newContentPane = new TableRenderDemo();
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
常献
2023-03-14

如果想要在编辑组合框中显示工具提示,则必须在该组合框的自定义渲染器中显示工具提示。下面是一个简短的例子:

// some data
User[] users = new User[] { 
        new User("Clara Zetkin", "CZ"),
        new User("Rosa Luxemburg", "RL"),
        new User("Susan Sontag", "SS"),
};
// the renderer for use in the editor
ListCellRenderer comboRenderer = new DefaultListCellRenderer() {

    @Override
    public Component getListCellRendererComponent(JList<?> list,
            Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        if (value instanceof User) {
            setToolTipText(((User) value).getName());
            value = ((User) value).getInitials();
        } else {
            setToolTipText(null);
        }
        return super.getListCellRendererComponent(list, value, index, isSelected,
                cellHasFocus);
    }

};
JComboBox editingCombo = new JComboBox(users);
editingCombo.setRenderer(comboRenderer);

JTable table = new JTable(3, 2);
// set up the editor for the first column
table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(editingCombo));
// the renderer to use in the table
TableCellRenderer renderer = new DefaultTableCellRenderer() {

    @Override
    protected void setValue(Object value) {
        if (value instanceof User) {
            setToolTipText(((User) value).getInitials());
            value = ((User) value).getName();
        } else {
            setToolTipText(null);
        }
        super.setValue(value);
    }

};
table.getColumnModel().getColumn(0).setCellRenderer(renderer);
 类似资料:
  • 问题内容: 我想为自定义组合框中的值设置工具提示值。基本上,我的组合框包含一个姓名缩写的列表- 当他们将鼠标悬停在上方时,我希望它显示该姓名的全名。我的组合框基本上是JTable的一个单元格/列,它具有自己的TableCellRenderer和DefaultCellEditor。该列表是一个JList(模型中的内部类)-iv尝试直接设置’setToolTipText’方法,但这似乎不起作用。 这是

  • 问题内容: 我不知道如何在特定行中设置一个jcombobox …现在我已经为所有行设置了这个jcombobox,但是我只希望在一行中设置它: 问题答案: 更新: 在测试我的(可能是不完整的)答案时,我遇到了一个非常好的SO问题,我认为它将比我能提供的更好:将JComboBox放入JTable 另一个更新: 我再次阅读了您的问题,并且意识到您要求输入 特定的行 。我能想到的唯一方法是创建一个自定义C

  • 我有一个JComboBox,其中的项是查询的结果。组合框显示从查询中获取的所有类别名称,对吗?好的,它起作用了。现在我需要给每个项目一个值,即产品的ID。 这是我目前得到的信息: 正如您在代码中看到的,每个项目的“标签”都是它的名称。现在,如何设置每个项目的ID,以便我可以操作之后?

  • 我有一个可过滤和可编辑的JComboBox。我想为JComboBox中的每一项设置一个工具提示——我想我应该使用JToolTip来做这件事。 我试着用了这个链接的答案:Java Swing:JComboBox项目上的Mouseover text?。 但是当JComboBox显示过滤的项目时,JToolTip索引的顺序会发生变化。在这种情况下,我不知道如何为每个JComboBox项目设置正确的JTo

  • 现在,在第一行第三列(“OK”)中,您可以在JComboBox中选择表示一行的不同条目。因此一行有三个引用另一行的JComboBoxes。如果您在这样的JComboBox中单击,您会注意到它总是选择第一个条目,而不是您在单击之前看到的带有数字的条目。 也许现在你明白我想做什么了?

  • 好吧,这很难解释,但我会尽力的。 我在JTable中有一个JTextField和一个JComboBox,它的getCellEditor方法被覆盖如下: 以下是行为差异(请注意,从现在开始,当我说JTextField或JComboBox时,我指的是JTable中包含任一组件的单元格): > 当我使用tab键或箭头键导航到JTextField,然后开始键入时,我键入的字符会自动输入单元格。然而,当我以