How to make a String available in other classes - java

I've managed to make the input into a string which is available within the same class but I want to make it so the input string can be available in different classes. Current class is OpenDetails and I want the string selectedFile to be available in a different class called OpenFileInfo. How would I set it so the result from selectedFile can be stored in either selectedRequirement or make it available in other classes?
I'm new to Java so if someone could help thank you.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class OpenFile
{
String selectedRequirement = "";
public static void main(String a[])
{
JFrame parent = new JFrame();
String selectedFile;
selectedFile = JOptionPane.showInputDialog(parent, "Add a new module");
if(selectedFile.equalsIgnoreCase(selectedFile)){
//Makes the user input case insensitive
}
final JTextArea edit = new JTextArea(60,100);
JButton read = new JButton("Open "+ selectedFile +".txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader(selectedFile + ".txt");
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
JButton write = new JButton("Save "+ selectedFile + ".txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter(selectedFile + ".txt");
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) {}
}
});
System.out.println("Module: " + selectedFile);
JFrame frame = new JFrame("Requirements");
frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
frame.getContentPane().add(read, BorderLayout.WEST);
frame.getContentPane().add(write, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}

As you are running from a static context, you need to define selectedRequirement as static:
private static String selectedRequirement = "";
To make selectedRequirement equal to selectedFile, simply say selectedRequirement = selectedFile; towards the end of the main function (maybe where you print it already).
To make selectedRequirement available to other classes, you need to create a "getter function" in the OpenFIle class (outside of the main function) like:
public String getSelectedRequirement(){
return selectedRequirement;
}
As pointed out in the comments, it would be a good idea for you (or anyone who finds this in the future) to look at some tutorials on getters, setters, and general encapsulation.

Related

How to access another object from within a listener in Java

I have a listener on one of the elements of the menu class GraphMenu() in my program that that needs to call a method of an existing object created outside that class and I can't seem to find a way to implement this.
I'm defining the method of the panel I need to call in the GraphPanel() class:
public class GraphPanel extends JPanel {
private JLabel textLabel, graphicLabel;
private JTextArea textArea;
private JPanel graphPanel;
public void appendTextArea(String s) {
textArea.append(s + '\n');
}
The listener of the GraphMenu() I need to call that method in is:
public class GraphMenu {
...
// Add the action listeners that identify the code to execute when the options are selected.
menuItemLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
// you can set the directory with the setCurrentDirectory method.
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// User has selected to open the file.
File file = fc.getSelectedFile();
try {
// Open the selected file
BufferedReader reader = new BufferedReader(new FileReader(file));
// Output the contents to the console.
String nextLine = reader.readLine();
while ( nextLine != null ) {
panel.appendTextArea(nextLine);
System.out.println(nextLine);
nextLine = reader.readLine();
}
reader.close();
} catch (IOException e1) {
System.err.println("Error while reading the file");
}
};
}
});
...
Is there a way I can call the appendTextArea() on the panel object as in the example above?
I'm creating the two objects of class GraphPanel() and GraphMenu() in the main function:
GraphPanel panel = new GraphPanel();
frame.getContentPane().add(panel);
GraphMenu menu = new GraphMenu();
frame.setJMenuBar(menu.setupMenu());

JTextArea saving to txt

