Ir ao conteúdo
  • Cadastre-se

Java Como fechar o JFrame atual após clicar num botão que abre outro JFrame


Posts recomendados

Olá a todos,

Estou a programar algo que abre um JFrame inicial contendo um painel. Nesse painel eu programei alguma animação que opera em alguns botões. Assim que eu clico num botão, abre um segundo JFrame que contém componentes swing e que vão servir para efeitos de formulário.

O que pretendo é que quando clico nesse botão, o JFrame inicial feche e apenas o segundo JFrame (do formulário) fique visivel.

Vou tentar disponibilizar a estrutura base principal do código que tenho, para não ser muito pesado colocar tudo aqui:

 

public class DBLauncher extends JFrame
{
    //Constructor
    public DBLauncher() throws IOException
    {
        super("Database Launcher v1.0");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(706, 768);
        setLocation(350, 50);
        setResizable(false); 

        DBPanel panel = new DBPanel();

        Container container = getContentPane(); 
        container.setLayout(new BorderLayout()); //Use BorderLayout
        container.add(panel, BorderLayout.CENTER); //Insert e center panel on BorderLayout
    }

    private class DBPanel extends JPanel implements MouseListener, MouseMotionListener
    {
        //Constants...
        //Variables...

        //Constructor
        private DBPanel() throws IOException
        {
            //Panel constants...
            //Panel variables...
            ...
            ...

            this.setOpaque(false);
            this.setFocusable(true);
            this.addMouseListener(this);
            this.addMouseMotionListener(this);

            Thread thread = new Thread(() -> animate());

            thread.start();
        }

        public void delay(int milliseconds)
        {
            try
            {
                Thread.sleep(milliseconds);
            } 
            catch (InterruptedException e)
            {
            }
        } 

        @Override
        protected void paintComponent(Graphics g) 
        {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g;

            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(100, 100, 100, 230)); //Define panel's transparent background using Color(r, g, b, a) where the "a" value = alpha channel
            g2.fillRect(0, 0, getWidth(), getHeight());

            for (CustomShapeButton mainShapeButton : shapeButtons)
            {
                mainShapeButton.paintComponent(g2);
            }

            for (CustomShapeButton mainShapeWireFrame : shapeWireFrames)
            {
                mainShapeWireFrame.paintComponent(g2);
            }
        }

        @Override
        public void mouseClicked(MouseEvent me) 
        {
             for (int i = 0; i < shapeButtons.size(); i++)
             {
                Shape shape = shapeButtons.get(i);     

                if (shape.contains(me.getPoint())) 
                {
                    switch (i) 
                    {
                        case 0:
                        ...
                        ...
                        ...

                        case 11:
                        {
                            musicButtonPressed = false;
                            tvButtonPressed = false;
                            gamesButtonPressed = true;
                            booksButtonPressed = false;
                            techButtonPressed = false;

                            try 
                            {   
                                CardInsert ci = new CardInsert();

                                ci.setVisible(true);

                                //É aqui que estou a criar a nova instância do segundo JFrame que aparece no ecrã (formulário).
                                //É também aqui que deveria fechar a instância do JFrame inicial onde estão os botões, certo? Não estou conseguindo aceder à instância aqui para fazer dispose() ou setVisible(false), por exemplo.
                            } 
                            catch (InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException | ClassNotFoundException ex) 
                            {
                                Logger.getLogger(DBPanel.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            System.out.println("Clicked on shape number " + i + " that represents the cards button!");

                            break;    
                        }
                    }
                }
            }
        }

        public synchronized void animate() 
        {       
            while (true)
            {   
                if (musicButtonPressed == true)
                {
                    animateShapeButtonMusic(); 
                    ...
                    ...
                    delay(35);
                    repaint();
                }   
            }
        }

        //Animate methods
        ...
        ...

        //Método main
        public static void main(String args[]) throws IOException 
        {   
            //Aqui estou a criar uma instância da classe inicial DBLauncher (JFrame inicial)
            DBLauncher dbl = new DBLauncher();

            //Aqui digo que essa instância tem que estar visivel, por defeito, sempre que executo o programa pela primeira vez
            dbl.setVisible(true);   
        }
    }
}

Já tentei instanciar objetos não estáticos dentro do método main, mas também já estava à espera que desse o erro comum "Cannot reference static methods from non-static....".

Como posso resolver esta simples questão de fechar o JFrame inicial e mostrar outro, após clicar num botão dele? Como devem imaginar, no segundo JFrame vou querer fazer o mesmo: fechar ele próprio quando clicar no botão Menu Principal e voltar a abrir o JFrame inicial...

 

Se calhar estou a complicar. Será que posso apenas "limpar" (ou substituir) o painel do JFrame inicial assim que clico no botão, preenchendo esse painel com os objetos swing que estão

no segundo JFrame?

 

Obrigado a todos desde já.

 

Joaquim Amorim

Link para o comentário
Compartilhar em outros sites

Segue um exemplo funcional:

Classe secundária

import javax.swing.JFrame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Formulario extends JFrame {
    private final JFrame parent;

    public Formulario(JFrame parent) {
        this.parent = parent;
        configure();
    }

    private void configure() {
        this.setTitle("Formulario");
        this.setSize(250, 150);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                parent.setVisible(true);
            }
        });

        parent.setVisible(false);
    }
}

Classe principal

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Programa extends JFrame {

    public Programa() {
        configure();
    }

    public static void main(String[] args) {
        Programa programa = new Programa();
    }

    private void configure() {
        JButton button = new JButton("Abrir formulario");
        button.addActionListener(e -> {
            Formulario formulario = new Formulario(this);
        });

        this.add(button);
        this.setTitle("Programa");
        this.setSize(500, 300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}
Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...