我想创建自己的自定义按钮,其中包含已定义的大小和已定义的颜色。
为此,我使用自定义组件创建了一个扩展JButton的类。
不幸的是,我意识到当我覆盖paintComponent()
并在方法结束时调用super.paintComponent(g)
时,它会导致覆盖颜色设置。但是,如果我不调用super方法,则该按钮不再具有可点击功能。
如果我的代码中有任何错误或缺少某些内容,是否有任何建议?有任何建议来实现我的目标吗?
答案 0 :(得分:2)
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
答案 1 :(得分:0)
我也试过这种方式,但是在开头将调用放到super方法会导致文本按钮不再可见! 实际上在这两种情况下我都调用了super方法,我已经覆盖了我设置的属性。
我的目标是改变按钮的大小,形状和颜色,以及其他所有其他Jbutton角色。 这是我的代码。
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (getModel().isArmed()) {
g2d.setColor(Color.LIGHT_GRAY);
} else {
g2d.setColor(this.colorwell);
}
g2d.fillOval(0, 0, getSize().width-1,getSize().height-1);
g.dispose();
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}