我正在使用从 JButton 扩展的类 KButton,我添加了一些代码,使其更加美观,例如更改字体、设置圆角边框、使用 Graphics 和 Graphics2D 更改背景。然而,当我想添加代码以使其在移动时改变颜色时,它不起作用!我的代码在这里
public class KButton extends JButton implements MouseMotionListener{
private static final long serialVersionUID = 1L;
public KButton(){
setStyle();
}
public KButton(String text){
super(text);
this.setText(text);
setStyle();
addMouseMotionListener(this);
}
public void setStyle(){
setFont(new Font("San Serif",Font.PLAIN,12));
setContentAreaFilled(false);
setBorder(new RoundedBorder(3));
}
@Override
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g.create();
g2.setPaint(new GradientPaint(new Point(0, 0), Color.WHITE, new Point(0, getHeight()), Color.LIGHT_GRAY));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.paintComponent(g);
}
@Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent arg0) {
Graphics g=this.getGraphics();
Graphics2D g2 = (Graphics2D)g.create();
g2.setPaint(new GradientPaint(new Point(0, 0), Color.WHITE, new Point(0, getHeight()), Color.BLUE.brighter()));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.setText(getText());
setBorder(new RoundedBorder(3));
super.paintComponent(g);
}
}
这似乎不起作用!
最佳答案
不要使用getGraphics
。执行自定义绘制的适当位置是在 paintComponent
方法中。 getGraphics
是对上次用于绘制组件的图形上下文的临时引用,当组件被重新绘制时,任何更改都将被各种 paintXxx
方法中的更改覆盖。
您也不应该自己调用任何 paintXxx
方法(当然,除非您尝试将组件渲染为图像)
相反,请使用状态标志来更改 paintComponent
的工作方式,并在想要更新状态时调用 repaint
。
就您而言,mouseMoved
方法中至少有两件事会破坏您的绘画工作:setText
和鼠标移动本身。这两者都会导致发生重绘
。
就个人而言,我会使用 MouseListener#mouseEntered
和 MouseListener#mouseExited
并更改按钮模型的状态(例如滚动),然后检查该值在 paintComponent
方法中做出我的绘画决策
另外,请注意 super.paintComponent
将尝试清除图形上下文,准备绘画,并且应该首先调用
关于java - 当鼠标悬停时如何更改java中扩展JButton的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17310844/