j A L
2010-12-13 13:12:21 UTC
The first button should be labeled "Open". When clicked, it should ask the user for a file name using a JOptionPane. It should then open the file by creating a FileReader and a Scanner.
ii. If the file opens successfully, the contents of the file should be read a line at a time using the Scanner object in a loop. Each line should be appended to the JTextArea (after clearing out the existing contents of the text area first). The title of the Frame should be set to the name of the file if successful.
iii. If the file does not exist, the program should not end - but the contents of the text area should be cleared and the title of the frame should be changed back to "My Reader"
iv. The second button should be labeled "Clear". When clicked, it should clear the textArea (i.e. set the text to ""). It should also rename the frame title back to " My Reader"
the clear button works fine as is, but the name of super will change in the previous operation, so dont know how to change it back.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ViewerFrame extends JFrame {
private JButton b1,b2;
private JTextArea field;
private JPanel panel, panel2;
public ViewerFrame(){
super("My Reader");
b1 = new JButton("Open");
b2 = new JButton("Clear");
field = new JTextArea(25,25);
panel = new JPanel();
panel2 = new JPanel();
panel.add(b1);
panel.add(b2);
panel2.add(field,BorderLayout.CENTER);
add(panel, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == b1)
field.setText( "Fred was clicked");
}
}
);
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == b2)
field.setText( " Pat was clicked");
}
}
);
}
}
import javax.swing.JFrame;
public class ViewerFrameTester {
public static void main(String[] args) {
ViewerFrame buck = new ViewerFrame();
buck.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buck.setSize(600, 400);
buck.setVisible(true);
}
}