Swing滚动条重写
摘自:https://blog.csdn.net/qq_40064948/article/details/81738191
未验证
1 Swing滚动条重写 2 2018年08月16日 11:17:20 3 阅读数:3 4 package com.bjsxt.view.ui; 5 6 import java.awt.AlphaComposite; 7 import java.awt.Color; 8 import java.awt.Graphics; 9 import java.awt.Graphics2D; 10 import java.awt.Rectangle; 11 12 import javax.swing.ImageIcon; 13 import javax.swing.JButton; 14 import javax.swing.JComponent; 15 import javax.swing.plaf.basic.BasicScrollBarUI; 16 17 /** 18 * 自定义滚动条 19 * @author Silly 20 * 21 */ 22 public class MyScrollBarUI extends BasicScrollBarUI { 23 24 @Override 25 protected void configureScrollBarColors() { 26 // 滑道 27 trackColor = Color.WHITE; 28 } 29 30 @Override 31 protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { 32 super.paintTrack(g, c, trackBounds); 33 } 34 35 //把手 36 @Override 37 protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) { 38 // 把绘制区的x,y点坐标定义为坐标系的原点,这句一定一定要加上,不然拖动就失效了 39 g.translate(thumbBounds.x, thumbBounds.y); 40 // 设置把手颜色 41 g.setColor(new Color(200,200,200)); 42 // 画一个圆角矩形,前4个参数为坐标和宽高,后面两个参数用于控制角落的圆角弧度 43 g.drawRoundRect(5, 0, 6, thumbBounds.height-1, 5, 5); 44 Graphics2D g2 = (Graphics2D) g; 45 //消除锯齿------------没有任何意义注掉 46 // RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 47 // g2.addRenderingHints(rh); 48 // 半透明 49 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); 50 // 设置填充颜色,这里设置了渐变,由下往上 ------------不好看注掉 51 // g2.setPaint(new GradientPaint(c.getWidth() / 2, 1, Color.GRAY, c.getWidth() / 2, c.getHeight(), Color.GRAY)); 52 // 填充圆角矩形 53 g2.fillRoundRect(5, 0, 6, thumbBounds.height-1, 5, 5); 54 } 55 56 @Override 57 protected JButton createIncreaseButton(int orientation) { 58 JButton button = new JButton(produceImage("down.png")); 59 button.setBorder(null); 60 return button; 61 } 62 63 @Override 64 protected JButton createDecreaseButton(int orientation) { 65 JButton button = new JButton(produceImage("up.png")); 66 button.setBorder(null); 67 return button; 68 } 69 70 /** 71 * 获取图片 72 * @param name 图片名称 73 * @return 74 */ 75 private ImageIcon produceImage(String name) { 76 ImageIcon backImage = new ImageIcon("img\scroll\"+name); 77 return backImage; 78 } 79 80 }
1 设置方式: 2 3 JScrollPane friendScro = new JScrollPane(tree); 4 friendScro.getVerticalScrollBar().setUI(new MyScrollBarUI()); 5 来自一个喜欢编程的小姐姐 >.< 6 7 客官~有缘再见!