trinity420 trinity420 - 4 months ago 49
Java Question

Java JOptionPane custom draw on background

I made a Java Desktop Application with a Swing GUI. In the menu bar there is a "About" entry. When clicking this "About" menu item, a JDialog is displayed using JOptionPane.showMessageDialog(...) with an icon, a text about my program and a "OK"-Button to close the dialog.

I want to draw an effect of one or more balls (circles) that move around in the background of the dialog and changeing their colors.

My first try was to create a class that extends from JOptionPane and overrides the paint() method. In the paint method I tried to draw some circles but it does not work. I think the draw method isn't even called.

How can I achieve this?

Excerpt of my code:

class MyEffectPane extends JOptionPane {

@Override
protected void paintComponent(Graphics g) {
System.err.println("paintComponent"); // never called

super.paintComponent(g);
}

@Override
public void paint(Graphics g) {

System.err.println("painting"); // never called

int width = getWidth();
int height = getHeight();

Graphics2D g2 = (Graphics2D) g;

g.fillOval(width/2-50, height/2-50, 50, 50);

super.paint(g);
}

}


Call:

new MyEffectPane().showMessageDialog(this, "Dev by Me (c) 2016", "About", JOptionPane.INFORMATION_MESSAGE, icon);

Answer

The showMessageDialog method is static (you can't override it) and it creates its own JOptionPane object.

You can reproduce what the showMessageDialog is doing, which is:

 /**
 * This method shows an INFORMATION_MESSAGE type message dialog.
 *
 * @param parentComponent The component to find a frame in.
 * @param message The message displayed.
 */
public static void showMessageDialog(Component parentComponent, Object message){
  JOptionPane pane = new JOptionPane(message, INFORMATION_MESSAGE);
  JDialog dialog = pane.createDialog(parentComponent, null);
  dialog.show();   
}

And you can change it to something like this:

MyEffectPane pane = new MyEffectPane("message....", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(this, null);
dialog.show();

Also, you will have to add this constructor to your MyEffectPane class:

MyEffectPane(String message, int type){
    super(message, type);
}
Comments