【发布时间】:2019-02-20 20:17:34
【问题描述】:
我一直试图找出我的代码有什么问题。我必须构建一个 GUI,并且没有错误。程序构建成功,但没有弹出 GUI。所以在 main 方法中,我注释掉了 GUI 编程并添加了一个简单的System.out.println("hello");,但它做同样的事情,即它构建成功,但不打印任何东西。有人可以告诉我有什么问题吗?谢谢!
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.*;
import javax.swing.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
super("Triangle Area Calculator");
setSize(500, 300);
setLayout(g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5*bInput*hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
public static void main(String[] args) {
/*JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);*/
System.out.println("hello world");
}
}
【问题讨论】:
-
你的代码是如何运行的?
-
@Mureinik 我正在使用 netbeans,绿色播放按钮(运行项目,(F6))
-
您还必须告诉 NetBeans 您的项目的主要类是什么。在您的情况下,您的主要课程似乎是
gui.GUI。你做到了吗? -
@MikeNakis 我刚刚检查了项目属性,主类已经是gui.GUI,所以我不确定它为什么会这样做。
-
另外,您希望输出显示在哪里?确认您没有无意中隐藏了 NetBeans 终端。