简体   繁体   中英

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. I get this error, however, when i try and run the test GUI: Error. 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. But neither GUI nor Main are good, descriptive names for a class / constructor. The name should be descriptive of that the class actually is. 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.

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:

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

public class Main {

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

and call it as a method from main() method.

public static void main(String[] args) {

    GUI();

  }

Java expects a return type for methods. If you don't want to specify return type, use a constructor instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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