import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Copy {
JFrame f=new JFrame();
JButton copy=new JButton("Copy");
JButton clear=new JButton("Clear");
JTextField t1=new JTextField();
JTextField t2=new JTextField();
JPanel p_top=new JPanel();
JPanel p_b=new JPanel();
JPanel p=new JPanel();
public Copy() {
Container c=f.getContentPane();
p_top.setLayout(new GridLayout(2,1));
p_top.add(t1);
p_top.add(t2);
p_b.setLayout(new FlowLayout());
p_b.add(copy);
p_b.add(clear);
p.setLayout(new BorderLayout());
p.add(p_top,BorderLayout.CENTER);
p.add(p_b,BorderLayout.SOUTH);
c.add(p);
copy.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
t2.setText(t1.getText());
}
}
);
clear.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.setText("");
t2.setText("");
}
}
);
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args) {
new Copy();
}
}先编的,GUI可能不好看。
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Copy {
JFrame f=new JFrame();
JButton copy=new JButton("Copy");
JButton clear=new JButton("Clear");
JTextField t1=new JTextField();
JTextField t2=new JTextField();
JPanel p_top=new JPanel();
JPanel p_b=new JPanel();
JPanel p=new JPanel();
public Copy() {
Container c=f.getContentPane();
p_top.setLayout(new GridLayout(2,1));
p_top.add(t1);
p_top.add(t2);
p_b.setLayout(new FlowLayout());
p_b.add(copy);
p_b.add(clear);
p.setLayout(new BorderLayout());
p.add(p_top,BorderLayout.CENTER);
p.add(p_b,BorderLayout.SOUTH);
c.add(p);
copy.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
t2.setText(t1.getText());
}
}
);
clear.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.setText("");
t2.setText("");
}
}
);
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args) {
new Copy();
}
}先编的,GUI可能不好看。
if(e.getActionCommand().equals("Copy"))
t2.setText(t1.getText());
}
catch(NullPointerException nullPointerException) {
System.exit(0);
}
if (e.getActionCommand().equals("Clear"))
{
...
}
换成这一段就可以看出来是这个错误,试着找找错误看吧。
copy.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
t2.setText(t1.getText());
}
}
);
这个时候访问的t1,t2是全局变量t1,t2,他们仅仅是被申明,却没有被初始化,要改的话,很简单,只需要将First里的
JTextField t1=new JTextField();
JTextField t2=new JTextField();
改成:
t1=new JTextField();
t2=new JTextField();就行了