Question

In Java how can we control if a variable was already created or not ? For example, I want to create a button with the variable name kutu but if there already is a button with the variable name kutu I don't want to create it.

button1.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){

           JButton kutu=new JButton("my box");
           kutu.setBounds(480, 620,120, 50);add(kutu);
           remove(button1);
           revalidate();
           repaint();
       }});

This is the code. There are 24 buttons (all of them have same action) and if the user clicks 2 or more buttons I dont want to create JButton kutu because kutu is already created in first click.

Was it helpful?

Solution

What you want to do is use a class field not a local variable. This way you can test if an object has been created and assigned to the class field before, and if not, create a new object and assign it to the variable:

public class MyClass {
  private JButton kutu = null;

  // in some action listener:
  public void actionPerformed(ActionEvent e) {
    // only create this JButton if the variable has not
    // been assigned a JButton object
    if (kutu == null) {
      kutu = new JButton("Some Text");

      // ... etc
    }
  }

As an aside, you don't want to use null layouts and setBounds(...). While initially this might seem the best and easiest way to create complex GUI's, if you program with Swing for any length of time, you'll come to find out that using null layouts puts your program into a straight jacket, making it very rigid, and very difficult to enhance. It also makes a GUI that looks good on one platform only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top