Problems with new in Java

Asked

Viewed 173 times

4

Why every time I use new in my class, for example:

if(e.getSource() == levelButton) {
     new PainelNivel().setVisible(true);
}

Java executes this command, i.e., shows the class Panel and opens the class from which this command was executed. Now, why does this happen?

NOTE: I’ve done this same procedure in the "constructor Jframe’s" of Netbeans and it worked. Why now is not giving?

package main;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Window extends JFrame implements ActionListener {

// Variáveis

JButton generateButton = new JButton("Gerar outro número");
JButton testButton = new JButton("Verificar");
JButton levelButton = new JButton("Nível");
private final JLabel label = new JLabel("Digite um número de 1 a 1000.");
JTextField campotext = new JTextField(27);
private final Object[] ops = new Object[3];

private int i, limit, num, palp, c;

// Construtor
public Window() {
    super("Adivinha Número 1.0");
    setSize(420, 120);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    add(label);
    add(campotext);
    add(testButton);
    add(generateButton);
    add(levelButton);
    testButton.addActionListener(this);
    generateButton.addActionListener(this);
    levelButton.addActionListener(this);

    setLocationRelativeTo(null);
    setResizable(false);
    setVisible(true);
    Generate();
}

// Gerador
private void Generate() {
    Random gen = new Random();
    num = gen.nextInt(1001);
}

// Teste
private void Test(int palp) {

    if(palp < num) {
        JOptionPane.showMessageDialog(this, "Errou, o número é maior");
    } else if(palp > num) {
        JOptionPane.showMessageDialog(this,"Errou, o número é menor");
    } else {
        JOptionPane.showMessageDialog(this,"Parabéns, voce acertou o numero!");
        campotext.setEditable(false);
    }
}

public int SetLimit(int l) {

    this.limit = l;
    return l;
}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource() == testButton) {
        palp = Integer.parseInt(campotext.getText());
        Test(palp);

    if(i == limit) {

        ops[0] = "Fechar";
        ops[1] = "Gerar Outro Número";
        ops[2] = "Mudar Nível";

        c = JOptionPane.showOptionDialog(this, "Você chegou ao limite de   tentativas!", "Game Over", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, ops, ops[0]);

    if(c == JOptionPane.YES_OPTION) {
        System.exit(0);
    } else if(c == JOptionPane.NO_OPTION) {
        Generate();
        campotext.setText("");
        i = 0;
    } else if(c == JOptionPane.CANCEL_OPTION) {
        new PainelNivel().setVisible(true);
    }

    } else {
        i++;
        System.out.println("Contador = " + i);
    }
}

    if(e.getSource() == generateButton) {
            Generate();
            campotext.setEditable(true);
            campotext.setText("");
            i = 0;
            System.out.println("Contador = " + i);
        }

    if(e.getSource() == levelButton) {
            new PainelNivel().setVisible(true);
        }
    }

public static void main(String[] args) {
    new Window();
}
 }        

Class code Panel:

package main;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;

public class PainelNivel extends JDialog implements ActionListener {

private Window w = new Window();

private final JLabel inst = new JLabel("Selecione o nível de dificuldade:");
private final JButton f = new JButton("Fácil (50 Tentativas)");
private final JButton m = new JButton("Médio (30 Tentativas)");
private final JButton d = new JButton("Difícil (10 Tentativas)");

public PainelNivel() {
    setTitle("Seletor De Nível");
    setSize(270, 160);
    setResizable(false);
    setLocationRelativeTo(w);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setLayout(new FlowLayout());

    add(inst);
    add(f);
    add(m);
    add(d);
    f.addActionListener(this);
    m.addActionListener(this);
    d.addActionListener(this);

}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == f) {
        w.SetLimit(50);
        dispose();
    } else if(e.getSource() == m) {
        w.SetLimit(30);
        dispose();
    } else if (e.getSource() == d) {
        w.SetLimit(10);
        dispose();
    }
  }
}

printStackTrace > Panel:

