gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:53:21 29 4
gpt4 key购买 nike

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

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

这可能不是有意的,但可以节省我用 JLabel 替换组合框的工作,因此也将不胜感激肮脏的黑客答案。

最佳答案

嗯,这对我来说似乎没问题......

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");
}
});
}

}

}

确保您使用的对象等于JComboBox中的值

关于java - 如何更改禁用的 JComboBox 上(显示的)所选项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823336/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com