Reputation: 1115
I am trying to change the look of JComboBox components by extending BasicComboBoxUI class. The problem is that when I use the extended MyComboBoxUI class, combo boxes stop functioning properly.
This SSCCE is demonstrating my problem. The first combo box displays the selected item of the second combo box, and the first combo box doesn't have arrow button painted and items cannot be selected.
Note: I had no problem changing JButton components in this manner.
Main class:
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);
}
});
}
}
ContenPane class:
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 class:
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;
}
}
Upvotes: 2
Views: 1031
Reputation: 324098
I think you want:
return new MyComboBoxUI();
When you have a static variable it means every combobox will share the same instance of the UI.
Upvotes: 5