Posted on Oct 21, 2018 By Keyu Zhao
Swing本来提供的滑块JSlider丑的实在不忍直视,所以很有必要进行优化重写
提供有两种方法进行JSlider的美化
运用look and feel
那什么是 LookAndFeel 呢?
通俗的说,这就是皮肤;
从功能上说。这是一种批量管理 Swing 控件外观的机制;
从根源来说,这是 Swing 的核心。
在Swing中只需一行代码就可以改变皮肤
UIManager.setLookAndFeel(new LookAndFeel());
比如:
UIManager.setLookAndFeel(new QuaquaLookAndFeel());
我们还可以通过
UIManager.setLookAndFeel(String s);
来改变外观,其中,s是表示该外观的路径,比如
UIManager.setLookAndFeel("org.fife.plaf.OfficeXP.OfficeXPLookAndFeel");
以下是一些java自带的look and feel,当然还可以去网上下载其他的.
UIManager.setLookAndFeel(com.sun.java.swing.plaf.windows.WindowsLookAndFeel.class.getName());//还可以,只能在windows系统中用,也就是这句代码不跨平台
UIManager.setLookAndFeel(javax.swing.plaf.nimbus.NimbusLookAndFeel.class.getName());//还可以
UIManager.setLookAndFeel(javax.swing.plaf.basic.BasicLookAndFeel.class.getName());//swing默认的丑皮肤
UIManager.setLookAndFeel(javax.swing.plaf.metal.MetalLookAndFeel.class.getName());//swing默认的丑皮肤
UIManager.setLookAndFeel(com.sun.java.swing.plaf.motif.MotifLookAndFeel.class.getName());//丑
UIManager.setLookAndFeel(com.sun.java.swing.plaf.gtk.GTKLookAndFeel.class.getName());//还可以
重写JSlider UI
JSlider playTime = new JSlider();
playTime.setUI(new javax.swing.plaf.metal.MetalSliderUI(){
@Override
public void paintThumb(Graphics g) {
//绘制指示物
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.white);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(thumbRect.x, thumbRect.y, thumbRect.width,
thumbRect.height);//修改为圆形
//也可以帖图(利用鼠标事件转换image即可体现不同状态)
//g2d.drawImage(image, thumbRect.x, thumbRect.y, thumbRect.width,thumbRect.height,null);
}
public void paintTrack(Graphics g) {
//绘制刻度的轨迹
int cy,cw;
Rectangle trackBounds = trackRect;
if (slider.getOrientation() == JSlider.HORIZONTAL) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.black);//将背景设为黑色
cy = (trackBounds.height/2) - 2;
cw = trackBounds.width;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.translate(trackBounds.x, trackBounds.y + cy);
g2.fillRect(0, -cy + 5, cw, cy);
int trackLeft = 0;
int trackRight = 0;
trackRight = trackRect.width - 1;
int middleOfThumb = 0;
int fillLeft = 0;
int fillRight = 0;
//换算坐标
middleOfThumb = thumbRect.x + (thumbRect.width / 2);
middleOfThumb -= trackRect.x;
if (!drawInverted()) {
fillLeft = !slider.isEnabled() ? trackLeft : trackLeft + 1;
fillRight = middleOfThumb;
} else {
fillLeft = middleOfThumb;
fillRight = !slider.isEnabled() ? trackRight - 1
: trackRight - 2;
}
//设定渐变,在这里从红色变为红色,则没有渐变,滑块划过的地方自动变成红色
g2.setPaint(new GradientPaint(0, 0, Color.red, cw, 0,
Color.red, true));
g2.fillRect(0, -cy + 5, fillRight - fillLeft, cy);
g2.setPaint(slider.getBackground());
g2.fillRect(10, 10, cw, 5);
g2.setPaint(Color.WHITE);
g2.drawLine(0, cy, cw - 1, cy);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2.translate(-trackBounds.x, -(trackBounds.y + cy));
}
else {
super.paintTrack(g);
}
}
});
效果图
JSlider
网友评论