I have a JButton, and clicking on it opens a modal dialog. When I close the dialog, the button still looks as if it is still pressed until I move the mouse. I think this is because the JDialog opens on top of the AWT component (it is a third-party component that uses AWT Canvas, and I cannot change this). If I open a dialog and close it using the swing component, it will work correctly.
I tried adding a window to the window's listener window and repainting the entire frame (using repaint and paintImmediately) when the dialog closes, but this does not work. Any suggestions on how to fix this?
Here is an example of SSCCE. Click the button and close the dialog box. Note that the focus border is still around the button until we move the mouse pointer to the green section.
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DialogExample
{
public static void main(String[] args) throws Exception
{
final JFrame jf = new JFrame("AWT/Swing Dialog Test");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("show dialog");
final Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
}
};
canvas.setPreferredSize(new Dimension(200,200));
button.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e)
{
JDialog dlg = new JDialog(jf,"modal");
dlg.add(new JLabel("hello"));
dlg.setModal(true);
dlg.pack();
dlg.setLocationRelativeTo(canvas);
dlg.setVisible(true);
}
});
button.setText("press me");
button.setFocusable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.setPreferredSize(new Dimension(200, 200));
jf.setLayout(new BorderLayout());
panel.add(button);
jf.add(panel, BorderLayout.NORTH);
jf.add(canvas, BorderLayout.SOUTH);
jf.setSize(new Dimension(400,400));
jf.setVisible(true);
}
}
source
share