Java按钮上出现不需要的图像



我正在尝试在Java中使用多边形按钮。我找到了这个代码:

package testklassen;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PolygonButton extends JButton {
private Polygon shape;
public PolygonButton(int[] x, int[] y) {
this.shape = new Polygon();

this.initialize(x, y);
}
protected void initialize(int[] x, int[] y) {
Point p1, p2, p3, p4, p5;
this.setSize(90, 120);
p1 = new Point(x[0], y[0]);
p2 = new Point(x[1], y[1]);
p3 = new Point(x[2], y[2]);
p4 = new Point(x[3], y[3]);
p5 = new Point(x[4], y[4]);
this.shape.addPoint((int) Math.round(p1.getX()),
(int) Math.round(p1.getY()));
this.shape.addPoint((int) Math.round(p2.getX()),
(int) Math.round(p2.getY()));
this.shape.addPoint((int) Math.round(p3.getX()),
(int) Math.round(p3.getY()));
this.shape.addPoint((int) Math.round(p4.getX()),
(int) Math.round(p4.getY()));
this.shape.addPoint((int) Math.round(p5.getX()),
(int) Math.round(p5.getY()));
this.setMinimumSize(this.getSize());
this.setMaximumSize(this.getSize());
this.setPreferredSize(this.getSize());
}
// Hit detection
public boolean contains(int x, int y) {
return this.shape.contains(x, y);
}
// Draw Button
protected void paintComponent(Graphics g) {
Graphics2D gCopy = (Graphics2D) g.create();
gCopy.fillPolygon(this.shape);
}
}

为了测试这一点,我构建了一个简单的框架,其中包含一个多边形按钮和一个普通按钮:

package testklassen;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameForPolygonButton extends JFrame {


int[] x = {0, 50, 100, 100, 0};
int[] y = {0, 50, 0, 100, 100};
PolygonButton polygonButton = new PolygonButton(x, y);
JButton button = new JButton();

public FrameForPolygonButton() { 

super();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 530; 
int frameHeight = 400;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);

setVisible(true);
button.setBounds(200, 200, 50, 50);
cp.add(button);

//polygonButton.setBorder(null);

cp.add(polygonButton);

} 

public static void main(String[] args) {
new FrameForPolygonButton();    
}
} 

这就是开始时的样子。这正是我想要的。

但是,当我将鼠标悬停在另一个JButton上,然后将鼠标悬停回PolygonButton 上时

PolygonButton 上会显示JButton的图片

有人知道吗,我该如何避免这种情况?

我找到了这个问题的解决方案。但我仍然不知道,为什么会发生这种事。如果有人知道,我会感兴趣的。

对我有效的解决方案是添加以下行:

polygonButton.setOpaque(false);

相关内容

  • 没有找到相关文章

最新更新