初学者编码器。
在输入信息后编写了一个简单的GUI来计算面积和周长。问题是标签在动作事件后消失。我无法弄清楚可能导致它的代码有什么问题。
我把行设为“setVisible(true);”在对象的最后。
import java.awt.*;
import java.awt.event.*;
public class RectangleCalc extends Frame implements ActionListener {
private Label widthLblInput; //label input for width
private Label heightLblInput; //label input for height
private TextField tfWidth; //text field for width
private TextField tfHeight; //text field for height
private TextField tfArea; //text field for area
private TextField tfPerimeter; //text field for Perimeter
private Button btnArea;
private Button btnPerimeter;
private int width;
private int height;
private int area = 0;
private int perimeter = 0;
/** time for GUI setup */
public RectangleCalc() {
setLayout(new FlowLayout());
// WIDTH GUI
widthLblInput = new Label("Enter the Width: "); // Construct label for widthInput
add(widthLblInput);
tfWidth = new TextField(10); // Add Textfield for width
add(tfWidth);
// HEIGHT GUI
heightLblInput = new Label("Enter the Height: "); // Construct label for heightInput
add(heightLblInput);
tfHeight = new TextField(10); // Add Textfield for height
add(tfHeight);
// AREA GUI
tfArea = new TextField("0", 10); // text field for area calculation
tfArea.setEditable(false);
add(tfArea);
btnArea = new Button("Area");
add(btnArea);
btnArea.addActionListener(this);
// PERIMETER GUI
tfPerimeter = new TextField("0", 10); // text field for Perimeter calculation
tfPerimeter.setEditable(false);
add(tfPerimeter);
btnPerimeter = new Button("Perimeter");
add(btnPerimeter);
btnPerimeter.addActionListener(this);
// WINDOW LAYOUT
setTitle("Rectangle Calculator");
setSize(300, 180);
setVisible(true);
}
/** The entry main() method */
public static void main(String[] args) {
new RectangleCalc();
}
@Override
/** Action Event */
public void actionPerformed(ActionEvent evt) {
width = Integer.parseInt(tfWidth.getText());
height = Integer.parseInt(tfHeight.getText());
area = (width * height);
perimeter = ((width*2) + (height*2));
widthLblInput.setText("");
heightLblInput.setText("");
tfPerimeter.setText(perimeter + "");
tfArea.setText(area + "");
}
}
答案 0 :(得分:0)
您在actionPerformed方法中明确将标签字段设置为空:
widthLblInput.setText("");
heightLblInput.setText("");
这会使它们看起来已经消失了。