I'm making a program that requires to save user input. So I would like to know how to save JTextArea to text file and when you close and re-open program text is still in JTextArea.
Also sorry for my bad grammar.
package main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class main extends JFrame {
JLabel statusbar;
public main() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
statusbar = new JLabel("");
statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
panel.setLayout(null);
JTextArea area1;
area1 = new JTextArea(90, 25);
area1.setBounds(20, 20, 200, 25);
area1.setBackground(Color.white);
area1.setForeground(Color.BLACK);
area1.setText("");
panel.add(area1);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setTitle("Viskis");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton) e.getSource();
String label = o.getText();
statusbar.setText("");
} }
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
main ms = new main();
ms.setVisible(true);
new main();
}
});
}
}
Here are some helper methods to help you read and write from Files. Look in the JavaDoc for getText() and setText() for getting and setting the text of the JTextArea.
I recommend reading the SwingWorker tutorials and using these methods in a SwingWorker, lest you lock up your GUI while saving/reading the Files
/**
* Writes a String text to a File specified by filename
*
* #param filename The filename/path of the File we would like to write the text to
* #param text The text to write to the File
*
*/
public static void writeToFile(String filename, String text) {
BufferedWriter writer = null; // This could go in a try-with-resources if you wanna get fancy
try {
writer = new BufferedWriter(new FileWriter(new File(filename))); // Open a File for writing
writer.write(text); // write the text to the file
} catch ( IOException e) {
/* We could not open the File for writing, or could not write to the File */
} finally {
try {
if (writer != null) {
writer.close(); // we are done writing to the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
}
/**
* Reads all lines from a File specified by filename
*
* #param filename The filename/path of the File we would like to read text from
*
* #return An list of Strings containing each line of the File
*/
public static List<String> readFromFile(String filename) {
BufferedReader reader = null; // This could go in a try-with-resources if you wanna get fancy
List<String> lines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(new File(filename))); // Open a File for writing
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
/* We could not open the File for reading, or could not read from the File */
} finally {
try {
if (reader != null) {
reader.close(); // we are done reading from the File, close the connection
}
} catch (IOException e) {
/* We could not close the connection to the File */
}
}
return lines;
}
Write and read file on a swing thread is not recommanded. Use mvc pattern. Create a data model with field binded to your component. Create an adapter to update model and write file
Then your component will always up to date with your model
Use model to write data(with the adapter) and read file will update your model with the adapter
For exemple, Focus listener will call adapter to do the task. Or you can use an obseevee pattern when you Object if modified.
This code worked for me with 'nam' as the current date and 'name' an input in a jTextField.
try {
con=Connect.ConnectDB();
pst.execute();
Date date=new Date();
SimpleDateFormat sd=new SimpleDateFormat("dd-mm-yyyy-h-m-s");
String nam= sd.format(date);
String name=CaseNoField.getText();
CaseNoField.setText("");
FileWriter writer=new FileWriter( "C:\\path"+name+"("+nam+")"+".txt");
BufferedWriter bw=new BufferedWriter( writer );
JCaseArea.write( bw );
bw.close();
JCaseArea.setText("");
JCaseArea.requestFocus();
JOptionPane.showMessageDialog(null, "Case Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

Why my JTextArea is not displaying properly from the while loop?

My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?
Please note the code below has been altered to the correct working version provided all the helpful contributors below.
Main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(textArea, BorderLayout.SOUTH);
}
Scanner s = null;
File af = null;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(truea);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
}
Driver class:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class TestMyFileLister {
public static void main(String [] args)
{
MyFileLister thePanel = new MyFileLister();
JFrame firstFrame = new JFrame("My File Lister");
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstFrame.setVisible(true);
firstFrame.setSize(500, 500);
firstFrame.add(thePanel);
}
}
Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.
I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
if(af == null)
{
System.out.println("Error");
}
while(s.hasNextLine())
{
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath = "";
for(String path: paths)
{
tempPath += path + "\n";
}
textArea.setText(tempPath);
}
}
You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).
// These lines below are causing only last file shown.
for(String path: paths)
{
textArea.setText(path);
}
Here is your modified version for MyFileLister class :
public class MyFileLister extends JPanel implements ActionListener {
private JLabel prompt = null;
private JTextField userInput = null;
private JTextArea textArea = null;
public MyFileLister()
{
prompt = new JLabel("Enter filename: ");
prompt.setOpaque(true);
this.add(prompt);
userInput = new JTextField(28);
userInput.addActionListener(this);
this.add(userInput);
textArea = new JTextArea(10, 30);
textArea.setOpaque(true);
JScrollPane scrollpane = new JScrollPane(textArea);
this.add(scrollpane, BorderLayout.SOUTH);
}
Scanner s = null;
File af ;
String[] paths;
public void actionPerformed(ActionEvent f)
{
try
{
s = new Scanner(new File(userInput.getText()));
while(s.hasNext())
{
String as = s.next();
textArea.setText(as);
}
}
catch(FileNotFoundException e)
{
af = new File(userInput.getText());
paths = af.list();
System.out.println(Arrays.toString(paths));
String tempPath="";
for(String path: paths)
{
tempPath+=path+"\n";
}
textArea.setText(tempPath);
}
}
}
Output :
Code:
public void actionPerformed(ActionEvent ae) {
try (Scanner s = new Scanner(new File(userInput.getText()))) {
while (s.hasNextLine()) {
String as = s.nextLine();
textArea.append(as + "\n");
textArea.setLineWrap(true);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this,
"File not found",
"No File Error",
JOptionPane.ERROR_MESSAGE);
}
}
Notes:
Just try to read your file line by line so you can copy the same structure from your file into your JTextArea.
Use setLineWrap method and set it to true
read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)
use append method in order to add text to end of your JTextArea
read here
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)
Use JOptionPane to show error message to an user

