I am coding a simple java program. It takes three parameteres. A folder containing images, a desired output folder and an image watermark file. The programs copies a watermarked image of every image in the input folder into the output folder.
I am writing a simple GUI. The user introduces the three parameters and presses a button. The programm works but I want to provide feedback to the user. I want to be able to update a JLabel field everytime an image is processed.
In my WatermarkFolders class i use this code snippet to show the user some feedback:
Gui.FEEDBACK.setText(text);
The issue is that the JLabel does not update each time an image is processed. It just updates with the 100% complete output when the processing is done.
Is there an easy way to update this asynchrously. Thanks for the answers.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Gui extends JPanel {
JButton button;
JFileChooser chooser;
JLabel inputLabel = new JLabel("Directorio donde estan las imagenes");
JTextField inputField = new JTextField(15);
JLabel outputLabel = new JLabel("Directorio donde guardar las copias con marca de agua");
JTextField outputField = new JTextField(15);
JLabel watermarkLabel = new JLabel("Archivo marca de agua (gif transparente)");
JTextField watermarkField = new JTextField(15);
public static JLabel FEEDBACK = new JLabel("Número de Imágenes: ");
JProgressBar pb;
public Gui() {}
public void go() {
JFrame frame = new JFrame("Añadir Marcas de Agua a todas las imágenes de un directorio");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton button = new JButton("Añadir Marca de Agua a las imágenes");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String input = inputField.getText();
String output = outputField.getText();
String watermark = watermarkField.getText();
if(!input.equals("") && !output.equals("") && !watermark.equals("")) {
WatermarkFolders wm = new WatermarkFolders(input, output, watermark);
wm.run();
}
}
});
panel.add(inputLabel);
panel.add(inputField);
panel.add(outputLabel);
panel.add(outputField);
panel.add(watermarkLabel);
panel.add(watermarkField);
panel.add(button);
panel.add(FEEDBACK);
frame.getContentPane().add(BorderLayout.WEST,panel);
frame.setVisible(true);
frame.pack();
}
public static void main(String s[]) {
Gui gui = new Gui();
gui.go();
}
}
Yes, processes that take time should not be on the EDT. Instead use a SwingWorker class to run the long running task while you make updates to the GUI at the same time.
You can use the SwingUtilities.invokeLater() method to update the GUI from another thread, or you could have a Swing Timer check the status of a task and update the GUI while it still runs.