looping problem
I have an if loop that i think is repeating itself, and i have absolutely no idea why
I put System.out.println's in with numbers so i could check.
What happens is is that when i selected "Open" in the JComboBox, the open file dialog pops up, i select a file, press open, the text is then display in the text area, but the dialog pops up again.
This only happens twice, i can either click cancel or open again on the dialog, if i click cancel it will close, if i press open on the same or a different file, it will open it again.
I actually have most of this code in a different application, but i experimented with a smaller version so i could reproduce this problem, just incase you are wondering why there are some variables i might not need.
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
publicclass Notepadextends JFrameimplements ItemListener{
JPanel pane =new JPanel();
JTextArea text =new JTextArea(20,30);
String[] choices ={"File","New","Open","Save","Save As","Exit"};
JComboBox options =new JComboBox(choices);
JScrollPane scroll =new JScrollPane(text);
JFileChooser chooser =new JFileChooser();
File theOpenFile;
File theSaveFile;
public Notepad(){
super("Notepad");
pane.add(options);
pane.add(scroll);
options.addItemListener(this);
setContentPane(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
publicvoid itemStateChanged(ItemEvent e){
int op = options.getSelectedIndex();
if(op == 1){
text.setText("");
}
if(op == 2){
System.out.println("1");
int returnVal = chooser.showOpenDialog(pane);
if(returnVal == JFileChooser.APPROVE_OPTION){
System.out.println("2");
try{
System.out.println("3");
theOpenFile =new File(chooser.getSelectedFile().getPath());
FileReader reader =new FileReader(theOpenFile);
BufferedReader buffer =new BufferedReader(reader);
String ss;
String aa ="";
while((ss = buffer.readLine()) !=null){
System.out.println("4");
aa = aa + ss +"\n";
}
System.out.println("5");
text.setText(aa);
reader.close();
System.out.println("6");
}
catch(FileNotFoundException f){
System.out.println("No file exists");
}
catch(IOException g){
System.out.println("IO Exception");
}
System.out.println("7");
}
}
}
publicstaticvoid main(String[] args){
JFrame notepad =new Notepad();
notepad.setSize(350,400);
notepad.setVisible(true);
}
}
By the way, the output i get is:
1
2
3
4
5
6
7
1 <open dialog comes up again
--
New development: The loop actually goes right back to the itemStateChanged method start. So its as if i'm selecting the Open option twice?