JLabel's text is not changing

EDIT: Huge code re-organisation, old question here: http://pastebin.com/Mbg4dYiY
I have created a basic program that is designed to show the weather in a window using Swing. I am developing using IntelliJ and I have used the UI builder in that. I am attempting to fetch some information from the Weather Underground servers and then make a JLabel called weatherlabel display this information. However, the JLabel doesn't actually change in the window; it just stays as 'Weather Will Go Here'. How do I fix this?
Here is my main.java:
public class main {
public static void main(String[] args) {
System.out.println("Hello World!");
Display d = new Display();
d.getandsetWeather();
}
}
Here is my Display.java:
public class Display {
Display disp = this;
public JPanel myPanel;
public JLabel weatherfield;
private JButton button1;
public void init() {
JFrame frame = new JFrame("Display");
frame.setContentPane(new Display().myPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(480, 234));
frame.pack();
frame.setVisible(true);
}
public void getandsetWeather() {
String editedline = null;
init();
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://api.wunderground.com/api/772a9f2cf6a12db3/geolookup/conditions/q/UK/Chester.json");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
if( line.contains("\"weather\":")) {
System.out.println(line);
editedline = line.replace("\"weather\":\"", "");
editedline = editedline.replace("\",", "");
System.out.println(editedline);
weatherfield.setText(editedline);
}
}
wr.close();
rd.close();
weatherfield.setText(editedline);
System.out.println(weatherfield.getText());
weatherfield.repaint();
weatherfield.revalidate();
} catch (Exception e) {
System.out.println("Error!" + e);
}
}
}
When I run the program, this is printed to the log:
Hello World!
"weather":"Scattered Clouds",
Scattered Clouds
Scattered Clouds
You seem to have a strange understanding of OOP and code-flow
You have to main methods, one of which you are trying to call the other main method. Don't do that. A program should only have one main method. You should never have to this
Display.main(new String[]{});
Why even have this ChangeWeatherLabelText class? There is only one method, that doesn't seem to be needed in it's own class. Your instantiation if Display in that method does nothing to the rest of the program. So you call has no effect on the label.
Instead of 3, put that method in the class that actually has the label and just reference the label field in the method.
Also, GetWeather just seems like a helper class with a helper method. "Helper" class methods are useless if they don't return something.
IMHO, you should restructure your entire program. Some things may work now, but there's a lot of bad practice going on in your code
If I were to write this program, all the code would be in one file. If you insist on them being in separate files, you need to learn how to use constructors and how to pass objects to them. That is how you are going to manipulate objects from other classes. That is unless you understand the MVC model, which may be a little advance at this point for you.
UPDATE with OP update of code
Test this out and be sure to read the comments so you can see what I did. Let me know if you have any question.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class main {
public static void main(String[] args) {
System.out.println("Hello World!");
new Display(); // <-- just instantiate
}
}
class Display {
Display disp = this;
public JPanel myPanel; // <--------- Haven't been initialized
public JLabel weatherfield;
private JButton button1;
public Display() { // you need constructor to call init
init();
}
public void init() {
myPanel = new JPanel(new BorderLayout()); // initialize
weatherfield = new JLabel(" "); // initialize
button1 = new JButton("Button"); // initialize
myPanel.add(weatherfield, BorderLayout.CENTER);
myPanel.add(button1, BorderLayout.SOUTH);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
getandsetWeather(); // <-------- add listener to call getandsetweather
}
});
JFrame frame = new JFrame("Display");
frame.setContentPane(myPanel); // <--------------------- fix 1
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(480, 234));
frame.pack();
frame.setVisible(true);
}
public void getandsetWeather() {
String editedline = null;
init();
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://api.wunderground.com/api/772a9f2cf6a12db3/geolookup/conditions/q/UK/Chester.json");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
if( line.contains("\"weather\":")) {
System.out.println(line);
editedline = line.replace("\"weather\":\"", "");
editedline = editedline.replace("\",", "");
System.out.println(editedline);
weatherfield.setText(editedline);
}
}
wr.close();
rd.close();
weatherfield.setText(editedline);
System.out.println(weatherfield.getText());
weatherfield.repaint();
weatherfield.revalidate();
} catch (Exception e) {
System.out.println("Error!" + e);
}
}
}

