java-如何创建带有圆角的JButton扩展?
作者:互联网
这是问题“Java rounded Swing JButton”的继续.我已经搜索了javax.swing.JButton的扩展名,该扩展名将继承所有运行时行为,并且仅覆盖角的绘制.
使用sun forums page在sun forums page上给出的代码,结果如下所示:
我希望能够在背景,鼠标悬停变化等时具有相同的渐变.有人知道如何做到这一点吗?
从图片创建Java Swing窗口的代码是:
public class XrButton extends JButton implements MouseListener {
private static final long serialVersionUID = 9032198251140247116L;
String text;
boolean mouseIn = false;
public XrButton(String s) {
super(s);
text = s;
setBorderPainted(false);
addMouseListener(this);
setContentAreaFilled(false);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if (getModel().isPressed()) {
g.setColor(g.getColor());
g2.fillRect(3, 3, getWidth() - 6, getHeight() - 6);
}
super.paintComponent(g);
if (mouseIn)
g2.setColor(Color.red);
else
g2.setColor(new Color(128, 0, 128));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.2f));
g2.draw(new RoundRectangle2D.Double(1, 1, (getWidth() - 3),
(getHeight() - 3), 12, 8));
g2.setStroke(new BasicStroke(1.5f));
g2.drawLine(4, getHeight() - 3, getWidth() - 4, getHeight() - 3);
g2.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
XrButton xrButton = new XrButton("XrButton");
JButton jButton = new JButton("JButton");
frame.getContentPane().add(xrButton);
frame.getContentPane().add(jButton);
frame.setSize(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
mouseIn = true;
}
public void mouseExited(MouseEvent e) {
mouseIn = false;
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
解决方法:
我认为您在这里有2个选择:
1,用组件的绘制方法进行绘制
2.为您的外观创建新的ButtonUI.在这种情况下,我建议使用Synch LAF
在两种情况下,绘制不同的状态都是您的责任
标签:swing,jbutton,rounded-corners,java 来源: https://codeday.me/bug/20191210/2102833.html