RFID Phidget Manager attached event - java

I am trying a program with many phidget rfid readers. This test code works fine and I can load up all the readers and have it worked.
Vector phidgetList = manager.getPhidgets();
Enumeration phidgetListEnum = phidgetList.elements();
int count=phidgets.size();
while(phidgetListEnum.hasMoreElements()) {
Phidget phidgetElement = (Phidget) phidgetListEnum
.nextElement();
if (!phidgets.containsKey(phidgetElement.getSerialNumber())) {
RFIDTracking rfi = (RFIDTracking) ct.getTracking("rfid")
.clone();
rfi.setName("rfid clone " + count++);
rfi.detect();
rfi.setCode(phidgetElement.getSerialNumber());
phidgets.put(phidgetElement.getSerialNumber(), rfi);
Thread t = new Thread(rfi);
t.start();
}
}
The problem is when I tried to detect the new readers attached or detached from the system. I used this code
Manager manager;
manager = new Manager();
try {
manager.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae)
{
try
{
System.out.println("attached" + ((RFIDPhidget)ae.getSource()).getSerialNumber());
}
catch (PhidgetException ex) { }
}
});
manager.open();
} catch (PhidgetException exception) {
System.err.println(exception.getErrorNumber()+ exception.getDescription());
}
// Allow the Phidgets time to attach
Thread.sleep(1000);
This code could not detect any reader attachment. I found there is no waitForAttachment(time) in the manager. May I know how to solve this. Thank you in advanced

It's Phidget, but not RFIDPhidget. There is no WaitForAttachment in the manager class because it is not necessary. The previous code works fine, but the wait time must be a little bit longer and the program won't terminate before something is attached.
Manager manager;
manager = new Manager();
try {
manager.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae)
{
try
{
System.out.println("attached" + ((Phidget)ae.getSource()).getSerialNumber());
} catch (PhidgetException ex) { }
}
});
manager.open();
} catch (PhidgetException exception) {
System.err.println(exception.getErrorNumber()+ exception.getDescription());
}
// Allow the Phidgets time to attach
Thread.sleep(1000);

Related

IProgressMonitor is not able to get monitor.isCanceled() method call

Good afternoon and hope you are doing great :)
I have method in which I have written new IRunnableWithProgress and I am getting progress bar and all process updates properly no issue at all.
My issue is I can see cancel button on progress bar dailog but after clicking on it nothing is happening. In short code inside if(monitor.isCanceled()){ sysout("Heloooooooooo") } is not executing at all.
please have a look at code sample :
public void runMappers(final EObject profile, final EObject list, final Notification notification) {
this.notification = notification;
getBroker().stopNotification();
final ProgressMonitorDialog pmd = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
IRunnableWithProgress rwp = new IRunnableWithProgress() {
#Override
public void run(IProgressMonitor monitor) throws InterruptedException {
if (mappers.get(profile) != null) {
int workload = mappers.get(profile).size();
monitor.beginTask("Loading DG list configurations", workload);
Pattern pattern = Pattern.compile("ProfileTo(.*?)ViewMapper");
for (final ProfileToDgListViewMapper mapper : mappers.get(profile)) {
Matcher matcher = pattern.matcher(mapper.toString());
if (matcher.find()) {
monitor.subTask("Loading DG list configuration section " + (matcher.group(1)));
}
mapper.mapProfile(profile, list, notification);
monitor.worked(1);
if(monitor.isCanceled()){
System.out.println("Heloooooooooo");
monitor.done();
Thread.currentThread().interrupt();
return;
}
}
}
monitor.done();
}
};
try {
pmd.run(false, true, rwp);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
}
getBroker().continueNotification();
}
I tried so many things also some stackoverflow answers, suggesting to perform it with Jobs, But i am not sure how can i call my custome method(with some attributes) in the Job.
Please let me know best suggestion
Thanks in advance ..

How do I pause my main thread so my JFrame can operate properly

I read a couple questions related to pausing main and both gave answers I didn't understand, and frankly I don't think are applicable.
I have a JFrame that makes use of a database I'm setting up in my driver class.
The JFrame will launch and the window opens; however when I try to make use of the database it fails; because back in main the program just keeps running and shuts down the connection, and closes it.
I tried just removing the connection.close() code just to see if my database methods work in the JFrame, and they do, so I just need to learn how to halt main while my JFrame is running.
public static void main(String[] args) {
File dbPropertiesFile = new File(DbConstants.DB_PROPERTIES_FILENAME);
if (!dbPropertiesFile.exists()) {
showUsage();
System.exit(-1);
}
try {
new Lab9(dbPropertiesFile).run(args);
} catch (Exception e) {
LOG.error(e.getMessage());
e.printStackTrace();
} finally {
shutdown();
}
}
private static void configureLogging() {
ConfigurationSource source;
try {
source = new ConfigurationSource(new FileInputStream(LOG4J_CONFIG_FILENAME));
Configurator.initialize(null, source);
} catch (IOException e) {
System.out.println(
String.format("Can't find the log4j logging configuration file %s.", LOG4J_CONFIG_FILENAME));
}
}
private static void shutdown() {
LOG.info("Shutting down");
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOG.error(e.getMessage());
e.printStackTrace();
}
}
}
private static void showUsage() {
System.err.println(
String.format("Program cannot start because %s cannot be found.", DbConstants.DB_PROPERTIES_FILENAME));
}
private Lab9(File file) throws IOException {
properties = new Properties();
properties.load(new FileInputStream(file));
database = new Database(properties);
}
/**
* Where the computer start making a lot of noise.
*
* #param args
* #throws Exception
*/
private void run(String[] args) throws Exception {
LOG.info("Running");
LOG.info("Loading database properties from: " + DbConstants.DB_PROPERTIES_FILENAME + ".");
LOG.info(properties.getProperty("db.driver"));
LOG.info("Driver loaded");
LOG.info("DB URL = " + properties.getProperty("db.url"));
LOG.info("DB USER = " + properties.getProperty("db.user"));
LOG.info("DB PASSWORD = " + properties.getProperty("db.password"));
connect();
Statement statement = connection.createStatement();
try {
// If the user enters the -drop switch
if (args[0].equalsIgnoreCase(DROP_COMMAND)) {
LOG.info("Table " + CustomerDao.TABLE_NAME + "is being DROPPED!");
customerDao.drop();
LOG.info("Table has been DROPPED!");
}
// Check to see if the table is already made; if its not then make it, and fill
// it.
if (Database.tableExists(CustomerDao.TABLE_NAME) == false) {
createTables(statement);
LOG.info("Created the table: " + CustomerDao.TABLE_NAME + ".");
LOG.info("Inserting Customer objects into table: " + CustomerDao.TABLE_NAME + ".");
insertCustomers();
LOG.info("Inserted customer info into table from file: [" + CUSTOMER_DATA + "].");
}
createUI();
// I NEED MAIN
// TO STOP
// AROUND HERE!
}catch(SQLException e){
e.printStackTrace();
LOG.error(e.getMessage());
}finally{
connection.close();
}
}
public static void createUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseControlFrame frame = new DatabaseControlFrame(customerDao);
frame.setVisible(true);
// OR MAYBE I NEED MAIN
// TO STOP
// AROUND HERE!
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void connect() throws SQLException {
connection = database.getConnection();
customerDao = new CustomerDao(database);
}
}
Any ideas? I tried using a while(frame.isVisilbe()){ wait(600) }; But the compiler had a spas when I tried to use wait().
You'll note I'm passing a customerDAO object to my JFrame constructor; but I'm beginning to wonder could I make a connection inside the JFrame so that when main's connection closes; my JFrame's doesn't? Is that a good idea? Is that even possible I'm not super SQL savvy I'm going to need to study up on it more.
You could use Thread.sleep() - I've found that useful with JFrame before, though I'm not 100% sure it would fit what you're looking for. If you want it to wait indefinitely, put it in a while loop:
while(//condition)
{
Thread.sleep(500); //pauses for .5 sec, then loops back to check condition
}
JFrame event handler runs on a different thread than main thread, so you need to shutdown on that thread.
Here is a example, Using JDBC with GUI API.
This example call connection.close() on received window-closing-event.
public class MyFrame extends JFrame {
public MyFrame() {
// ...
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(final WindowEvent e) {
shutdown();
System.exit(0);
}
});
}
// ...
}

Exception in using Java API Oracle VirtualBox

My goal is running some process in VirtualMachine using Java. First of all, I have a part of code for create and connect to VB, but i have exception(NullPointer in main Thread) in 21 and 89 lines. I searching some answer to fix this problem, and read that problem look as I haven't Oracle VB. But in my computer i have it , version equals to imported.
So if you have an experience in using this API, or can help me, please, describe in detail how i can fix it. So, my code:
import org.virtualbox_5_1.*;
import org.virtualbox_5_1.ISession;
import org.virtualbox_5_1.IProgress;
import java.util.List;
import java.util.Arrays;
public class Events_5_1 {
static VirtualBoxManager mgr;
static Thread listener;
public static void main(String[] args) {
String vmName = Long.toString(System.currentTimeMillis()); // Берем рандомное значение имени VirtualMachine
System.out.println("Creating VirtualBox instance");
mgr = VirtualBoxManager.createInstance(null);
try {
listener = new EventWorker();
listener.start();
try {
//Создаем пустую машину и сохраняем на диск
IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);//тестить , разобраться с параметрами
vm.saveSettings();
mgr.getVBox().registerMachine(vm);
vm = mgr.getVBox().findMachine(vmName);
ISession session = mgr.getSessionObject();
IProgress p = vm.launchVMProcess(session, "headless", null); // Вместо headless - ставим процесс ??
p.waitForCompletion(-1);
try {
if (p.getResultCode() != 0) {
throw new RuntimeException(p.getErrorInfo().getText());
} else {
p = session.getConsole().powerDown();
p.waitForCompletion(-1);
if (p.getResultCode() != 0) {
throw new RuntimeException(p.getErrorInfo().getText());
} else {
}
}
} finally {
session.unlockMachine();
while (!SessionState.Unlocked.equals(vm.getSessionState())) {
try {
System.out.println("Waiting for session unlocked");
Thread.sleep(1000L);
} catch (InterruptedException e) {
System.err.println("Interrupted while vaiting for session unlocked");
}
}
System.out.println("Deleting machine");
vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
}
} finally {
listener.interrupt();
try {
listener.join(5000);
} catch (InterruptedException e) {
System.err.println("Inerrupted while vaiting for EventWorker stop");
}
if (listener.isAlive()) {
System.err.println("Event worked did not stop in a timely fashion");
} else {
System.out.println("event worker stoped");
}
}
} finally {
mgr.disconnect();
mgr.cleanup();
System.out.println("Disconecting from VirtualBox");
}
}
static class EventWorker extends Thread {
IEventListener el;
#Override
public void run() {
System.out.println("EventWorker started");
el = mgr.getVBox().getEventSource().createListener();
//TODO: connect gradle, mvnrepository.com idea connect datasource postgre
List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
VBoxEventType.OnMachineRegistered);
mgr.getVBox().getEventSource().registerListener(el, types, false);
try{
while(!isInterrupted()){
mgr.waitForEvents(0);
IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el , 1000);
if(rawEvent==null) continue;
try{
System.out.println("Got event type "+rawEvent.getType());
if(VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())){
ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getState()+" for machine "+event.getMachineId());
}
if(VBoxEventType.OnMachineRegistered.equals((rawEvent.getType()))){
IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getMachineId()+" has been "+(event.getRegistered() ? "registered":"unregistered"));
}
if(VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())){
IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getMachineId()+" state changed to "+event.getState());
}
}finally {
mgr.getVBox().getEventSource().eventProcessed(el,rawEvent);
}
}
}catch(Throwable t){
t.printStackTrace();
}finally {
mgr.getVBox().getEventSource().unregisterListener(el);
System.out.println("EventWorker finished");
}
}
}
}
If you are to plain copy/paste adapt my code, you should at least stick to the code structure and flow.
You've moved code around for some reasons and variables are not initialized timely, which is why you get NPEs.
Here is the working version for VirtualBox 5.1.x

Telling a ThreadPoolExecutor when it should go ahead or not

I have to send a set of files to several computers through a certain port. The fact is that, each time that the method that sends the files is called, the destination data (address and port) is calculated. Therefore, using a loop that creates a thread for each method call, and surround the method call with a try-catch statement for a BindException to process the situation of the program trying to use a port which is already in use (different destination addresses may receive the message through the same port) telling the thread to wait some seconds and then restart to retry, and keep trying until the exception is not thrown (the shipping is successfully performed).
I didn't know why (although I could guess it when I first saw it), Netbeans warned me about that sleeping a Thread object inside a loop is not the best choice. Then I googled a bit for further information and found this link to another stackoverflow post, which looked so interesting (I had never heard of the ThreadPoolExecutor class). I've been reading both that link and the API in order to try to improve my program, but I'm not yet pretty sure about how am I supposed to apply that in my program. Could anybody give a helping hand on this please?
EDIT: The important code:
for (Iterator<String> it = ConnectionsPanel.list.getSelectedValuesList().iterator(); it.hasNext();) {
final String x = it.next();
new Thread() {
#Override
public void run() {
ConnectionsPanel.singleAddVideos(x);
}
}.start();
}
private static void singleAddVideos(String connName) {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
try {
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
try {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
}
}
Your question is not very clear - I understand that you want to rerun your task until it succeeds (no BindException). To do that, you could:
try to run your code without catching the exception
capture the exception from the future
reschedule the task a bit later if it fails
A simplified code would be as below - add error messages and refine as needed:
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(corePoolSize);
final String x = "video";
Callable<Void> yourTask = new Callable<Void>() {
#Override
public Void call() throws BindException {
ConnectionsPanel.singleAddVideos(x);
return null;
}
};
Future f = scheduler.submit(yourTask);
boolean added = false; //it will retry until success
//you might use an int instead to retry
//n times only and avoid the risk of infinite loop
while (!added) {
try {
f.get();
added = true; //added set to true if no exception caught
} catch (ExecutionException e) {
if (e.getCause() instanceof BindException) {
scheduler.schedule(yourTask, 3, TimeUnit.SECONDS); //reschedule in 3 seconds
} else {
//another exception was thrown => handle it
}
}
}
}
public static class ConnectionsPanel {
private static void singleAddVideos(String connName) throws BindException {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
}
}
}

Two questions on using Window Listeners in Java Swing Desktop Applications

**** Please note that my question is regarding the answers in another thread. However, when I posted the question in that thread, it was deleted. So I'm reposting the question here (with a link to the exact post that I'm referring to). ****
I have a couple of questions that go along with this thread. If I have a Timer (updateTimer), which I want to cancel when the window is closing, can I put that in place of the System.out.println("Windows Closing"); statement? Or would I have to put it in the actual "View" class (I have three classes DesktopApplication.App, DesktopApplication.View, and DesktopApplication.AboutBox and the configure Window method is in the .App class).
Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?
What I want to do is the following: When my application starts (and the main window opens) I want to check for a configuration file. If it exists, then I want to get the username, password, tunnel ID, and IP Address from that file--and populate their respective text boxes in the main jPanel. If it doesn't exist, then I won't do anything with it.
On closing the application, I want two things to happen: 1) any UpdateTimers that are running will be cancelled (to effectively and cleanly close the application) and 2) write the username, password, tunnel ID and IP Address to the configuration file for the next run.
I've created the file in Netbeans, so the "exitMenu" is automatically generated, and there is no "close button" configured. So I need to use WindowClosing to accomplish this (or hack the "exitMenu" method in a text editor and hope it doesn't create issues with Netbeans).
I should also add that the username and password are actually MD5 hashes of the real username and password. So, while someone can possibly open the text file and read them, they'll only see something like this:
c28de38997efb893872d893982ac
3289ab83ce8f398289d938999cab
12345
192.168.2.2
Thanks, and have a great day:)
Patrick.
Edited to include information about the "Username and Password" that will be stored.
can I put that in place of the System.out.println("Windows Closing"); statement?
Yes, you can put arbitrary code in your listener
Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?
Yes
How I ended up accomplishing this is like this.
In my "TunnelbrokerUpdateView" class (the one that actually handles the main frame), I added the following code:
WindowListener wl = new WindowListener(){
public void windowOpened(WindowEvent e)
{
try
{
FileReader fr = new FileReader (new File("userinfo.txt"));
BufferedReader br = new BufferedReader (fr);
jTextField1.setText(br.readLine());
jPasswordField1.setText(br.readLine());
jTextField2.setText(br.readLine());
oldIPAddress = br.readLine();
br.close();
}
catch (FileNotFoundException ex) {
// Pop up a dialog box explaining that this information will be saved
// and propogated in the future.. "First time running this?"
int result = JOptionPane.showConfirmDialog((Component)
null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
}
catch (java.io.IOException ea)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
}
}
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
BufferedWriter userData;
//Handle saving the user information to a file "userinfo.txt"
try
{
userData = new BufferedWriter(new FileWriter("userinfo.txt"));
StringBuffer sb = new StringBuffer();
sb.append(jTextField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jPasswordField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jTextField2.getText());
sb.append(System.getProperty("line.separator"));
sb.append(oldIPAddress);
userData.write(sb.toString());
userData.close();
}
catch (java.io.IOException ex)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
};
super.getFrame().addWindowListener(wl);
}
I added this into the "public TunnelbrokerUpdateView(SingleFrameApplication app)" method. So, everything works as I wanted it to. I'm sure there are better ways of incorporating the user information, but this was quick and dirty. In the future, I do plan on encrypting the data (or making it into a format that isn't readable normally), since there's a password hash involved.
Hopefully this will help someone else in the future.
(for reference, here's the entire method (including the stuff that Netbeans automatically puts in)
public TunnelbrokerUpdateView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
// This will take care of Opening and Closing
WindowListener wl = new WindowListener(){
public void windowOpened(WindowEvent e)
{
try
{
FileReader fr = new FileReader (new File("userinfo.txt"));
BufferedReader br = new BufferedReader (fr);
jTextField1.setText(br.readLine());
jPasswordField1.setText(br.readLine());
jTextField2.setText(br.readLine());
oldIPAddress = br.readLine();
br.close();
}
catch (FileNotFoundException ex) {
// Pop up a dialog box explaining that this information will be saved
// and propogated in the future.. "First time running this?"
int result = JOptionPane.showConfirmDialog((Component)
null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
}
catch (java.io.IOException ea)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
}
}
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
BufferedWriter userData;
//Handle saving the user information to a file "userinfo.txt"
try
{
userData = new BufferedWriter(new FileWriter("userinfo.txt"));
StringBuffer sb = new StringBuffer();
sb.append(jTextField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jPasswordField1.getText());
sb.append(System.getProperty("line.separator"));
sb.append(jTextField2.getText());
sb.append(System.getProperty("line.separator"));
sb.append(oldIPAddress);
userData.write(sb.toString());
userData.close();
}
catch (java.io.IOException ex)
{
Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
};
super.getFrame().addWindowListener(wl);
}
Have a great day:)
Patrick.

Categories