我正在使用java创建一个GUI,并收到以下错误:
Error: Main method not found in class mainGUI, please define the main method as:
public static void main(String[] args)
我无法弄清楚为什么会发生这种情况,因为我的代码中确实有一个主方法,它确实包含一些代码。我的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();
}
}
有人能说清楚为什么会这样吗?
非常感谢:)
答案 0 :(得分:0)
您的代码运行正常,尝试从命令行运行它,或尝试重新安装eclipse,因为它不是代码错误,它是一个环境错误。
如果这不起作用,尝试重新创建它,从main开始,然后向上走,它应该确定eclipse正在起作用的地方。
祝你好运!答案 1 :(得分:0)
你知道,我来这里寻找类似问题的答案。结果是我的Java主目录中具有相同名称的旧文件的错误版本。正确的文件保存在其他一些目录中。也许你遇到了类似的问题。
编辑:我看到这篇文章已经有好几年了。 OP现在可能是一名CIO。对那些将文件保存到奇数位置的人留下评论。