I am a beginner in Java & I am learning the swing api. I am having trouble with my code, and I can’t figure out how to fix it. Please help.
Below is an example of the code I am using:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class HelloWorldApp extends JFrame {
public static void main(String args[]) {
CustomWindow w = new CustomWindow();
w.setVisible(true);
}
public CustomWindow() {
setSize(500, 500);
setTitle("Jacob Perkins");
JLabel lbl = new JLabel("Hello World!");
add(lbl);
}
}
My problem is that I get the following error:
invalid method declaration; return type required
should be:
Or instead of
void(for returning nothing) we would put the data type we wanted to return. The method would now have to include areturnstatement which returns an appropriate data type to match the method signature, or you will get the error you have:See Returning a Value from a Method.
Unless you are attempting to create a constructor for the
HelloWorldAppclass than the method must be given the class name (have a read on Providing Constructors for Your Classes):Other suggestions
Dont extend
JFrameunnecessarily.Dont call
setSizerather use correctLayoutManagerand/or overridegetPreferredSizeand returnDimensions which fit its contents. Than callpack()onJFramebefore setting it visible but after adding components.Create and manipulate Swing components on Event Dispatch Thread via
SwingUtilities.invokeLater(Runnable r)block: