简体   繁体   English

GUI 上的方法声明无效,需要返回类型

[英]invalid method declaration, return type required, on a GUI

So im trying to make a simple GUI that goes up by one when you click a button in it.因此,我试图制作一个简单的 GUI,当您单击其中的按钮时,它会上升一个。 I get this error, however, when i try and run the test GUI: Error.但是,当我尝试运行测试 GUI 时出现此错误:错误。 Here is the code这是代码

import javax.swing.JFrame;
import javax.swing.BorderFactory;
import javax.swing.JPanel;


public class Main {

public GUI() {

  JFrame frame = new JFrame();
  JPanel panel = new JPanel();
  panel.setBorder(borderFactory.createEmptyBorder(30, 30, 10, 30));
  panel.setLayout(new GridLayout(0, 1));

  frame.add(panel, BorderLayout.CENTER);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setTitle("Clicks");
  frame.pack();
  frame.setVisible(true);

}

  public static void main(String[] args) {

    new GUI();

  }
}
public class Main {

public GUI() {

GUI seems intended as a constructor and the constructor must have the same name as the class. GUI似乎打算用作构造函数,并且构造函数必须与 class 具有相同的名称。 But neither GUI nor Main are good, descriptive names for a class / constructor.但是GUIMain都不是 class / 构造函数的好的描述性名称。 The name should be descriptive of that the class actually is.该名称应该描述 class 实际上是。 So here is something that might not only be better, but should work for this case.所以这里的东西可能不仅更好,而且应该适用于这种情况。

public class ClicksGUI {

public ClicksGUI() {

Note that if changing the name of the class / constructor, the reference in the main method also needs to change to reflect that.请注意,如果更改 class / 构造函数的名称,则main方法中的引用也需要更改以反映这一点。

If you want GUI to be a function you must specify a return type (I suppose you want void in your case), and call it like a regular function, not to create an object of it:如果您希望GUI成为 function,您必须指定一个return type (我想您希望在您的情况下为void ),并像常规 function 一样调用它,而不是创建 ZA8CFDE6331BD59EB26696F8911ZCB:

public class Main {

public static void GUI() {

  JFrame frame = new JFrame();
  JPanel panel = new JPanel();
  panel.setBorder(borderFactory.createEmptyBorder(30, 30, 10, 30));
  panel.setLayout(new GridLayout(0, 1));

  frame.add(panel, BorderLayout.CENTER);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setTitle("Clicks");
  frame.pack();
  frame.setVisible(true);

}

  public static void main(String[] args) {

    GUI();

  }
}

Add void as return type for your GUI method添加void作为 GUI 方法的返回类型

public class Main {

public static void GUI() {
.....
}
}

and call it as a method from main() method.并将其作为 main() 方法中的方法调用。

public static void main(String[] args) {

    GUI();

  }

Java expects a return type for methods. Java 需要方法的返回类型。 If you don't want to specify return type, use a constructor instead.如果您不想指定返回类型,请改用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM