好吧,在addActionListener(this)语句之前我没有问题。我不知道将按钮链接到要在文本字段中输入的各自字符串的位置
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener {
private JButton one, two, three, four, five, six, seven, eight, nine, zero, point, cancel;
private JTextField t;
private JFrame frame;
private String number = "";
public GUI() {
//creating button objects
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton zero = new JButton("0");
JButton point = new JButton(".");
JButton cancel = new JButton("cancel");
//call addActionListener() method
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
//point.addActionListener(this);
//cancel.addActionListener(this);
//create jframe object
JFrame frame = new JFrame("Vendor");
//create text field
JTextField t = new JTextField();
frame.setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //remove this after creating other modules
//creating panel object
JPanel panel = new JPanel();
GridLayout grid = new GridLayout(0, 3);
panel.setLayout(grid);
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
//setting text field to the top of the frame
add(t, BorderLayout.NORTH);
//adding buttons to panel
panel.add(one);
panel.add(two);
panel.add(three);
panel.add(four);
panel.add(five);
panel.add(six);
panel.add(seven);
panel.add(eight);
panel.add(nine);
panel.add(zero);
panel.add(point);
panel.add(cancel);
//adding panel to frame
add(panel);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == one) {
t.setText(t.getText().concat("1"));
}
if (e.getSource() == two) {
t.setText(t.getText().concat("2"));
}
if (e.getSource() == three) {
t.setText(t.getText().concat("3"));
}
if (e.getSource() == four) {
t.setText(t.getText().concat("4"));
}
if (e.getSource() == five) {
t.setText(t.getText().concat("5"));
}
if (e.getSource() == six) {
t.setText(t.getText().concat("6"));
}
if (e.getSource() == seven) {
t.setText(t.getText().concat("7"));
}
if (e.getSource() == eight) {
t.setText(t.getText().concat("8"));
}
if (e.getSource() == nine) {
t.setText(t.getText().concat("9"));
}
if (e.getSource() == zero) {
t.setText(t.getText().concat("0"));
}
/*if(e.getSource() == point) {
t.setText(t.getText().concat("."));
}*/
}
public static void main(String[] args) {
GUI object = new GUI();
}
}
答案 0 :(得分:3)
您在构造函数中本地声明了按钮,从而覆盖了您的成员变量。您的成员变量一,二,三......将始终为null。您可以像这样编写构造函数:
public GUI() {
//creating button objects
one = new JButton("1");
two = new JButton("2");
.
.
.