I have a Java Application that creates a JPanel menu and part of the program is to export data provided by the user inside JPanel to excel.
I want to create excel file and provide certain formatting inside my program.
I have tried using Apache POI, my code for the function is below. The function is called with a press of a button inside the JPanel when the application is running.
private static void processExcelInformation() throws FileNotFoundException
{
JOptionPane.showMessageDialog(panel, "stuck before workbook", "Display",
JOptionPane.WARNING_MESSAGE);
HSSFWorkbook workbook = new HSSFWorkbook(); // <---- I cannot seem to initialize new workbook
JOptionPane.showMessageDialog(panel, "created workbook", "Display",
JOptionPane.WARNING_MESSAGE); // <---- This message is not displayed when the application runs
HSSFSheet sheet = workbook.createSheet("Sample sheet");
JOptionPane.showMessageDialog(panel, "created sheet", "Display",
JOptionPane.WARNING_MESSAGE);
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) { // <---- This statement does not allow the application to run, I get an error
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
JOptionPane.showMessageDialog(panel, "stuck before xls", "Display",
JOptionPane.WARNING_MESSAGE);
FileOutputStream out =
new FileOutputStream(new File("new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
JOptionPane.showMessageDialog(panel, "Excel written", "Display",
JOptionPane.WARNING_MESSAGE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Check for comments where I have issues with my code.
Maybe someone can recommend me another way to complete my task or provide me a solution to my issues.
Thanks
Here's more to my code...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
soccerStock = new ArrayList<Soccer>();
childrenStock = new ArrayList<Children>();
miniSoccerStock = new ArrayList<MiniSoccer>();
tennisStock = new ArrayList<Tennis>();
universalStock = new ArrayList<Universal>();
try {
// processExcelInformation();
parseXMLInput();
initializeGrassChoices();
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calculator ex = new Calculator();
ex.setVisible(true);
}
});
}
public Calculator() {
initUI();
}
public final void initUI() {
initGrassRollChoices();
initPanel();
createMenu();
}
This is the button that calls processExcelInformation() function...
JMenuItem xls = new JMenuItem("Excel", null);
xls.setMnemonic(KeyEvent.VK_E);
xls.setToolTipText("Export Excel");
xls.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
processExcelInformation();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
When I call processExcelInformation() during compilation from main function it creates the excel file as asked. However, when I write my code to call processExcelInformation() function using a button I get an error when launching my application.
There is an open source package called Jexcel which might provide the tools you need. See this Source Forge site for the source packages. For tutorials and API docs you can look here.
Additional: I've just read some reviews. Seems JExcel doesn't enjoy a very good rep and doesn't support xlsx format.
Looking at your code I can see that there may be a problem with the for-loop you've indicated. You haven't mentioned what the error is, but I suspect you cannot simply treat an array as a collection. I'd be inclined to try something more traditional like this:
for (int i = 0; i < objArr.length; i++){
...
}
Take a look at JExcel. It´s pretty easy to use if you don´t need overly complicated spreadsheets and there are a lot examples and HowTos if you ask our friend Google.
Related
I have class Laptops. Inside this class I have 3 parameters "String name, Integer screen, Integer price" I created Set and now I need to split it and compare with price if price over 2000$ write to file if lower write to second file.
This is my method:
public void check(Set<Laptops> laptops, File under2000, File over2000){
try{
String under2000 = "2000";
OutputStream under = new FileOutputStream(under2000);
PrintStream printStream = new PrintStream(under);
Iterator<Laptops> lap = laptops.iterator();
while (lap.hasNext()){
lap.next();
if (laptops.contains(under2000)) {
printStream.print(lap);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Can someone help me?
It is easy to split the set with streams:
Set<Laptops> over2000 = laptops.stream().filter(l -> l.getPrice() > 2000).collect(Collectors.toSet());
Set<Laptops> rest = new HashSet<>(laptops);
rest.removeAll(over2000);
The first part filters all laptops with price over 2000. The rest takes the original set and removes those laptops. Than you can handle each set as you like.
public void check(Set<Laptops> laptops, File under2000file, File over2000file){
try {
PrintStream under2000 = new PrintStream(under2000file);
PrintStream over2000 = new PrintStream(over2000file);
for(Laptop laptop: laptops) {
if(laptop.getPrice() < 2000) {
under2000.println(laptop);
} else {
over2000.println(laptop);
}
}
under2000.close();
over2000.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I'm writing a program in order to keep track of DVDs in my library. I'm having trouble altering the text file that saves an added or removed DVD object from the arraylist. Whenever I call my save method, which is the one that overwrites the existing text file holding all the information, it will not change it whatsoever. My add and remove methods work fine but it's just the save method which overwrites the file that I'm reading from that will not work. The following code is what I was attempting to use to save the arraylist to the file. My filename is DVDCollection.txt and the boolean variable flag is a static variable used to check whether or not the code which adds or removes an object from the arraylist was reached.
public void save() {
try{
if(flag=true){
FileWriter instream = new FileWriter("DVDCollection.txt",false);
instream.close();
}else{
return;
}
}catch(IOException e){
System.out.println("The file could not be written to!");
}
}
If you are using java 8 or above it's as simple as:
List<String> lines = Arrays.asList("first line", "second line");
try {
Files.write(Paths.get("my-file.txt"), lines);
} catch (IOException e) {
//handle exception
}
Make sure you provide the right path!
Not sure, why this method should save an array list, as the actual code that writes to this file is missing. Here is simple test, let's start here:
import java.io.*;
import java.util.*;
public class FileSaveTest {
public static void main(String[] args) {
FileSaveTest test = new FileSaveTest();
test.fill();
test.save();
}
public void fill() {
arrayList.add("My disc 1");
arrayList.add("My disc 2");
arrayList.add("Another disc");
}
public void save() {
try {
if(flag) { // you dont need ==true
FileWriter instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
instream.close();
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
}
private ArrayList<String> arrayList = new ArrayList<>();
private static boolean flag = true;
}
Next, it's not very good, to close the file in such manner. If an exception occurs while writing, the file will not be closed. instream.close() should be put into the "finally" block. This block will be executed in any case, regardless of whether an exception occurred or the return keyword met:
public void save() {
Writer instream = null;
try {
if(flag) { // you dont need ==true
instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
} finally {
try {
if (instream != null)
instream.close();
} catch (IOException e) {
System.err.println("Exception during close");
}
}
}
Or, if you are using java 7, you can use try-with-resources syntax:
public void save() {
if(flag) { // you dont need ==true
try (Writer instream = new FileWriter("DVDCollection.txt",false)) {
for (String entry : arrayList)
instream.write(entry + "\n");
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
} // you dont need "return else { return; }" anymore
}
I've done plenty of research on this question and have tried many different methods, but none of them do what I'd like, or the explanations to implement them into my own code are really vague.
I need to export the test results (TestID, Expected Result, Pass or Fail) into an excel sheet. I am currently using TestNG and Apache POI.
I know how to write to an excel sheet, but I am absolutely lost on how to write whether or not something passed or failed. I am currently using some code that doesn't exactly work - sometimes it will write it, sometimes it won't. I need the most simple, easy way to do this, with a good explanation.
I'll show you my current #BeforeClass, #AfterClass, and two #Test blocks.
#BeforeClass:
#BeforeClass(alwaysRun = true)
public void setupBeforeSuite(ITestContext context) throws IOException {
//create a new work book
workbook = new HSSFWorkbook();
//create a new work sheet
sheet = workbook.createSheet("Test Result");
testresultdata = new LinkedHashMap < String, Object[] > ();
//add test result excel file column header
//write the header in the first row
testresultdata.put("1", new Object[] {
"Test Step Id", "Action", "Expected Result", "Actual Result"
});
}
#AfterClass:
#AfterClass
public void setupAfterSuite(ITestContext context) {
//write excel file and file name is TestResult.xls
Set<String> keyset = testresultdata.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = testresultdata.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
FileOutputStream out =new FileOutputStream(new File("C:/Users/PathToFile/LoginCombinations.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
#Test blocks:
#Test(priority=0)
public void successfulLogin() throws InterruptedException {
Properties prop = new Properties();
InputStream config = null;
InputStream signinpage;
try {
// First we iterate over and read the config file
config = new FileInputStream("C:/Users/PathToFile/src/ConfigFiles/config");
prop.load(config);
signinpage = new FileInputStream("C:/Users/PathToFile/src/ObjectRepositories/signinpage");
prop.load(signinpage);
// Next we initiate the driver, and navigate to the Web Application
driver = new FirefoxDriver();
driver.get(prop.getProperty("url"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// Now we run the first step, "enterValidCredentials"
// In this test, this is actually the only step.
LoginPage.enterValidCredentials.run(driver);
// Assert that we landed on the Product Select page.
// assertEquals(driver.findElement(By.xpath(prop.getProperty("tempproductselect"))).getText(), "SELECT PRODUCT");
try{
assertEquals(driver.findElement(By.xpath(prop.getProperty("tempproductselect"))).getText(), "SELECT PRODUCT");
//add pass entry to the excel sheet
testresultdata.put("2", new Object[] {1d, "User can login with a valid username and password", "Login successful","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("2", new Object[] {1d, "User can login with a valid username and password", "Login successful","Fail"});
}
// Write the test result to the sheet.
driver.close();
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (config != null) {
try {
config.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Test(priority=1)
public void invalidCredentialsOne() throws InterruptedException {
Properties prop = new Properties();
InputStream config = null;
InputStream signinpage;
try {
// First we iterate over and read the config file
config = new FileInputStream("C:/Users/PathToFile/src/ConfigFiles/config");
prop.load(config);
signinpage = new FileInputStream("C:/Users/PathToFile/src/ObjectRepositories/signinpage");
prop.load(signinpage);
// Next we initiate the driver, and navigate to the Web Application
WebDriver driver;
driver = new FirefoxDriver();
driver.get(prop.getProperty("url"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// Now we run the first step, "invalidCredentialsOne"
// In this test, this is actually the only step.
LoginPage.invalidCredentialsOne.run(driver);
Thread.sleep(5000);
try{
assertEquals(driver.findElement(By.xpath(prop.getProperty("failedlogin"))).getText(), "LOG IN");
//add pass entry to the excel sheet
testresultdata.put("3", new Object[] {2d, "User should not be able to login with an invalid password", "Login failed","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("3", new Object[] {2d, "User should not be able to login with an invalid password", "Login failed","Fail"});
}
// Write the test result to the sheet.
// After the test, we close the driver.
driver.close();
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (config != null) {
try {
config.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The second test, invalidCredentialsOne, never writes to the excel, whether I make it pass or fail.
Java is also new to me, so forgive any formatting/lingo/whatever errors I have in there. I'm very open-minded to suggestion, I'm trying to improve.
Here is the structure as i see it:
1) A part where you have a DriverFactory defined.
public class BrowserFactory {
public static WebDriver localDriver(Capabilities capabilities) {
String browserType = capabilities.getBrowserName();
if (browserType.equals("firefox"))
return new FirefoxDriver(capabilities);
if (browserType.startsWith("internet explorer"))
return new InternetExplorerDriver(capabilities);
if (browserType.equals("chrome"))
return new ChromeDriver(capabilities);
throw new Error("Unrecognized browser type: " + browserType);
}
Then you can simply initialize it anytime you need it :
Example:
driver = BrowserFactory.localDriver(DesiredCapabilities.firefox());
2) Your test classes, where you use this factory. Then there will be no need in #BeforeClass annotations. You write your tests in those classes. And at the end of every test, you make an assert (if test result failed or not). To check if the test passes, use the Assert.true();
Example: I i use the wrokg credentials on login, the allert: Wrong Password will appear.
Solution: You make an Assert.true(errorMessagePresent)
3) Your output writer class - to make it accessible for your tests
3) In case the test passes - you add the string you want to the output, using the buffer reader, else you throw an exception
Okay, I'm trying to create a custom client for Minecraft (don't worry, my question has nothing to do with Minecraft in particular), and I added an abstract class to manage a configuration file using Java's built-in Properties system. I have a method that loads a properties file or creates it if it doesn't already exist. This method is called at the beginning of all my other methods (although it only does anything the first time its called).
The properties file gets created just fine when I run Minecraft the first time, but somehow when I run it the second time, the file gets blanked out. I'm not sure where or why or how I'm wiping the file clean, can someone please help me? Here's my code; the offending method is loadConfig():
package net.minecraft.src;
import java.util.*;
import java.util.regex.*;
import java.io.*;
/**
* Class for managing my custom client's properties
*
* #author oxguy3
*/
public abstract class OxProps
{
public static boolean configloaded = false;
private static Properties props = new Properties();
private static String[] usernames;
public static void loadConfig() {
System.out.println("loadConfig() called");
if (!configloaded) {
System.out.println("loading config for the first time");
File cfile = new File("oxconfig.properties");
boolean configisnew;
if (!cfile.exists()) {
System.out.println("cfile failed exists(), creating blank file");
try {
configisnew = cfile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
configisnew=true;
}
} else {
System.out.println("cfile passed exists(), proceding");
configisnew=false;
}
FileInputStream cin = null;
FileOutputStream cout = null;
try {
cin = new FileInputStream(cfile);
cout = new FileOutputStream(cfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!configisnew) { //if the config already existed
System.out.println("config already existed");
try {
props.load(cin);
} catch (IOException e) {
e.printStackTrace();
}
} else { //if it doesn't exist, and therefore needs to be created
System.out.println("creating new config");
props.setProperty("names", "oxguy3, Player");
props.setProperty("cloak_url", "http://s3.amazonaws.com/MinecraftCloaks/akronman1.png");
try {
props.store(cout, "OXGUY3'S CUSTOM CLIENT\n\ncloak_url is the URL to get custom cloaks from\nnames are the usernames to give cloaks to\n");
cout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
String names = props.getProperty("names");
System.out.println("names: "+names);
try {
usernames = Pattern.compile(", ").split(names);
} catch (NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("usernames: "+Arrays.toString(usernames));
configloaded=true;
}
}
public static boolean checkUsername(String username) {
loadConfig();
System.out.println("Checking username...");
for (int i=0; i<usernames.length; i++) {
System.out.println("comparing "+username+" with config value "+usernames[i]);
if (username.startsWith(usernames[i])){
System.out.println("we got a match!");
return true;
}
}
System.out.println("no match found");
return false;
}
public static String getCloakUrl() {
loadConfig();
return props.getProperty("cloak_url", "http://s3.amazonaws.com/MinecraftCloaks/akronman1.png");
}
}
If it's too hard to read here, it's also on Pastebin: http://pastebin.com/9UscXWap
Thanks!
You are unconditionally creating new FileOutputStream(cfile). This will overwrite the existing file with an empty one. You should only invoke the FileOutputStream constructor when writing a new config file.
if (configloaded)
return;
File cfile = new File("oxconfig.properties");
try {
if (cfile.createNewFile()) {
try {
FileOutputStream cout = new FileOutputStream(cfile);
props.setProperty("names", "oxguy3, Player");
props.setProperty("cloak_url", "http://...");
...
cout.flush();
} finally {
cout.close();
}
} else {
FileInputStream cin = new FileInputStream(cfile);
try {
props.load(cin);
} finally {
cin.close();
}
}
configloaded=true;
} catch(IOException ex) {
e.printStackTrace();
}
**** 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.