How to properly load a JFrame from a file?

I'm making this grade keeping program for my computer science class and the one thing I haven't gotten to work is saving/loading sessions. As I have it set up now it automatically saves when you exit and loads when you start if there is a file to load. However, I feel I'm loading or saving it incorrectly; there's one main JFrame that holds all the data, and that's the one object that is saved. When it's loaded, well, it'd be easier to show you.
If it looks like this when I close it::
Then it'll look like this when I start it up again:
Also, the "Enter Student" button, as well as the ActionListener on the JTextField used for input, cease to work when the program loads the JFrame. The program is split into 3 class files:
Gradebook:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class GradeBook implements java.io.Serializable {
private static JFrame frame;
public static void main(String[] args) throws Exception{
try{
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
frame = (JFrame) ois.readObject();
ois.close();
} catch(Throwable t) {
frame = new JFrame("Course Grades");
}
frame.addWindowListener(new closing());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CourseGrade());
frame.pack();
frame.setVisible(true);
}
closing:
private static class closing extends WindowAdapter {
public void windowClosing(WindowEvent e) {
try {
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(frame);
oos.close();
} catch(Throwable t){System.out.println(t.getMessage());}
}
}
}
CourseGrade:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
import java.util.Random;
import javax.swing.table.*;
import java.io.*;
public class CourseGrade extends JPanel implements java.io.Serializable {
private JLabel entername;
private JTextField in;
private JTextArea list;
private JScrollPane scroll;
private String[] students = new String[1000];
private JButton enter;
private JButton[] studentbuttons = new JButton[1000];
private JButton[] delete=new JButton[1000];
private int numstudents;
private JFrame[] studentframes=new JFrame[1000];
private static JTable[] tables=new JTable[1000];
private static DefaultTableModel[] model=new DefaultTableModel[1000];
private static int[] numass=new int[1000];
public CourseGrade() {
String[][] data = {{"", "", "", ""}};
String[] headers = {"Assignment", "Date Assigned", "Score", "Percentage"};
for(int i=0; i<tables.length; i++){
model[i] = new DefaultTableModel(data, headers);
tables[i] = new JTable(model[i]){
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
}
numstudents=0;
in=new JTextField(13);
in.addActionListener(new enterListener());
list=new JTextArea();
scroll=new JScrollPane(list);
list.setEditable(false);
entername=new JLabel("Enter a student's name");
enter=new JButton("Enter Student");
enter.addActionListener(new enterListener());
setPreferredSize(new Dimension(260, 300));
setBackground(Color.green);
add(entername);
add(in);
add(enter);
add(scroll);
scroll.setPreferredSize(new Dimension(240, 200));
}
private class enterListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String x=in.getText();
String y="";
String z="";
in.setText("");
int a=numstudents+1;
if(x.length()>0) x=a+". " + x + "\n";
students[numstudents] = x;
if(x.length()>0)numstudents++;
for(int i=0; i<numstudents; i++){
x=students[i];
if(x.length()>13)x=x.substring(0,11)+"...\n";
y+=x;
}
studentbuttons[numstudents]=new JButton("Edit");
studentbuttons[numstudents].addActionListener(new grades());
delete[numstudents]=new JButton("Delete");
delete[numstudents].addActionListener(new del());
list.setText(y);
list.add(studentbuttons[numstudents]);
studentbuttons[numstudents].setBounds(100,(numstudents-1)*16,55,15);
list.add(delete[numstudents]);
delete[numstudents].setBounds(160,(numstudents-1)*16,70,15);
}
}
private class grades implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if(obj instanceof JButton){
JButton clicked = (JButton)obj;
int x=clicked.getY()/16;
String y=students[x];
for(int i=0; i<y.length(); i++){
String q=y.substring(i,i+1);
if(q.equals(" ")) {
y=y.substring(i+1);
i=y.length()+1;
}
}
studentframes[x]=new JFrame(y+"'s Grades");
studentframes[x].setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try{studentframes[x].getContentPane().add(new GradePage(x, tables[x], numass[x]));}
catch(Exception e){}
studentframes[x].pack();
studentframes[x].setVisible(true);
}
}
}
private class del implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if(obj instanceof JButton){
JButton clicked = (JButton)obj;
int x=clicked.getY()/16;
String y="", z="";
studentbuttons[numstudents].setVisible(false);
delete[numstudents].setVisible(false);
numstudents--;
int q=3;
int w=0;
for(int i=x; i<=numstudents; i++){
if(i<10)q=1;
else if(i<100) q=2;
tables[i]=tables[i+1];
numass[i]=numass[i+1];
model[i]=model[i+1];
w=i+1;
try{if(!students[i+1].equals(null)){students[i]=w+students[i+1].substring(q);} else{students[i]=null;}}catch(Throwable t){}
}
for(int i=0; i<numstudents; i++){
y=students[i];
if(y.length()>13)y=y.substring(0,11)+"...\n";
z+=y;
}
list.setText(z);
}
}
}
public static void setTable(int numtable, JTable table){
tables[numtable]=table;
}
public static void newRow(int numtable){
model[numtable].addRow(new Object[]{"", "", "", ""});
}
public static void setNumEntries(int numtable, int num){
numass[numtable]=num;
}
}
The third class shouldn't have anything to do with this so I wont post it for now.
I realize the code is probably poorly written but I'm only in my second year of High School computer science and we haven't actually covered any of this. This program wasn't even supposed to be a GUI, and this is the first time I've even heard of Input or Output streams so I really don't know anything about them. I realize now that having the classes implement java.io.Serializable was probably unnecessary but when I was trying to research this I came across someone taking about how some objects can't be saved because they don't naturally implement it. So sorry if it's some stupid mistake, and thanks for your time.
You can store the data in a notepad file like this
try
{
FileWriter file = new FileWriter( "insert file name here" );
BufferedWriter buffer = new BufferedWriter( file ) ;
buffer.write( "insert file content here" ) ;
buffer.newLine();
buffer.close();
}
catch ( IOException e )
{
//Insert error message here
}
And then read it like this
try
{
FileReader file = new FileReader( "insert file name here" ) ;
BufferedReader buffer = new BufferedReader( file );
String line = "" ;
while( ( line = buffer.readLine() ) != null )
{
System.out.println( line ) ;
}
buffer.close() ;
}
catch( IOException e )
{
//Insert error message here
}
Hope that helps
i dont recomend that you save JFrame object. here is a better solution you can save the students name and there grades on a text file and each time your program loads it will load the information from the text file.
Hint : you can use Input & Output streams dirctly but it's maybe a little bit sonfusing so go and read about these two classes :
Scanner (and how to use it to read from file)
PrintWriter (and how to use it to write to file)
P.S.: i could'v given you the code but it is much better learning experience to suffer a little bit to find information, because while you are trying to figure it out you will learn a lot of other things.
The frame is not an integral part of your application's state, it's just a way of displaying the important information (names, grades, etc). If you want to save your session, save the information the is currently on the screen and then re-create the JFrame with the deserialized information. An ObjectOutputStream is a reasonable way of writing things to disk, and and ObjectInputStream is good for reading the data back in. The documentation contains good examples. Also, your classes would need to implement Serializable.

Categories