Trying to make a triangular JButton, however unexpected shapes appear in the background, as shown in the picture.
When used in my GUI, the background of the button contains seemingly random parts of other element (instead of just a transformation of the triangle). Resizing the window sometimes changes the shape of the background also. So far I have only tried this on Windows, so I don't know if this is platform specific.
I also don't understand why the triangle is point down, as the second y coordinate is positive.
public class TriangleButton extends JButton {
private Polygon shape;
public TriangleButton() {
this.initialize();
}
private void initialize() {
int[] xpoints = {0, 50, 100};
int[] ypoints = {0, 50, 0};
this.shape = new Polygon(xpoints, ypoints, 3);
this.setSize(new Dimension(100, 50));
this.setMinimumSize(this.getSize());
this.setMaximumSize(this.getSize());
this.setPreferredSize(this.getSize());
this.setForeground(Color.BLACK);
}
protected void paintComponent(Graphics g) {
Graphics2D gCopy = (Graphics2D) g.create();
gCopy.fillPolygon(this.shape);
}
public boolean contains(int x, int y) {
return this.shape.contains(x, y);
}
protected void paintBorder(Graphics g) {
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
TriangleButton button = new TriangleButton();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}