java.lang.Throwable: Printing stack trace:
at com.sun.corba.se.impl.util.Utility.printStackTrace(Utility.java:933)
at main.Window.<init>(Window.java:48)
at main.PainelNivel.<init>(PainelNivel.java:13)
at main.Window.actionPerformed(Window.java:116)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at      javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
java.lang.Throwable: Printing stack trace:
at com.sun.corba.se.impl.util.Utility.printStackTrace(Utility.java:933)
at main.PainelNivel.<init>(PainelNivel.java:36)
at main.Window.actionPerformed(Window.java:116)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

1 answer

2


In this example you are trying to create an instance of PainelNivel and calling to this instance the method setVisible.

I’ve done the same procedure in the Netbeans "Jframe Builder" and it worked. Why is it not working now?

For Já fiz esse mesmo procedimento no... you must be saying that you managed to use setVisible in an instance of [JFrame][jframe.

Well, it worked with JFrame why he has this method, since it is a subclass of Window which is a subclass of Component (Obs.: all that somehow extend from Component have such a method).

If to PainelNivel is giving error, this is why PainelNivel is not, in any way, a subclass of Component.

Observing:

java executes this command, i.e., shows the Painellevel class and opens the class from which this command was executed. Now, why does this happen?

Actually it is not that java executes this command, shows the class and opens the class from which this command was executed. new is a key word and reserved in the language to create instances and the class is shown by the IDE (in your case Netbeans) because it is giving you a helping hand and listing the classes in your project’s classpath. There are other comments in your text, but finally, this is for later =)

In case my understanding is wrong, just say =D

EDIT:

Well, considering the comments, the initial understanding above is completely different from the problem, even due to the initial text of the question.

Well, your program has several problems, I will not quote all and not even refactor it all, but just highlight points that caused the error no longer appear, at least here.

First: you are creating N instance of PainelNivel. As far as I understand there is no need for this, since you can just make it visible. So, create a variable in Window thus:

private final PainelNivel painel = new PainelNivel();

Also in the class Window, where to own new PainelNivel().setVisible(true);, replace with painel.setVisible(true);. Finally, still in class PainelNivel, altere of:

private Window w = new Window();

for:

private static Window w;

and include the method main in PainelNivel:

public static void main(final String[] args) {
    w = new Window();
}

Second: you are also creating more instances of Window than necessary. As a way to avoid this we have already passed to PainelNivel the responsibility to monitor the life cycle of the single Window (Obs.: this may not be the best solution, but due to the shape it is, ie the property limit, to simplify I did so) and we changed a little the flow of the application.

Finally, remove from class PainelNivel

public static void main(final String[] args) {
    w = new Window();
}

Carried out the above changes and some others for you to take a look, in my environment the class PainelNivel was like this:

public class PainelNivel extends JDialog implements ActionListener {

    private static final long serialVersionUID = 1793309720800631003L;

    private static Window window;

    private final JLabel lblSelecioneNivel = new JLabel("Selecione o nível de dificuldade:");
    private final JButton btnFacil = new JButton("Fácil (50 Tentativas)");
    private final JButton btnMedio = new JButton("Médio (30 Tentativas)");
    private final JButton btnDificil = new JButton("Difícil (10 Tentativas)");

    public PainelNivel() {
        setTitle("Seletor De Nível");
        setSize(270, 160);
        setResizable(false);
        setLocationRelativeTo(window);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLayout(new FlowLayout());

        add(lblSelecioneNivel);
        add(btnFacil);
        add(btnMedio);
        add(btnDificil);
        btnFacil.addActionListener(this);
        btnMedio.addActionListener(this);
        btnDificil.addActionListener(this);
    }

    @Override
    public void actionPerformed(final ActionEvent e) {
        if (e.getSource() == btnFacil) {
            window.setLimit(50);
            dispose();
        } else if (e.getSource() == btnMedio) {
            window.setLimit(30);
            dispose();
        } else if (e.getSource() == btnDificil) {
            window.setLimit(10);
            dispose();
        }
    }

