Java Reference
In-Depth Information
Listing 20-8 shows the updated source used to produce Figure 20-6.
Listing 20-8. Using Customized ComboBoxUI
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class PopupComboSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
String labels[] = {"Chardonnay", "Sauvignon", "Riesling", "Cabernet",
"Zinfandel", "Merlot", "Pinot Noir", "Sauvignon Blanc", "Syrah",
"Gewürztraminer"};
JFrame frame = new JFrame("Popup JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox comboBox = new JComboBox(labels);
comboBox.setMaximumRowCount(5);
comboBox.setUI((ComboBoxUI)MyComboBoxUI.createUI(comboBox));
frame.add(comboBox, BorderLayout.NORTH);
JComboBox comboBox2 = new JComboBox(labels);
frame.add(comboBox2, BorderLayout.SOUTH);
frame.setSize (300, 100);
frame.setVisible (true);
}
};
EventQueue.invokeLater(runner);
}
}
If you want to use the new UI delegate for all components, you can let the UIManager know
about the delegate before creating the components, instead of manually calling setUI() after
creating one. In the example in Listing 20-8, you would add the following line:
UIManager.put("ComboBoxUI", "MyComboBoxUI")
If you did this, both combo boxes would then look the same.
The actual creation of the UI delegate is done somewhat indirectly, as shown by Figure 20-7.
A call to the component constructor asks the UIManager for the UI delegate class. The UIManager
maintains the list of delegates in its defaults property, a UIDefaults object. When the UIDefaults
is queried for the delegate, it goes back to the component to ask which delegate is needed. After
it finds the appropriate delegate implementation, the UIDefaults object tells the ComponentUI
to create it, resulting in the actual UI delegate class being created. Once the UI delegate is
created, it needs to be configured for the state of the specific model.
Search WWH ::




Custom Search