How to call a Jframe from another Jframe with different classes

Asked

Viewed 1,014 times

-1

I’m creating a little game of rock paper and scissors and would like to know what I call a JFrame other’s JFrame, only from different classes. Or maybe I should do it in different methods? I tried to do it here but it was always wrong. I guess I wasn’t getting the call right.

I’ll post the codes below:

Leading:

public class Principal {

private JFrame frame;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Principal window = new Principal();
                window.frame.setVisible(true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public Principal() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setResizable(false);
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel lblPedraPapelOu = new JLabel("Pedra Papel ou Tesoura!");
    lblPedraPapelOu.setFont(new Font("Comic Sans MS", Font.BOLD, 26));

    JLabel label = new JLabel("");
    label.setIcon(new ImageIcon("C:\\Users\\nelio\\workspace\\PedraPapelOuTesoura\\Imagens\\pedra-papel-tesoura-final.png"));

    JButton btnIniciar = new JButton("Iniciar");
    btnIniciar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            //AQUI!

        }
    });
    btnIniciar.setForeground(new Color(0, 204, 0));
    btnIniciar.setFont(new Font("Tahoma", Font.BOLD, 16));

    JButton btnSair = new JButton("Sair");
    btnSair.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });
    btnSair.setFont(new Font("Tahoma", Font.PLAIN, 16));
    GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
    groupLayout.setHorizontalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
                .addGap(69)
                .addComponent(lblPedraPapelOu, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(88))
            .addGroup(groupLayout.createSequentialGroup()
                .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
                    .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
                        .addGap(79)
                        .addComponent(btnIniciar)
                        .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnSair))
                    .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
                        .addGap(61)
                        .addComponent(label)))
                .addContainerGap(73, Short.MAX_VALUE))
    );
    groupLayout.setVerticalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblPedraPapelOu, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(label)
                .addGap(44)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                    .addComponent(btnIniciar)
                    .addComponent(btnSair))
                .addGap(29))
    );
    frame.getContentPane().setLayout(groupLayout);
}
}

The screen I’d like to call:

public class TelaJogo {

JFrame tela;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TelaJogo window = new TelaJogo();
                    window.tela.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TelaJogo() {
        initialize();
    }

    /**
     * Initialize the contents of the tela.
     */
    private void initialize() {
        tela = new JFrame();
        tela.setBounds(100, 100, 328, 298);
        tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton btnPedra = new JButton("Pedra");
        btnPedra.setFont(new Font("Tahoma", Font.BOLD, 16));

        JButton btnPapel = new JButton("Papel");
        btnPapel.setFont(new Font("Tahoma", Font.BOLD, 16));

        JButton btnTesoura = new JButton("Tesoura");
        btnTesoura.setFont(new Font("Tahoma", Font.BOLD, 16));

        JLabel lblFaaSuaEscolha = new JLabel("Fa\u00E7a sua escolha:");
        lblFaaSuaEscolha.setFont(new Font("Tahoma", Font.PLAIN, 16));

        JLabel lblJogador = new JLabel("Jogador");
        lblJogador.setForeground(new Color(0, 128, 0));
        lblJogador.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 18));

        JLabel lblIa = new JLabel("I.A");
        lblIa.setForeground(new Color(255, 0, 0));
        lblIa.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 28));
        GroupLayout groupLayout = new GroupLayout(tela.getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(134)
                            .addComponent(lblIa, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(90)
                            .addComponent(lblFaaSuaEscolha))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(btnPedra)
                            .addGap(9)
                            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                .addComponent(lblJogador)
                                .addGroup(groupLayout.createSequentialGroup()
                                    .addComponent(btnPapel)
                                    .addPreferredGap(ComponentPlacement.RELATED)
                                    .addComponent(btnTesoura, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)))))
                    .addContainerGap(10, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.TRAILING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(lblIa, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED, 118, Short.MAX_VALUE)
                    .addComponent(lblFaaSuaEscolha)
                    .addGap(18)
                    .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnPedra)
                        .addComponent(btnPapel)
                        .addComponent(btnTesoura))
                    .addPreferredGap(ComponentPlacement.UNRELATED)
                    .addComponent(lblJogador)
                    .addGap(10))
        );
        tela.getContentPane().setLayout(groupLayout);
    }

}

(All packages included, I only took to post here to make it easier to see)

I put a //AQUI in the main to find the actionperformed that I’m working.

  • You could post the stack trace?

  • Why not use Jdialog instead of multiple frames?

1 answer

1

One of the solutions would be you use JDialog, whose purpose is precisely this, when more than one window is needed. The difference is that it will be dependent on your main frame(even if it is a window too), and has the option to be modal.

