Iam making a simple program where the user enters name and description. If the user presses OK, the program will write the result to the file. Basically, i have 3 classes. I want to call my class2 from class1 and implement the method. I know how to do it in only one class but i would like to know this way too. Thanks in advance.
The problem is that the inputs cannot be added to the file. Maybe iam not calling the file name properly:
if (result == JOptionPane.OK_OPTION){
class2 ad = new class2(this);
}
Below are my 3 classes:
Main
public class mainclass {
public static void main(String[] args) {
class1 a = new class1();
}
}
Class1
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.table.*;
import java.util.*;
public class class1{
final JTextField field1 = new JTextField(10);
final JTextField field2 = new JTextField(10);
JPanel panel = new JPanel();
public class1() {
panel.add(new JLabel("Name:"));
panel.add(field1);
panel.setLayout(new GridLayout(5,2));
panel.add(new JLabel("Description:"));
panel.add(field2);
int result = JOptionPane.showConfirmDialog(null, panel,"Enter Information", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
class2 ad = new class2 ();
}
}
}
Class2
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.table.*;
import java.util.*;
public class class2 {
class1 a;
public class2(class1 a) {
this.a = a;
a = new class1();
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("file.txt", true));
String add1 = a.field1.getText();
String add2 = a.field2.getText();
writer.write(add1);
writer.write("\t");
writer.write(add2);
writer.write("\t");
} catch ( IOException e) {
} finally {
try {
if ( writer != null)
writer.close( );
} catch ( IOException e) {
}
}
}
}