Problems with new in Java

4

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

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

Java runs this command ie it shows the class LevelDraw and opens the class from where this command was executed. Now, why does this happen?

NOTE: I've done this same procedure in the Netbeans constructor and it worked. Why are not you giving it to me now?

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 ID LevelDraw :

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 > Dashboard :

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)
    
asked by anonymous 27.04.2015 / 06:37

1 answer

2

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

  

I've done this same procedure in Netbeans' "JFrame's builder" and it worked. Why are not you giving it to me now?

For Já fiz esse mesmo procedimento no... you should be talking you could use setVisible in an instance of [ JFrame ] [jframe.

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

If for PainelNivel is giving error, this is why PainelNivel is not somehow a subclass of Component .

Note:

  

java executes this command that is, it shows the class PanelPanel and opens the class from where this command was executed. Now, why does this happen?

In fact, it is not that java runs this command, shows the class, and opens the class from which this command was executed. new is a keyword 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 hand and listing the classes in the classpath of your project. There are other comments in your text, but anyway, this is for later =)

If my understanding is wrong, just talk = D

EDIT:

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

Well, your program has several problems, I will not mention all and not even refactor it all, but only highlight points that made 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 like this:

private final PainelNivel painel = new PainelNivel();

In addition, also in class Window , where new PainelNivel().setVisible(true); , replace painel.setVisible(true); . Finally, even in the PainelNivel class, change from:

private Window w = new Window();

To:

private static Window w;

and include 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 of avoiding this we have already passed to PainelNivel the responsibility of controlling the life cycle of the single instance of Window (obs .: this may not be the best solution, but due to the form that is, property limit , to simplify I did so) and we changed the flow of the application a little bit.

Finally, remove from class PainelNivel

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

Once the above changes have been made and a few others to take a look at, in my environment the class PainelNivel looks 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 looks 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 prompted with the error message, if it keeps happening to you, let me know the steps to play =)

    
27.04.2015 / 08:11