下面列出了怎么用javax.swing.UIManager的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
for ( LookAndFeelInfo info : UIManager.getInstalledLookAndFeels() ) {
if ( "Nimbus".equals(info.getName()) ) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(WeaponDataGeneratorPanel.getInstance());
frame.setSize(800, 800);
frame.setVisible(true);
}
});
}
public TransparentSectionButton(ActionListener al) {
// force initialization of PropSheet look'n'feel values
UIManager.get( "nb.propertysheet" );
setMargin(new Insets(0, 3, 0, 3));
setFocusPainted( false );
setHorizontalAlignment( SwingConstants.LEFT );
setHorizontalTextPosition( SwingConstants.RIGHT );
setVerticalTextPosition( SwingConstants.CENTER );
updateProperties();
if( getBorder() instanceof CompoundBorder ) { // from BasicLookAndFeel
Dimension pref = getPreferredSize();
pref.height -= 3;
setPreferredSize( pref );
}
if(al != null) {
addActionListener(al);
}
initActions();
}
@Override
protected void initialize(String args[]) {
try {
// TODO Use nimbus L&F by Oracle
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
// TODO Use Beauty L&F by Jack Jiang
BeautyEyeLNFHelper.launchBeautyEyeLNF();
UIManager.put("RootPane.setupButtonVisible", false);
} catch (Exception ex) {
// not catestrophic
}
resourceMap = getContext().getResourceMap();
title = resourceMap.getString("mainFrame.title");
runningDemoCache = new HashMap<String, DemoPanel>();
setDemoList(resourceMap.getString("demos.title"), getDemoClassNames(args));
IntroPanel intro = new IntroPanel();
setDemoPlaceholder(intro);
}
/**
* Creates a new instance of RaceGUI
*/
public RaceGUI(String appName) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame(appName);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BorderLayout());
// Add Track view
track = new TrackView();
f.add(track, BorderLayout.CENTER);
// Add control panel
controlPanel = new RaceControlPanel();
f.add(controlPanel, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
private static void initLookAndFeel() {
//Allow users to overwrite LaF
if (System.getProperty("swing.defaultlaf") != null) {
return;
}
String lookAndFeel;
//lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
lookAndFeel = UIManager.getSystemLookAndFeelClassName(); //System
//lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName(); //Java
//lookAndFeel = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; //Nimbus
//lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel"; //Metal
//lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; //GTK+
//lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; //CDE/Motif
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
log.log(Level.SEVERE, "Failed to set LookAndFeel: " + lookAndFeel, ex);
}
}
public void addChildBranch() {
int row = table.getSelectedRow();
if (row < 0)
return;
Node node = (Node) table.getPathForRow(row).getLastPathComponent();
String message = GlobalResourcesManager
.getString("BranchCreationWarning");
if (node.branch.getChildren().size() > 0)
message = GlobalResourcesManager
.getString("BranchNodeCreationWarniong");
if (JOptionPane.showConfirmDialog(framework.getMainFrame(), message,
UIManager.getString("OptionPane.titleText"),
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION)
return;
String s = JOptionPane.showInputDialog(framework.getMainFrame(),
GlobalResourcesManager.getString("BranchCreationReason"),
GlobalResourcesManager.getString("BranchCreationReason"),
JOptionPane.QUESTION_MESSAGE);
if (s == null)
return;
int type = node.branch.getType() - 1;
if (node.branch.getChildren().size() > 0) {
type = getMaxType(type, (Node) branchModel.getRoot());
}
engine.createBranch(node.branch.getBranchId(), s, type + 1, "core");
}
public static void main(String[] args) {
System.setProperty("user.ramus.application.name", "DemoApplication1");
if (args.length == 0)
if (JOptionPane.showConfirmDialog(null,
"Do you want to create a new file of your application?",
UIManager.getString("OptionPane.messageDialogTitle"),
JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new MyFileFilter());
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
args = new String[]{chooser.getSelectedFile()
.getAbsolutePath()};
}
}
new Application().run(args);
}
private static void runTest() {
try {
LookAndFeelInfo[] lafInfo = UIManager.getInstalledLookAndFeels();
for (LookAndFeelInfo info : lafInfo) {
UIManager.setLookAndFeel(info.getClassName());
for (Locale locale : LOCALES) {
for (String key : MNEMONIC_KEYS) {
int mnemonic = SwingUtilities2.getUIDefaultsInt(key, locale);
if (mnemonic != 0) {
throw new RuntimeException("No mnemonic expected (" + mnemonic + ") " +
"for '" + key + "' " +
"in locale '" + locale + "' " +
"in Look-and-Feel '"
+ UIManager.getLookAndFeel().getClass().getName() + "'");
}
}
}
}
System.out.println("Test passed");
} catch (Exception e) {
exception = e;
}
}
void testNames() {
Color defaultColor = label.getBackground();
UIManager.put("\"BlueLabel\"[Enabled].background",
new ColorUIResource(Color.BLUE));
UIManager.put("\"RedLabel\"[Enabled].background",
new ColorUIResource(Color.RED));
nimbus.register(Region.LABEL, "\"BlueLabel\"");
nimbus.register(Region.LABEL, "\"RedLabel\"");
label.setName("BlueLabel");
check(Color.BLUE);
label.setName("RedLabel");
check(Color.RED);
// remove name, color goes back to default
label.setName(null);
check(defaultColor);
}
@Override
public String getRedoPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
return last.getRedoPresentationName();
} else {
String name = getPresentationName();
if (!"".equals(name)) {
name = UIManager.getString("AbstractUndoableEdit.redoText")
+ " " + name;
} else {
name = UIManager.getString("AbstractUndoableEdit.redoText");
}
return name;
}
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LookAndFeelInfo[] lookAndFeels = UIManager.getInstalledLookAndFeels();
for (int i = 0, n = lookAndFeels.length; i < n; i++) {
if ("Nimbus".equals(lookAndFeels[i].getName())) {
try {
UIManager.setLookAndFeel(lookAndFeels[i].getClassName());
} catch (Exception ignored) {
}
break;
}
}
try {
new Hiero();
} catch (SlickException ex) {
throw new RuntimeException(ex);
}
}
});
}
public static void main(String[] args) {
if (args.length != 5) {
System.err.println("Needs database parameters eg. ...");
System.err.println(
"java TableExample2 \"jdbc:derby://localhost:1527/sample\" "
+ "org.apache.derby.jdbc.ClientDriver app app "
+ "\"select * from app.customer\"");
return;
}
// Trying to set Nimbus look and feel
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {
Logger.getLogger(TableExample2.class.getName()).log(Level.SEVERE,
"Failed to apply Nimbus look and feel", ex);
}
new TableExample2(args[0], args[1], args[2], args[3], args[4]);
}
public static void main(String[] args) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame.setDefaultLookAndFeelDecorated(true);
Toolkit.getDefaultToolkit().setDynamicLayout(true);
System.setProperty("sun.awt.noerasebackground", "true");
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
System.out.println(
"Metal Look & Feel not supported on this platform. \n"
+ "Program Terminated");
System.exit(0);
}
JFrame frame = new MetalworksFrame();
frame.setVisible(true);
}
private static AreaXRules getDefaultRules() {
Object rulesObject = UIManager.get("AreaX.rules");
if (rulesObject instanceof AreaXRules)
return (AreaXRules) rulesObject;
String className = (String) rulesObject;
if (className == null)
className = "com.pump.geom.BoundsRules";
AreaXRules rules = rulesTable.get(className);
try {
if (rules == null) {
Class<?> theClass = Class.forName(className);
Constructor<?> constructor = theClass
.getConstructor(new Class[] {});
rules = (AreaXRules) constructor.newInstance(new Object[] {});
}
return rules;
} catch (Throwable t) {
t.printStackTrace();
return minimalRules;
}
}
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
{
}
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new frmMain().setVisible(true);
}
});
}
public static void main(String[] args) throws Exception {
OSType type = OSInfo.getOSType();
if (type != OSType.WINDOWS) {
System.out.println("This test is for Windows only... skipping!");
return;
}
SwingUtilities.invokeAndWait(() -> {
try {
UIManager.setLookAndFeel(new WindowsLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
System.out.println("Creating JFileChooser...");
JFileChooser fileChooser = new JFileChooser();
System.out.println("Test passed: chooser = " + fileChooser);
});
// Test fails if creating JFileChooser hangs
}
/** Calculate the height of rows based on the current font. */
private void calcRowHeight() {
//Users of themes can set an explicit row height, so check for it
Integer i = (Integer) UIManager.get("netbeans.outline.rowHeight"); //NOI18N
int rHeight = 20;
if (i != null) {
rHeight = i.intValue();
} else {
//Derive a row height to accomodate the font and expando icon
Font f = getFont();
FontMetrics fm = getFontMetrics(f);
int h = Math.max (fm.getHeight () + fm.getMaxDescent (),
DefaultOutlineCellRenderer.getExpansionHandleHeight ());
rHeight = Math.max (rHeight, h) + 2; // XXX: two pixels for cell's insets
}
//Set row height. If displayable, this will generate a new call
//to paint()
setRowHeight(rHeight);
}
protected void addSubComponents() {
leftPanel = new JPanel();
iconLabel = new JLabel();
titleLabel = new JLabel();
iconLabel.setBorder( new FlatEmptyBorder( UIManager.getInsets( "TitlePane.iconMargins" ) ) );
titleLabel.setBorder( new FlatEmptyBorder( UIManager.getInsets( "TitlePane.titleMargins" ) ) );
leftPanel.setLayout( new BoxLayout( leftPanel, BoxLayout.LINE_AXIS ) );
leftPanel.setOpaque( false );
leftPanel.add( iconLabel );
menuBarPlaceholder = new JComponent() {
@Override
public Dimension getPreferredSize() {
JMenuBar menuBar = rootPane.getJMenuBar();
return (menuBar != null && isMenuBarEmbedded())
? FlatUIUtils.addInsets( menuBar.getPreferredSize(), UIScale.scale( menuBarMargins ) )
: new Dimension();
}
};
leftPanel.add( menuBarPlaceholder );
createButtons();
setLayout( new BorderLayout() );
add( leftPanel, BorderLayout.LINE_START );
add( titleLabel, BorderLayout.CENTER );
add( buttonPanel, BorderLayout.LINE_END );
}
public ModernSliderUI(JSlider b)
{
super(b);
thumbColor = Color.GRAY;
UIManager.put("Slider.shadow", Color.DARK_GRAY);
UIManager.put("Slider.highlight", Color.DARK_GRAY);
}
/**
* Check behaviour of method TitledBorder.getTitleFont()
*/
private static void checkTitleFont() {
TitledBorder titledBorder = new TitledBorder(new EmptyBorder(1, 1, 1, 1));
Font defaultFont = UIManager.getLookAndFeelDefaults().getFont("TitledBorder.font");
Font titledBorderFont = titledBorder.getTitleFont();
// check default configuration
if (defaultFont == null) {
if (titledBorderFont == null) {
return;
}
else {
throw new RuntimeException("TitledBorder default font should be null");
}
}
if (!defaultFont.equals(titledBorderFont)) {
throw new RuntimeException("L&F default font " + defaultFont.toString()
+ " differs from TitledBorder font " + titledBorderFont.toString());
}
// title font is explicitly specified
Font font = new Font("Dialog", Font.PLAIN, 10);
titledBorder.setTitleFont(font);
if (!font.equals(titledBorder.getTitleFont())) {
throw new RuntimeException("TitledBorder font should be " + font.toString());
}
// title Font is unspecified
titledBorder.setTitleFont(null);
if (!defaultFont.equals(titledBorder.getTitleFont())) {
throw new RuntimeException("L&F default font " + defaultFont.toString()
+ " differs from TitledBorder font " + titledBorderFont.toString());
}
}
public static void main(String[] args) throws Exception {
robot = new Robot();
robot.delay(2000);
UIManager.LookAndFeelInfo[] lookAndFeelArray
= UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo lookAndFeelItem : lookAndFeelArray) {
executeCase(lookAndFeelItem.getClassName());
}
}
public static void setUpLookAndFeel(Window mainWindow) {
try {
final String laf = PREFERENCES.get(LOOK_AND_FEEL_KEY, UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(mainWindow);
} catch (Throwable e) {
// Just ignore if the L&F has any errors
}
}
public PlatformsView() {
super();
this.setPopupAllowed(false);
this.setDefaultActionAllowed(false);
this.setRootVisible(false);
this.tree.setEditable(false);
this.tree.setShowsRootHandles(false);
this.setBorder(UIManager.getBorder("Nb.ScrollPane.border")); // NOI18N
setPreferredSize(new java.awt.Dimension(200, 334));
}
public EditorToolbar() {
Border b = UIManager.getBorder("Nb.Editor.Toolbar.border"); //NOI18N
setBorder(b);
if( "Aqua".equals(UIManager.getLookAndFeel().getID()) ) { //NOI18N
setBackground(UIManager.getColor("NbExplorerView.background")); //NOI18N
}
}
private void initUI() {
// Trying to set Nimbus look and feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception ex) {
Logger.getLogger(SwingApplet.class.getName()).
log(Level.SEVERE, "Failed to apply Nimbus look and feel", ex);
}
getContentPane().setLayout(new FlowLayout());
button = new JButton("Hello, I'm a Swing Button!");
getContentPane().add(button);
getContentPane().doLayout();
}
protected void keyEvent(KeyEvent e) {
Number delay = (Number) UIManager.get("textSelectionDelay");
if (delay == null)
delay = Integer.valueOf(500);
if (e.getWhen() - lastKeyEvent > delay.intValue()) {
typedText.delete(0, typedText.length());
}
String origTypedText = typedText.toString();
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE
|| e.getKeyCode() == KeyEvent.VK_DELETE) {
if (typedText.length() != 0) {
typedText.substring(0, typedText.length() - 1);
}
} else {
char ch = e.getKeyChar();
if (ch != KeyEvent.CHAR_UNDEFINED) {
typedText.append(ch);
}
}
if (!origTypedText.equals(typedText.toString())) {
lastKeyEvent = e.getWhen();
boolean success = changeSelectionUsingText(e, typedText.toString());
if (success)
e.consume();
}
}
public AltConfigWizard() {
super();
// Set the Look and Feel of the application to the operating
// system's look and feel.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
Activator.getDefault().logError(e);
}
setWindowTitle("CogniCrypt");
final ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin("de.cognicrypt.codegenerator", "platform:/plugin/de.cognicrypt.core/icons/cognicrypt-medium.png ");
setDefaultPageImageDescriptor(image);
this.constraints = new LinkedHashMap<>();
}
RowHeaderRenderer(final JTable table) {
this.table = table;
normalBorder = UIManager.getBorder("TableHeader.cellBorder");
selectedBorder = BorderFactory.createRaisedBevelBorder();
final JTableHeader header = table.getTableHeader();
normalFont = header.getFont();
selectedFont = normalFont.deriveFont(normalFont.getStyle() | Font.BOLD);
setForeground(header.getForeground());
setBackground(header.getBackground());
setOpaque(true);
}
private Painter getPainter(Map<String, Object> defaults, String key) {
Object p = defaults.get(key);
if (p instanceof UIDefaults.LazyValue) {
p = ((UIDefaults.LazyValue)p).createValue(UIManager.getDefaults());
}
return (p instanceof Painter ? (Painter)p : null);
}
private void patchUI( JFileChooser fc ) {
// turn top-right buttons into toolbar buttons
Component topPanel = fc.getComponent( 0 );
if( (topPanel instanceof JPanel) &&
(((JPanel)topPanel).getLayout() instanceof BorderLayout) )
{
Component topButtonPanel = ((JPanel)topPanel).getComponent( 0 );
if( (topButtonPanel instanceof JPanel) &&
(((JPanel)topButtonPanel).getLayout() instanceof BoxLayout) )
{
Insets margin = UIManager.getInsets( "Button.margin" );
Component[] comps = ((JPanel)topButtonPanel).getComponents();
for( int i = comps.length - 1; i >= 0; i-- ) {
Component c = comps[i];
if( c instanceof JButton || c instanceof JToggleButton ) {
AbstractButton b = (AbstractButton)c;
b.putClientProperty( FlatClientProperties.BUTTON_TYPE,
FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON );
b.setMargin( margin );
b.setFocusable( false );
} else if( c instanceof Box.Filler )
((JPanel)topButtonPanel).remove( i );
}
}
}
// increase maximum row count of directory combo box popup list
try {
Component directoryComboBox = ((JPanel)topPanel).getComponent( 2 );
if( directoryComboBox instanceof JComboBox ) {
int maximumRowCount = UIManager.getInt( "ComboBox.maximumRowCount" );
if( maximumRowCount > 0 )
((JComboBox<?>)directoryComboBox).setMaximumRowCount( maximumRowCount );
}
} catch( ArrayIndexOutOfBoundsException ex ) {
// ignore
}
}