0

Trying to make a triangular JButton, however unexpected shapes appear in the background, as shown in the picture.

Strange shapes?

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);

    }

}
  • 1
    You've failed to honour the paint chain by not calling `super.paintComponent` before you do any additional painting. Also, as a general rule, if you `create` it, you should `dispose` of it – MadProgrammer Mar 13 '17 at 21:09
  • Remember, when overriding methods, you either need to be willing to take over ALL their responsibility or call the `super` method – MadProgrammer Mar 13 '17 at 21:11

0 Answers0