如何更改已禁用的JComboBox上的(显示的)所选项目?

时间:2016-01-16 03:51:24

标签: java swing java-7 jcombobox

我想以编程方式更改已禁用的JComboBox上显示的所选项目。我试过了

  • 在调用setSelectedItem之前启用它并在
  • 之后立即禁用它
  • 前者并在禁用
  • 之前调用updateUI

可能这不是故意的,但是可以省去用JLabel替换组合框的工作,所以也应该感谢肮脏的黑客答案。

1 个答案:

答案 0 :(得分:3)

好吧,它似乎对我有用......

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

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

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

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            JComboBox cb = new JComboBox(new String[]{
                "One", "Two", "Three", "Four", "Five"
            });
            cb.setEnabled(false);
            add(cb, gbc);
            cb.setEnabled(false);

            JButton btn = new JButton("Update");
            add(btn, gbc);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    cb.setSelectedItem("Five");
                }
            });
        }

    }

}

确保您使用的对象equalJComboBox

中的值