    public static void main(final String[] args) {
        window = new Window();
    }

}

And the class Window was like this:

public class Window extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1096933824629421772L;

    private final PainelNivel painel = new PainelNivel();

    private final JButton btnGerarNumero = new JButton("Gerar outro número");
    private final JButton btnVerificar = new JButton("Verificar");
    private final JButton btnNivel = new JButton("Nível");
    private final JLabel lblDigiteNumero = new JLabel("Digite um número de 1 a 1000.");
    private final JTextField txtFieldNumero = new JTextField(27);
    private final Object[] dialogOpcoes = {"Fechar", "Gerar Outro Número", "Mudar Nível"};

    private int tentativas, qtdTentativas, numeroAleatorio, palpite, c;

    public Window() {
        super("Adivinha Número 1.0");
        setSize(420, 120);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        add(lblDigiteNumero);
        add(txtFieldNumero);
        add(btnVerificar);
        add(btnGerarNumero);
        add(btnNivel);
        btnVerificar.addActionListener(this);
        btnGerarNumero.addActionListener(this);
        btnNivel.addActionListener(this);

        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
        generate();
    }

    private void generate() {
        final Random gen = new Random();
        numeroAleatorio = gen.nextInt(1001);
    }

    private void testePalpite(final int palp) {
        if (palp < numeroAleatorio) {
            JOptionPane.showMessageDialog(this, "Errou, o número é maior");
        } else if (palp > numeroAleatorio) {
            JOptionPane.showMessageDialog(this, "Errou, o número é menor");
        } else {
            JOptionPane.showMessageDialog(this, "Parabéns, voce acertou o numero!");
            txtFieldNumero.setEditable(false);
        }
    }

    public void setLimit(final int limit) {
        qtdTentativas = limit;
    }

    @Override
    public void actionPerformed(final ActionEvent e) {
        if (e.getSource() == btnVerificar) {
            palpite = Integer.parseInt(txtFieldNumero.getText());
            testePalpite(palpite);

            if (tentativas == qtdTentativas) {
                c = JOptionPane.showOptionDialog(this, "Você chegou ao limite de tentativas!", "Game Over",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, dialogOpcoes,
                        dialogOpcoes[0]);

                if (c == JOptionPane.YES_OPTION) {
                    dispose();
                } else if (c == JOptionPane.NO_OPTION) {
                    generate();
                    txtFieldNumero.setText("");
                    tentativas = 0;
                } else if (c == JOptionPane.CANCEL_OPTION) {
                    painel.setVisible(true);
                }
            } else {
                System.out.println("Tentativas já realizadas = " + ++tentativas);
            }
        }

        if (e.getSource() == btnGerarNumero) {
            generate();
            txtFieldNumero.setEditable(true);
            txtFieldNumero.setText("");
            tentativas = 0;
            System.out.println("Tentativas já realizadas = " + tentativas);
        }

        if (e.getSource() == btnNivel) {
            System.out.println("Alteração de nível solicitada.");
            painel.setVisible(true);
        }
    }

}

I was not given the error message, if it continues with you, inform me the steps to play =)

  • Well, Painelnivel is a Jdialog, and as far as I know Jdialog is a subclass of Component, right? To clarify I will post the code of the Panel Checklevel in the answer, ok?

  • Yes @Dongabi. So please update your question with the bug trace stack and more information about PainelNivel. Thank you.

  • Ready! - @Bruno_césar

  • It’s kind of hard to understand what you’re doing young. You have a class Window, that treats some events and in some event creates an instance of PainelNivel, right? In PainelNivel you create a Window and says that the PainelNivel is related to the Window? o_O, man, crazy, it’s hard to understand the flow of your application. Post the class Window to see if I can better understand

  • Ready - @Bruno_césar

  • @Dongabi edited the answer considering some points, see if it works with you too. Good studies :)

  • Po vey, thanks a lot! It worked out! It’s just that I’m starting now, you know?... More worth brother! : D

  • Come on, man, just need some value.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.