Hi! I'm learning how to make a GUI in Java.

I'm wondering how to add a JThingy (JLabel, etc) without the use of the add(NameOfJThingy);

Because add(); isn't static, you can't use it in a static function (like main, which must be static).
I've seen that the constructor can help, but I don't want to make a new class so often. Is there another way to add something to GUIs?
Thanks,
JT

Recommended Answers

All 5 Replies

OK. I'll post my code :)

import javax.swing.*;


@SuppressWarnings("serial")
public class Main extends JFrame {
	ImageIcon ic1=new ImageIcon("12471.jpg");//12471 is an image :)
	JLabel lab1=new JLabel(ic1);
	public Main()
	{
		add(lab1);
	}
public static  void main(String []args)
{
Main a=new Main();
a.setVisible(true);
a.setSize(200, 200);

//add(lab1);
}
}

This works how I want it to, but I'm wondering if there's a way to do something like the add (J____); but something static or some other way to add the J____ to the JFrame.

Also, I can't figure out how to use a label that has text and an image. I thought it was =new JLabel("TEXT", IMAGEICON, POSITION);

add is't static because you add a JThingy to an instance of JFrame, not to the class JFrame. Here the normal template for stuff lkike this

public class Main extends JFrame {
  ImageIcon ic1=new ImageIcon("12471.jpg");//12471 is an image :)
  JLabel lab1=new JLabel(ic1);
  ...
  public static void main(String []args) {
   new Main();
  }

  public Main() {  // instance constructor
   add(lab1);
   setSize(200, 200);
   setVisible(true);
   ...
  }
  ...
}

Ok, But how do I add something when I add it through a static function?

Ok, But how do I add something when I add it through a static function?

By using an instance, like you did in your original code for setSize/Visibility.
But I would question why you want to do that. Java code doesn't often use static methods in that kind of way. Maybe you are transferring a C++ mode of thought when you should be switching to a Java idiom??? This may be a topic for a new thread?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.