Using standard buttons from a Look and Feel
I am making a UI with Swing, and I want the buttons I am using for my custom dialogs to have the same style as the ones in standard dialogs.
For instance, in the attached image I have a custom dialog and the standard file select dialog. I want the 'OK' and 'Cancel' buttons from the file select dialog to be used for the equivalent buttons in my custom dialog.
I want开发者_运维技巧 my application to use the default system look and feel of whatever OS it is running on, so I don't want to try to manually re-create these standard buttons. Using a more rigid Swing class that automatically provides these buttons wouldn't work either, as I'd like to also use them in other, more exotic places in my UI.
Is there an easy solution to this problem?
Sorry to be the bearer of bad news, but it look like there is no standard way to do this cross-platform. The behaviours, mnemonics and icons on default buttons are handled in very specific ways by each look-and-feel.
Here is a SO question that answers the question on how to set the default OK and Cancel buttons on a dialog (the default button is set using getRootPane().setDefaultButton(...)
and the Cancel button needs a custom keyboard listener. If you're very lucky, setting the default button might add an icon to it, depending on how the UI is coded.
This forum thread addresses the issue of getting icon resources from the UIManager
. Each LaF has a set of UI defaults such as colors, text, borders and icons. There are a number of default icons which are found across all LaFs, but for non-standard icons, such as ones on buttons, there are no guarantees. However, if you tell me which LaF you are using in the screenshot you provided, I can look up the resource keys used by its custom UI classes (or you can find it yourself if you have the source). You could then write a helper method which looks for the icons via these keys, and adds them to the buttons if they are found.
JButton.setUI(ButtonUI) sets the UI for just one JButton. Use that in conjunction with a factory:
public static JButton createStyledButton(String text) {
JButton button = new JButton(text);
button.setUI(STYLE_UI);
return button;
}
精彩评论