How to use Swing and thread's?
Hello guys!I hope for some hint's and idea's how develope this in a "best practice" maner.
My question is how to develop a swing app that in the background listens for changes in the file system.
Below I have a test app, but as you can see I have put the listener-code last in the main-method.
The app opens a new JFrame if there is any changes in the user.dir.
I bet there must be a better pattern for this.
All ideas where to put the listener code are most welcome!
Best regards
Fredrik
package filelistener;
import java.io.File;
public class Listener extends JPanel
{
private static JFrame jFrame = new JFrame("Listener");
private static JLabel jLabel = new JLabel( System.getProperty("user.dir" ));
private static Path path = Paths.get( System.getProperty("user.dir" ));
private static ListenerDialog listenerDialog;
public Listener()
{
add(jLabel);
}
private static void createAndShowGUI()
{
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setResizable(false);
jFrame.getContentPane().add(new Listener());
jFrame.pack();
jFrame.validate();
jFrame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
try
{
WatchService watchService = path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
for(;;)
{
WatchKey watckKey = watchService.take();
List<WatchEvent<?>> watchEvents = watckKey.pollEvents();
for (WatchEvent watchEvent : watchEvents)
{
if(listenerDialog == null)
{
listenerDialog = new ListenerDialog(jFrame);
}
listenerDialog.jTextArea.setText( listenerDialog.jTextArea.getText() +"\n"+ watchEvent.context().toString() );
}
boolean valid = watckKey.reset();
if (!valid)
{
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class ListenerDialog extends JFrame
{
JPanel jPanel = new JPanel();
JTextArea jTextArea = new JTextArea(20, 8);
public ListenerDialog(JFrame parentFrame)
{
super("Dialog");
jTextArea.setEditable(false);
JScrollPane scrollPaneText = new JScrollPane(jTextArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jPanel.add( scrollPaneText );
getContentPane().add( jPanel );
setResizable(false);
pack();
setVisible(true);
}
}