第1个回答 2013-02-13
//这是A类
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MyFrame extends JFrame {
private JButton addButton;
private JTextField resultText;
public static void main(String[] args) {
new MyFrame();
}
public MyFrame() {
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
resultText = new JTextField(20);
addButton = new JButton("+1");
addButton.addActionListener(new AddButtonAction(resultText));
add(resultText);
add(addButton);
setVisible(true);
}
}
//这是B类
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class AddButtonAction implements ActionListener {
private JTextField resultText;
public AddButtonAction(JTextField resultText) {
this.resultText = resultText;
}
public void actionPerformed(ActionEvent e) {
try {
int value = Integer.parseInt(resultText.getText());
resultText.setText(String.valueOf(value + 1));
} catch (NumberFormatException ne) {
resultText.setText("your input string is not a number!");
}
}
}