I would like to display an opaque overlay with a loading description or spinner over the top of my JFrame when a button is clicked and disappear again when the action has been performed. I have read up on Glass Pane but I cannot understand the right way to do this underneath an action performed function with a button. Is there a way to do this using Java and Swing? By the way here is my JFrame at the moment...
public class Frame {
private JButton btnH;
/** Main Panel */
private static final Dimension PANEL_SIZE = new Dimension(500, 500);
private static JPanel panel = new JPanel();
public Frame() {
init();
panel.setLayout(null);
panel.setPreferredSize(PANEL_SIZE);
}
public void init() {
btnH = new JButton("HELP");
btnH.setBounds(50, 50, 100, 25);
panel.add(btnH);
// Action listener to listen to button click and display pop-up when received.
btnH.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// Message box to display.
JOptionPane.showMessageDialog(null, "Helpful info...", JOptionPane.INFORMATION_MESSAGE);
}
});
}
public JComponent getComponent() {
return panel;
}
private static void createAndDisplay() {
JFrame frame = new JFrame("Frame");
frame.getContentPane().add(new Frame().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndDisplay();
}
});
}
There hard part about this isn't the glass pane, but the interoperability between the UI and the
SwingWorker.There are lots of ways you might do this, this is just one.
You should start by reading through How to Use Root Panes which goes into how to use glass panes and Worker Threads and SwingWorker, because until you get your head around it, it will mess with you.
The important things to note here are:
SwingWorkeris forHence, the importance of the
SwingWorkerJust as a side note, I have verified that the
PropertyChangeListenerused by theSwingWorkeris updated within the context of the EDTYou should also take a look at
JLayer(formally known asJXLayer)For example, example
It's like glass pane on steroids
Now, if you really want to do something fancy, you could do something like this for example