我正在java中创建GUI,并收到以下错误:
Error: Main method not found in class mainGUI, please define the main method as:
public static void main(String[] args)
我无法弄清楚为什么会发生这种情况,考虑到我的代码中确实有一个 main 方法并且它确实包含一些代码。我的 GUI 代码如下:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class mainGUI extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL, perimeterL;
private JTextField lengthTF, widthTF, areaTF, perimeterTF;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public mainGUI() {
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
perimeterTF = new JTextField(10);
calculateB = new JButton("Calculate");
exitB = new JButton("Exit");
Container pane = getContentPane();
pane.setLayout(new GridLayout(5, 2));
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setTitle("Main Menu");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
mainGUI rectObj = new mainGUI();
}
}
谁能阐明为什么会发生这种情况?
非常感谢:)
您的代码工作正常,请尝试从命令行运行它,或尝试重新安装 eclipse,因为它不是代码错误,而是环境错误。
如果这不起作用,请尝试重新创建它,从main开始,然后向上走,它应该可以精确定位日食的作用位置。
祝你好运!
,我来这里是为了寻找类似问题的答案。事实证明,具有相同名称的Java文件的较旧错误版本在我的Java主目录中。正确的文件保存在其他目录中。也许您遇到了类似的问题。
编辑:我看到这篇文章已经有好几年了。OP现在可能是一名首席信息官。为那些将文件保存到奇怪地方的人留下评论。