Note that there are some explanatory texts on larger screens.

plurals
  1. POJButton subclass with custom shape shifts during repainting
    primarykey
    data
    text
    <p>I have just started working with Swing and am trying to draw a button with a custom shape, a triangle in this example. I called the JButton subclass 'ShiftingButton' in the following code because of its unusual behavior. When the mouse enters its region, it is repainted with an offset from its original position. Furthermore the shifted, offset version is drawn in addition to the original position so that both the original and shifted versions appear together. That is, when I run this code, the button is shown as a triangle along the left edge of the window. Then when I run the mouse over the button, a new triangle is drawn (in addition to the old one), shifted down and to the right by about 10 pixels. Resizing the window changes the offset of the phantom button from the original.</p> <p>Experimenting with mouse clicks shows that only the original, correctly-positioned button is active. The region of the offset phantom button is not active.</p> <pre><code>import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; import java.awt.Polygon; public class ShiftingButton extends JButton implements ActionListener { private Polygon shape; public ShiftingButton () { initialize(); addActionListener(this); } protected void initialize() { shape = new Polygon(); setSize(120, 120); shape.addPoint(0, 0); shape.addPoint(0, 60); shape.addPoint(90, 0); setMinimumSize(getSize()); setMaximumSize(getSize()); setPreferredSize(getSize()); } // Hit detection public boolean contains(int x, int y) { return shape.contains(x, y); } @Override public void paintComponent (Graphics g) { System.err.println("paintComponent()"); g.fillPolygon(shape); } protected void paintBorder(Graphics g) { } @Override public void actionPerformed (ActionEvent ev) { System.out.println("ShiftingButton ActionEvent!"); } public static void main (String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); ShiftingButton button = new ShiftingButton(); panel.add(button); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.pack(); frame.setVisible(true); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload