java panel 绘制_java – JPanel什么时候绘制(或重绘)它的子组件?

我已经将示例简化为抗锯齿,我无法重现该问题.它似乎不依赖于平台.我不确定你为什么使用getClipBounds().

附录:

The JPanel background (a gradient) needs to shine through…

我更新了示例,使用透明按钮后面的渐变背景;我并排放置了反锯齿(左)和别名(右)的例子.我没有看到意外的行为.

import java.awt.Color;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.GradientPaint;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.GridLayout;

import java.awt.RenderingHints;

import javax.swing.JButton;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.plaf.basic.BasicButtonUI;

/** @see http://stackoverflow.com/questions/5169647 */

public class ButtonUITest extends JPanel {

public ButtonUITest() {

this.setLayout(new GridLayout(1, 0));

this.setPreferredSize(new Dimension(640, 480));

this.add(new CustomButton(true));

this.add(new CustomButton(false));

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

int w = this.getWidth();

int h = this.getHeight();

Graphics2D g2d = (Graphics2D) g;

g2d.setPaint(new GradientPaint(0, 0, Color.blue, w, h, Color.red));

g2d.fillRect(0, 0, w, h);

}

private void display() {

JFrame f = new JFrame("ButtonUITest");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.add(this);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

}

private static class CustomButton extends JButton {

public CustomButton(boolean antialiased) {

this.setOpaque(false);

this.setUI(new CustomButtonUI(antialiased));

}

}

private static class CustomButtonUI extends BasicButtonUI {

private boolean antialiased;

public CustomButtonUI(boolean antialiased) {

this.antialiased = antialiased;

}

@Override

public void paint(Graphics g, JComponent c) {

int w = c.getWidth();

int h = c.getHeight();

Graphics2D g2d = (Graphics2D) g;

if (antialiased) {

g2d.setRenderingHint(

RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

}

g2d.setColor(Color.LIGHT_GRAY);

g2d.fillOval(0, 0, w, 2 * h);

}

}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

new ButtonUITest().display();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值