在一个两个类之间的元素中添加一些文本

时间:2015-10-15 16:23:37

标签: java user-interface actionlistener

我在文件夹中有两个类。我点击 class 2 的按钮后,我想在 class 1 的文本区域添加一些文字。但这不起作用。

我该怎么办?

第1类:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;


public class TwoClasses {

    public JTextArea textArea;
    public JFrame frame;
    public JTextField textS;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TwoClasses window = new TwoClasses();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TwoClasses() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        textS = new JTextField();
        textS.setBounds(102, 101, 216, 20);
        frame.getContentPane().add(textS);
        textS.setColumns(10);

        textArea = new JTextArea();
        textArea.setBounds(61, 11, 303, 66);
        frame.getContentPane().add(textArea);
    }
}


第2课:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;


public class TwoClasses2 {

public JFrame frame;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TwoClasses2 window = new TwoClasses2();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
//TwoClasses obj = new TwoClasses();
/**
 * Create the application.
 */
public TwoClasses2() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
public void initialize() {
    final TwoClasses obj = new TwoClasses();
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnButton = new JButton("Button");

    btnButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            obj.textArea.setText("This is an example!");
        }
    });
    btnButton.setBounds(134, 124, 89, 23);
    frame.getContentPane().add(btnButton);
}
}

0 个答案:

没有答案