2

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) {
            }
        }       
    }
}
4

2 回答 2

2

in 中的行创建了一个与a = new class1()class2创建的实例不同的实例mainclass。相反,将引用传递class1给您的class2构造函数。

if (result == JOptionPane.OK_OPTION) {
    class2 ad = new class2(this);
}
...
public class2(class1 a) {
    //a = new class1();
    this.a = a;
    ...
}
于 2013-02-20T18:02:03.767 回答
2

这是一个问题。

的构造函数在这里class1创建一个实例class2

class2 ad = new class2();

它调用class2.

它创建了一个class1这里的实例:

a = new class1();

它调用class1.

这再次提示您。

因此,您只能class2在第二个提示之后(如果您取消)到达构造函数的其余部分。

于 2013-02-20T18:02:11.483 回答