Heshamy Heshamy - 2 months ago 12
Java Question

Java Function/GUI

I'm trying to make a calculator with GUI, and I figured out I will have to repeat the JButton code million of times, so I decided to make a function instead, but I'm not able to do a function. Here's what I did

public static void button(String name, int size1, int size2, int loc1, int loc2) {
JButton l=new JButton(name);
l.setSize(size1, size2);
l.setLocation(loc1, loc2);
}


And inside the main, I did this

myForm.add(button("5", 20, 20, 20, 20));


After declaring myForm for sure, but I keep getting this error:
The method add(Component) in the type Container is not applicable for the arguments (void)

I'm new to functions and java, thus it looks confusing.
Thank you.

Answer

Issue 1

First things first, regarding your error:

The method add(Component) in the type Container is not applicable for the arguments (void)

Your button() method returns a void, you have to make it return the object:

public static JButton button(String name, int size1, int size2, int loc1, int loc2) {
  JButton l=new JButton(name);
  l.setSize(size1, size2);
  l.setLocation(loc1, loc2);
  return l;
}

myForm.add() expects a Component to be passed, so you simply needed to return the JButton created by your helper button() method.

Issue 2

The second issue here will be with your application's design: there is no way creating 1,000,000 JButton instances makes sense.

It will:

  • eat away your memory,
  • be useless in terms of UI/UX.

More likely, you want to create as many JButtons as you need at any given time on the screen, and reuse these depending on the actions you want.

Considering your requirement, I suspect you want to try to display a very large grid of objects you can interact with (say a giant Minesweeper, Game of Life, or biology simulation maybe?). If that's the case, quite likely you'll want to draw the objects yourself and to handle events yourself to reduce the overhead.

Comments