0

I don't know how to call another class (called Calc) that is in the same package as my main class (Lista), using the JMenuItem. If i need to be more specific, i dont know how to call my class Calc to my Lista class using a JMenuItem that its on my Lista class.

The code below is my Lista class, sorry for the english guys

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.event.MenuEvent;
    import javax.swing.event.MenuListener;

    import javax.swing.*;
    import java.awt.event.*;

    public class Lista extends JFrame{
      public Lista(){
        super("Menu");

        // Menu Bar
        JMenuBar barra = new JMenuBar();
        setJMenuBar(barra);

        // Menu
        JMenu opcoes = new JMenu("Options");

        // Menu Item
        JMenuItem item = new JMenuItem("Item 1");

        // actionlistener
        item.addActionListener(
          new ActionListener(){
            public void actionPerformed(ActionEvent e){
              //I think that is in here where i must write the code
            }
          }
        );

        opcoes.add(item);

        // Adds
        barra.add(opcoes);

        setSize(300, 150);
        setVisible(true);    
      }

      public static void main(String args[]){
        Lista app = new Lista();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
    }

The other class, Calc, its just a simple calculator that i made with this code: public class Calc extends JFrame {

public Calc(){
    super("Calculadora");
    Container tela = getContentPane();
    setLayout(null);

    JLabel rotulo1 = new JLabel("1 numero: ");
    JLabel rotulo2 = new JLabel("2 numero: ");
    JLabel showup = new JLabel("");

    JTextField texto1 = new JTextField(5);
    JTextField texto2 = new JTextField(5);

    JButton somar = new JButton ("+");
    JButton subtrair = new JButton("-");
    JButton dividir = new JButton("/");
    JButton multiplicar = new JButton("x");
    JButton exibir = new JButton("=");

    rotulo1.setBounds(30,20,100,20); rotulo2.setBounds(30,60,100,20);
    texto1.setBounds(100,20,200,20); texto2.setBounds(100,60,200,20);
    showup.setBounds(125,100,200,20);
    somar.setBounds(230,100,45,45);//coluna, linha, largura, comprimento
    subtrair.setBounds(280,100,45,45);
    dividir.setBounds(230,155,45,45);
    multiplicar.setBounds(280,155,45,45);
    exibir.setBounds(255,205,45,45);


    setVisible(true);
    setLocationRelativeTo(null);

    tela.add(rotulo1); tela.add(rotulo2);
    tela.add(texto1); tela.add(texto2); tela.add(showup);
    tela.add(exibir); tela.add(somar); tela.add(subtrair); tela.add(dividir);tela.add(multiplicar);

    setSize(350,300);

    somar.addActionListener( new ActionListener(){
        public void actionPerformed(ActionEvent e){
            double numero1, numero2, soma;
            soma=0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            soma = numero1+numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText()+""+"+"+""+texto2.getText()+""+"="+soma);
            texto1.setText(null); texto2.setText(null); texto1.requestFocus(); //funcao limpar e focar
        }
    }
    );

    subtrair.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            double numero1, numero2, subtrair;
            subtrair=0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            subtrair = numero1 - numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText()+""+"-"+""+texto2.getText()+""+"="+subtrair);
            texto1.setText(null); texto2.setText(null); texto1.requestFocus();
        }
    });

    multiplicar.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            double numero1, numero2, multiplicar;
            multiplicar=0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            multiplicar = numero1*numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText()+""+"x"+""+texto2.getText()+""+"="+multiplicar);
            texto1.setText(null); texto2.setText(null); texto1.requestFocus();
        }
    });

    dividir.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            double numero1, numero2, dividir;
            dividir=0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            dividir=numero1/numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText()+""+"/"+""+texto2.getText()+""+"="+dividir);
            texto1.setText(null); texto2.setText(null); texto1.requestFocus();
        }
    });


}

public static void main (String [] args){
    Calc app = new Calc();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}

The only thing that i want to do is: when i click in the JMenuItem in Lista code, my calculator program (Calc class) is called. I already tried to do: "Calc calc = new Calc(); calc.Visible(true);" or "item = calc;" but failled. I'm a beginner programmer guys, sorry, i think thats simple.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    It looks like you may be trying to create and display a second JFrame with this code, and if so, you don't want to do this. Please see: [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/questions/9554636). As for your problem, one simple solution is to simply pass in a reference to the visualized other class into this one. – Hovercraft Full Of Eels Jun 05 '16 at 13:55

3 Answers3

2

One simple way to call methods from another class is to obtain a reference to the other class and call the method. If the object of the other class is already in existence, then don't do this by creating a new object, but rather pass a reference from the existing object into this class. How this is done specifically will depend on code that you've not yet shown us.

Note that your code can only run from one main method, and my bet is that it won't be the main method that you have here in the code you've posted but rather will be from another main method in another class, but again all this will depend on code that you've not yet shown us. You may be detecting a theme here, and you should consider improving your question, showing more pertinent code, including how you would plan to launch this class, would it be launched from the other class, what the other class does and looks like, what methods from the other class you'd want to call from this one....

There are better ways to handle, this including M-V-C, however that will likely only confuse you at this stage, but it would be good for you to know that this current solution that I have suggested above, while being easy, is not the cleanest.

It looks like you may be trying to create and display a second JFrame with this code, and if so, you don't want to do this. Please see: The Use of Multiple JFrames, Good/Bad Practice?.

In fact, you're probably better off making Lista not extend JFrame and instead have it create and produce a JMenu which you can then place where and when you need it, but then again, to fully answer your question would require knowledge gained from code that you've not yet shown us.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I already put the another code in this question. Sorry, i dont thought it was important at all. I'm beginner and i just want to call the calculator that is in another class when i click in the JMenuItem called item. – Felipe Squire Jun 05 '16 at 15:39
  • @FelipeSquire: thanks for that post, but sorry, there's more that I want to know, specifically how both classes are supposed to interact. Will Calc display a Lista window say in response to an ActionLIstener? Will both be displaying from the start? Or will Lista display a Calc object, perhaps in response to one of its listeners? Your question is about how to have one class alter the behavior of the other, and how they are supposed to interact is **key** information; doesn't this make sense? – Hovercraft Full Of Eels Jun 05 '16 at 16:21
  • Yes, sorry, Lista class its just like a "Tool window" that when you click in the JMenuItem, i want to open a new window with the content of the Calc class (a calculator). i also want to implement in the future a code to make the Calc class content surpass the Lista content but making the menu stay there, just like a web browser that when you click in a new bar opens a new content in the main container (the body in this case). – Felipe Squire Jun 05 '16 at 16:42
1

Could you make following changes in your classes and see the result:

1) Lista.java

 public static void main(String args[]){
    Lista app = new Lista();        
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    app.setLocationRelativeTo(null); //so that the JFrame appears at the center of screen
  }

2) Lista.java

// actionlistener
item.addActionListener(
      new ActionListener(){
        public void actionPerformed(ActionEvent e){
          //I think that is in here where i must write the code              
          Calc calc=new Calc(Lista.this); // pass owner JFrame i.e. an instance of Lista
          calc.setVisible(true);
        }
      }
 );

3) Calc.java

import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Calc extends JDialog {

private JLabel rotulo1;
private JLabel rotulo2;
private JLabel showup;
private JTextField texto1;
private JTextField texto2;
private JButton somar;
private JButton subtrair;
private JButton dividir;
private JButton multiplicar;
private JButton exibir;

public Calc(Frame owner) {
    super(owner, "Calculadora");
    Container tela = getContentPane();
    setLayout(null);

    rotulo1 = new JLabel("1 numero: ");
    rotulo2 = new JLabel("2 numero: ");
    showup = new JLabel("");

    texto1 = new JTextField(5);
    texto2 = new JTextField(5);

    somar = new JButton("+");
    subtrair = new JButton("-");
    dividir = new JButton("/");
    multiplicar = new JButton("x");
    exibir = new JButton("=");

    rotulo1.setBounds(30, 20, 100, 20);
    rotulo2.setBounds(30, 60, 100, 20);
    texto1.setBounds(100, 20, 200, 20);
    texto2.setBounds(100, 60, 200, 20);
    showup.setBounds(125, 100, 200, 20);
    somar.setBounds(230, 100, 45, 45);// coluna, linha, largura, comprimento
    subtrair.setBounds(280, 100, 45, 45);
    dividir.setBounds(230, 155, 45, 45);
    multiplicar.setBounds(280, 155, 45, 45);
    exibir.setBounds(255, 205, 45, 45);

    setVisible(true);
    setLocationRelativeTo(null);

    tela.add(rotulo1);
    tela.add(rotulo2);
    tela.add(texto1);
    tela.add(texto2);
    tela.add(showup);
    tela.add(exibir);
    tela.add(somar);
    tela.add(subtrair);
    tela.add(dividir);
    tela.add(multiplicar);

    setSize(350, 300);

    somar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            double numero1, numero2, soma;
            soma = 0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            soma = numero1 + numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText() + "" + "+" + "" + texto2.getText() + "" + "=" + soma);
            texto1.setText(null);
            texto2.setText(null);
            texto1.requestFocus(); // funcao limpar e focar
        }
    });

    subtrair.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            double numero1, numero2, subtrair;
            subtrair = 0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            subtrair = numero1 - numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText() + "" + "-" + "" + texto2.getText() + "" + "=" + subtrair);
            texto1.setText(null);
            texto2.setText(null);
            texto1.requestFocus();
        }
    });

    multiplicar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            double numero1, numero2, multiplicar;
            multiplicar = 0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            multiplicar = numero1 * numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText() + "" + "x" + "" + texto2.getText() + "" + "=" + multiplicar);
            texto1.setText(null);
            texto2.setText(null);
            texto1.requestFocus();
        }
    });

    dividir.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            double numero1, numero2, dividir;
            dividir = 0;
            numero1 = Double.parseDouble(texto1.getText());
            numero2 = Double.parseDouble(texto2.getText());
            dividir = numero1 / numero2;
            showup.setVisible(true);
            showup.setText(texto1.getText() + "" + "/" + "" + texto2.getText() + "" + "=" + dividir);
            texto1.setText(null);
            texto2.setText(null);
            texto1.requestFocus();
        }
    });

  }

}

Explanation:

There are many trivial changes in Calc.java

  1. The class is made to extend JDialog instead of JFrame
  2. The constructor is changed so that it takes owner JFrame (Lista) as argument.
  3. There were many local variables of JTextField, JButton, JLabel etc. All of them are instance variables.

Hope this helps to you.

Sanjeev Saha
  • 2,632
  • 1
  • 12
  • 19
  • How do we know that Lista needs to create a Calc object and not the other way around? – Hovercraft Full Of Eels Jun 05 '16 at 14:48
  • If Calc is another GUI and is already being displayed, then creating a new instance will be counter-productive. – Hovercraft Full Of Eels Jun 05 '16 at 14:49
  • The class Calc its a simple calculator and i want to open this calculator in a new windows when i clicked in the JMenuItem called item, but i can't do it. Thanks! – Felipe Squire Jun 05 '16 at 21:50
  • Hi @FelipeSquire Sorry to hear that you are still unable to call your `Calc`. When I saw another is given upvote, I assumed that you found your answer and I stopped following this post. Please make changes as per my answer and see whether it works for you or not. Let me know the result. – Sanjeev Saha Jun 06 '16 at 00:23
  • @FelipeSquire Could you please accept this answer so that readers of your question know which answer is the correct one. Otherwise they don't have a clue. – Sanjeev Saha Jun 15 '16 at 02:27
1

Felipe, this worked for me... It's based on Sanjeev Saha answer...

enter 

import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Calc extends JDialog {

private JLabel rotulo1;
private JLabel rotulo2;
private JLabel showup;
private JTextField texto1;
private JTextField texto2;
private JButton somar;
private JButton subtrair;
private JButton dividir;
private JButton multiplicar;
private JButton exibir;

public Calc(Frame owner) {
super(owner, "Calculadora");
Container tela = getContentPane();
setLayout(null);

rotulo1 = new JLabel("1 numero: ");
rotulo2 = new JLabel("2 numero: ");
showup = new JLabel("");

texto1 = new JTextField(5);
texto2 = new JTextField(5);

somar = new JButton("+");
subtrair = new JButton("-");
dividir = new JButton("/");
multiplicar = new JButton("x");
exibir = new JButton("=");

rotulo1.setBounds(30, 20, 100, 20);
rotulo2.setBounds(30, 60, 100, 20);
texto1.setBounds(100, 20, 200, 20);
texto2.setBounds(100, 60, 200, 20);
showup.setBounds(125, 100, 200, 20);
somar.setBounds(230, 100, 45, 45);// coluna, linha, largura, comprimento
subtrair.setBounds(280, 100, 45, 45);
dividir.setBounds(230, 155, 45, 45);
multiplicar.setBounds(280, 155, 45, 45);
exibir.setBounds(255, 205, 45, 45);

setVisible(true);
setLocationRelativeTo(null);

tela.add(rotulo1);
tela.add(rotulo2);
tela.add(texto1);
tela.add(texto2);
tela.add(showup);
tela.add(exibir);
tela.add(somar);
tela.add(subtrair);
tela.add(dividir);
tela.add(multiplicar);

setSize(350, 300);

somar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        double numero1, numero2, soma;
        soma = 0;
        numero1 = Double.parseDouble(texto1.getText());
        numero2 = Double.parseDouble(texto2.getText());
        soma = numero1 + numero2;
        showup.setVisible(true);
        showup.setText(texto1.getText() + "" + "+" + "" + texto2.getText() + "" + "=" + soma);
        texto1.setText(null);
        texto2.setText(null);
        texto1.requestFocus(); // funcao limpar e focar
    }
});

subtrair.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        double numero1, numero2, subtrair;
        subtrair = 0;
        numero1 = Double.parseDouble(texto1.getText());
        numero2 = Double.parseDouble(texto2.getText());
        subtrair = numero1 - numero2;
        showup.setVisible(true);
        showup.setText(texto1.getText() + "" + "-" + "" + texto2.getText() + "" + "=" + subtrair);
        texto1.setText(null);
        texto2.setText(null);
        texto1.requestFocus();
    }
});

multiplicar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        double numero1, numero2, multiplicar;
        multiplicar = 0;
        numero1 = Double.parseDouble(texto1.getText());
        numero2 = Double.parseDouble(texto2.getText());
        multiplicar = numero1 * numero2;
        showup.setVisible(true);
        showup.setText(texto1.getText() + "" + "x" + "" + texto2.getText() + "" + "=" + multiplicar);
        texto1.setText(null);
        texto2.setText(null);
        texto1.requestFocus();
    }
});

dividir.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        double numero1, numero2, dividir;
        dividir = 0;
        numero1 = Double.parseDouble(texto1.getText());
        numero2 = Double.parseDouble(texto2.getText());
        dividir = numero1 / numero2;
        showup.setVisible(true);
        showup.setText(texto1.getText() + "" + "/" + "" + texto2.getText() + "" + "=" + dividir);
        texto1.setText(null);
        texto2.setText(null);
        texto1.requestFocus();
    }
});

  }

}

and Lista class...

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

import javax.swing.*;
import java.awt.event.*;

public class Lista extends JFrame{
  public Lista(){
    super("Menu");

    // Menu Bar
    JMenuBar barra = new JMenuBar();
    setJMenuBar(barra);

    // Menu
    JMenu opcoes = new JMenu("Options");

    // Menu Item
    JMenuItem item = new JMenuItem("Item 1");

    // actionlistener
    item.addActionListener(
      new ActionListener(){
        public void actionPerformed(ActionEvent e){
          new Calc(Lista.this);
        }
      }
    );

    opcoes.add(item);

    // Adds
    barra.add(opcoes);

    setSize(300, 150);
    setVisible(true);    
  }

  public static void main(String args[]){
    Lista app = new Lista();
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}
wagnermarques
  • 140
  • 1
  • 4