Another thing, usually when working with classes that represent screens, it is more recommended that you extend JFrame(or another frame class), so you take advantage of functionalities already written in the class, without having to keep creating a method to encapsulate your variable that represents the JFrame.

I modified your class a little bit, and look how it turned out, just apply the logic of your game.

Main Class:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

public class Principal{

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Principal window = new Principal();
                    window.frame.setVisible(true);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Principal() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setResizable(false);
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lblPedraPapelOu = new JLabel("Pedra Papel ou Tesoura!");
        lblPedraPapelOu.setFont(new Font("Comic Sans MS", Font.BOLD, 26));

        JLabel label = new JLabel("");
        label.setIcon(new ImageIcon("C:\\Users\\nelio\\workspace\\PedraPapelOuTesoura\\Imagens\\pedra-papel-tesoura-final.png"));

        JButton btnIniciar = new JButton("Iniciar");
        btnIniciar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //a chamada da tela modal  
                TelaJogo telaJogo = new TelaJogo(frame, true);
                telaJogo.setVisible(true);
            }
        });
        btnIniciar.setForeground(new Color(0, 204, 0));
        btnIniciar.setFont(new Font("Tahoma", Font.BOLD, 16));

        JButton btnSair = new JButton("Sair");
        btnSair.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        btnSair.setFont(new Font("Tahoma", Font.PLAIN, 16));
        GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
                        .addGap(69)
                        .addComponent(lblPedraPapelOu, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(88))
                .addGroup(groupLayout.createSequentialGroup()
                        .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
                                .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
                                        .addGap(79)
                                        .addComponent(btnIniciar)
                                        .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(btnSair))
                                .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
                                        .addGap(61)
                                        .addComponent(label)))
                        .addContainerGap(73, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblPedraPapelOu, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(label)
                        .addGap(44)
                        .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                .addComponent(btnIniciar)
                                .addComponent(btnSair))
                        .addGap(29))
        );
        frame.getContentPane().setLayout(groupLayout);
    }
}

Telajogo class:

import java.awt.*;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

public class TelaJogo extends JDialog{

    /**
     * Create the application.
     */
    public TelaJogo(Frame owner, boolean isModal) {
        super(owner, isModal);
        initialize();
    }

    /**
     * Initialize the contents of the tela.
     */
    private void initialize() {

        this.setBounds(100, 100, 328, 298);
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        JButton btnPedra = new JButton("Pedra");
        btnPedra.setFont(new Font("Tahoma", Font.BOLD, 16));

        JButton btnPapel = new JButton("Papel");
        btnPapel.setFont(new Font("Tahoma", Font.BOLD, 16));

        JButton btnTesoura = new JButton("Tesoura");
        btnTesoura.setFont(new Font("Tahoma", Font.BOLD, 16));

        JLabel lblFaaSuaEscolha = new JLabel("Fa\u00E7a sua escolha:");
        lblFaaSuaEscolha.setFont(new Font("Tahoma", Font.PLAIN, 16));

        JLabel lblJogador = new JLabel("Jogador");
        lblJogador.setForeground(new Color(0, 128, 0));
        lblJogador.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 18));

        JLabel lblIa = new JLabel("I.A");
        lblIa.setForeground(new Color(255, 0, 0));
        lblIa.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 28));
        GroupLayout groupLayout = new GroupLayout(this.getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(134)
                            .addComponent(lblIa, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(90)
                            .addComponent(lblFaaSuaEscolha))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(btnPedra)
                            .addGap(9)
                            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                .addComponent(lblJogador)
                                .addGroup(groupLayout.createSequentialGroup()
                                    .addComponent(btnPapel)
                                    .addPreferredGap(ComponentPlacement.RELATED)
                                    .addComponent(btnTesoura, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)))))
                    .addContainerGap(10, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.TRAILING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(lblIa, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED, 118, Short.MAX_VALUE)
                    .addComponent(lblFaaSuaEscolha)
                    .addGap(18)
                    .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnPedra)
                        .addComponent(btnPapel)
                        .addComponent(btnTesoura))
                    .addPreferredGap(ComponentPlacement.UNRELATED)
                    .addComponent(lblJogador)
                    .addGap(10))
        );
        this.getContentPane().setLayout(groupLayout);
    }

}

That way, when you click on btnIniciar of the main class, your game screen will be displayed. If you want the main screen to be hidden when the game screen is open, just modify inside the actionPerformed:

@Override
            public void actionPerformed(ActionEvent e) {
                //a chamada da tela modal  
                frame.setVisible(false);
                TelaJogo telaJogo = new TelaJogo(frame, true);
                telaJogo.setVisible(true);
                frame.setVisible(true);
            }

The main class can be improved, but not to change your code too much, I just adapted the class TelaJogo.

Browser other questions tagged

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