我试图通过扩展 BasicComboBoxUI 类来改变 JComboBox 组件的外观。问题是当我使用扩展的 MyComboBoxUI 类时,组合框停止正常工作。
这个 SSCCE 正在展示我的问题。第一个组合框显示第二个组合框的选定项,第一个组合框没有绘制箭头按钮,无法选择项目。
注意:我以这种方式更改 JButton 组件没有问题。
主类:
import javax.swing.JFrame;
import javax.swing.UIManager;
public class Main {
public static void main(String[] args) {
UIManager.put("ComboBoxUI", "MyComboBoxUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
ContentPane contentPane = new ContentPane();
frame.setContentPane(contentPane);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
内容窗格类:
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JPanel;
public class ContentPane extends JPanel {
public ContentPane() {
setLayout(new FlowLayout());
JComboBox<String> firstComboBox = new JComboBox<>();
firstComboBox.addItem("firstComboBox - 1. item");
firstComboBox.addItem("firstComboBox - 2. item");
firstComboBox.addItem("firstComboBox - 3. item");
add(firstComboBox);
JComboBox<String> secondComboBox = new JComboBox<>();
secondComboBox.addItem("secondComboBox - 1.item");
secondComboBox.addItem("secondComboBox - 2. item");
secondComboBox.addItem("secondComboBox - 3. item");
add(secondComboBox);
}
}
MyComboBoxUI 类:
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicComboBoxUI;
public class MyComboBoxUI extends BasicComboBoxUI {
private static MyComboBoxUI myComboBoxUI = new MyComboBoxUI();
public static ComponentUI createUI(JComponent component) {
return myComboBoxUI;
}
}