我正在编写一个小游戏,需要小按钮而不是自定义绘制的JPanel。我的解决方案很简单,但它有一些问题。
class TargetButton extends JButton {
private Point point;
public TargetButton(Point point) {
this.point = point;
}
public Point getPoint() {
return point;
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.RED.darker());
g2.draw(new Ellipse2D.Double(0, 0, getWidth()-1, getHeight()-1));
}
}
它们是这样创建的:
public void setTargets(List<Point> pts) {
for (Point point : pts) {
TargetButton target = new TargetButton(point);
targets.add(target); // list of target buttons
target.setBounds((int)__(point.getX()), (int)__(point.getY()), (int)(track.getWidth()*scale/resolution), (int)(track.getWidth()*scale/resolution));
target.addActionListener(this);
add(target);
}
invalidate();
repaint();
}
按钮正确显示为圆圈,但是当我将它们悬停时,它们会被涂在黑色或白色背景上,看起来非常难看。
我没有打电话给super.paintComponent(g)
,因为我不想要默认外观。我还试图扩展AbstractButton
,但它不会对点击做出回应。