Java 改变按钮外观

来源:百度知道 编辑:UC知道 时间:2024/05/30 14:54:01
Java 改变按钮外观
我看到有的按钮是椭圆的,或圆的,或很花哨的。
鼠标移到上面还会变化。
希望给出完整代码,分我可以加。

通常swing自定义组件继承javax.swing.JComponent并重写protected void paintComponent(Graphics g)方法实现自定义绘制。 重写paintComponent方法时通常要先去掉super.paintComponent(g),因为父方法调用会绘制背景色。不妨先看一下源代码中的调用过程。

在JComponent.java中paintComponent(Graphics g)方法定义如下:

protected void paintComponent(Graphics g) {
if (ui != null) {
Graphics scratchGraphics = (g == null) ? null : g.create();
try {
ui.update(scratchGraphics, this);
}
finally {
scratchGraphics.dispose();
}
}
}

其中ui的声明如下
protected transient ComponentUI ui;
然后转向ComponentUI的update(Graphics g, JComponent c)方法:

public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRect(0, 0, c.getWidth(),c.getHeight());
}
paint(g, c);
}

可见如果发现组件是非透明的,就绘制背景,