gpt4 book ai didi

java - swing创建自定义Jbutton问题

转载 作者:行者123 更新时间:2023-12-02 05:23:54 26 4
gpt4 key购买 nike

我想创建自己的自定义按钮,具有定义的大小和定义的颜色。为此,我使用自定义组件创建了一个扩展 JButton 的类。不幸的是,我意识到当我覆盖 paintComponent() 并在方法末尾调用 super.paintComponent(g) 时,它会导致覆盖所做的颜色设置。但是,如果我不调用 super 方法,按钮就不再具有可点击的功能。

如果我的代码有任何问题或缺少任何内容,有什么建议吗?对于实现我的目标有什么建议吗?

最佳答案

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;

import javax.swing.JButton;
import javax.swing.JFrame;

public class CreateRoundButton extends JButton {
public CreateRoundButton(String label) {
super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width,size.height);
setPreferredSize(size);
//added to remove a border of the text in jbutton
setFocusPainted(false);
setContentAreaFilled(false);
}

protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width-1,getSize().height-1);

super.paintComponent(g);
}

protected void paintBorder(Graphics g) {

g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}

Shape shape;
public boolean contains(int x, int y) {
if (shape == null ||
!shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}

public static void main(String[] args) {
JButton button = new CreateRoundButton("Click");
button.setBackground(Color.gray);

JFrame frame = new JFrame();
frame.getContentPane().add(button);
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(150, 150);
frame.setVisible(true);
}
}

取自这里http://www.roseindia.net/tutorial/java/swing/createRoundButton.html

关于java - swing创建自定义Jbutton问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com