本文实例讲述了Java实现Swing组件定制Button。分享给大家供大家参考,具体如下:
先来看看运行效果图:
具体代码如下:
package themedemo;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Painter;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class ButtonSkinDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (UIManager.LookAndFeelInfo laf : UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
try {
UIManager.setLookAndFeel(laf.getClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
for (Map.Entry entry : UIManager
.getLookAndFeelDefaults().entrySet()) {
if ((entry.getKey().toString()).startsWith("Button")) {
System.out.println(entry.getKey() + " = "
+ entry.getValue());
}
}
JFrame frame = new JFrame("www.jb51.net - Button Skining Demo");
frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridLayout(0,1,20,20));
panel.setBorder(BorderFactory.createEmptyBorder(20,20));
panel.setBackground(Color.darkGray);
UIDefaults buttonDefaults = new UIDefaults();
buttonDefaults.put("Button.backgroundPainter",new Painter() {
public void paint(Graphics2D g,JComponent c,int w,int h) {
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(2f));
g.setColor(Color.WHITE);
g.fillRoundRect(0,w - 2,h - 2,8,8);
g.setColor(Color.LIGHT_GRAY);
g.drawRoundRect(0,8);
}
});
buttonDefaults.put("Button[Pressed].backgroundPainter",RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(2f));
g.setColor(Color.LIGHT_GRAY);
g.fillRoundRect(0,8);
}
});
JButton button = new JButton("myButton");
panel.add(button);
button.putClientProperty("Nimbus.Overrides",buttonDefaults);
button.putClientProperty("Nimbus.Overrides.InheritDefaults",false);
// Add a normal themed slider for comparison
JButton normalButton = new JButton("normalButton");
panel.add(normalButton);
frame.getContentPane().add(panel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
希望本文所述对大家java程序设计有所帮助。
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250