2012-03-05 18 views
14

Tengo una aplicación Java netbeans que debe mostrar un JFrame (clase StartUpWindow extiende JFrame) con algunas opciones cuando se inicia la aplicación, luego el usuario hace clic en un botón y ese JFrame debe ser cerrado y uno nuevo (clase MainWindow) debe ser abierto.aplicación Java swing, cierre una ventana y abra otra cuando se haga clic en el botón

Entonces, ¿cómo hago esto correctamente? Obviamente establecí un controlador de clics en el botón en StartupWindow, pero ¿qué debo poner en este controlador para poder cerrar el StartUpWindow y abrir MainWindow? Parece que el roscado entra en esto también como cada ventana parece tener su propio hilo ... o se enhebrar temas manejados automáticamente por sí mismos JFrames ...

+3

[¿El uso de múltiples JFrames, buenas/malas prácticas?] (Http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes- good-bad-practice-9554657#9554657) y [Eliminar contenedor de nivel superior en tiempo de ejecución] (http://stackoverflow.com/questions/6309407/remove-top-level-container-on-runtime) – mKorbel

Respuesta

22

Aquí se muestra un ejemplo:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 


public class StartupWindow extends JFrame implements ActionListener 
{ 
    private JButton btn; 

    public StartupWindow() 
    { 
     super("Simple GUI"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     btn = new JButton("Open the other JFrame!"); 
     btn.addActionListener(this); 
     btn.setActionCommand("Open"); 
     add(btn); 
     pack(); 

    } 

    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     String cmd = e.getActionCommand(); 

     if(cmd.equals("Open")) 
     { 
      dispose(); 
      new AnotherJFrame(); 
     } 
    } 

    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable(){ 

      @Override 
      public void run() 
      { 
       new StartupWindow().setVisible(true); 
      } 

     }); 
    } 
} 

AnotherJFrame.java

import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class AnotherJFrame extends JFrame 
{ 
    public AnotherJFrame() 
    { 
     super("Another GUI"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     add(new JLabel("Empty JFrame")); 
     pack(); 
     setVisible(true); 
    } 
} 
+0

Gran ejemplo, ¡¡¡Voto ascendente !!! – ron

+0

@ Eng.Fouad cómo está abierto 'StartupWindow' from' AnotherJFrame', creando un objeto de 'StartupWindow' en' AnotherJFrame' no funcionará –

9

Usted puede llamar dispose() en la ventana actual y setVisible(true) en el que usted quiero mostrar

+0

¿Conservaría la variable JFrame en el alcance de clase? ¿o lo haría seleccionable para la recolección de basura una vez que se muestra el segundo JFrame? –

+0

dispose() hará que sea basura coleccionable siempre y cuando no tenga otras referencias a ella. –

9

Este es obviamente el escenario en el que deberías estar usando CardLayout. Aquí, en lugar de abrir dos JFrame, lo único que puede hacer es cambiar los JPanels con CardLayout.

Y el código que se encarga de crear y mostrar su GUI debe estar dentro de SwingUtilities.invokeLater (...); método para que sea Thread Safe. Para obtener más información, debe leer sobre Concurrency in Swing.

Pero si quiere seguir con su enfoque, aquí hay un código de muestra para su ayuda.

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

public class TwoFrames 
{ 
    private JFrame frame1, frame2; 
    private ActionListener action; 
    private JButton showButton, hideButton; 

    public void createAndDisplayGUI() 
    { 
     frame1 = new JFrame("FRAME 1"); 
     frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
     frame1.setLocationByPlatform(true); 

     JPanel contentPane1 = new JPanel(); 
     contentPane1.setBackground(Color.BLUE); 

     showButton = new JButton("OPEN FRAME 2"); 
     hideButton = new JButton("HIDE FRAME 2"); 

     action = new ActionListener() 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       JButton button = (JButton) ae.getSource(); 

       /* 
       * If this button is clicked, we will create a new JFrame, 
       * and hide the previous one. 
       */ 
       if (button == showButton) 
       { 
        frame2 = new JFrame("FRAME 2"); 
        frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame2.setLocationByPlatform(true); 

        JPanel contentPane2 = new JPanel(); 
        contentPane2.setBackground(Color.DARK_GRAY); 

        contentPane2.add(hideButton); 
        frame2.getContentPane().add(contentPane2); 
        frame2.setSize(300, 300); 
        frame2.setVisible(true); 
        frame1.setVisible(false); 
       } 
       /* 
       * Here we will dispose the previous frame, 
       * show the previous JFrame. 
       */ 
       else if (button == hideButton) 
       { 
        frame1.setVisible(true); 
        frame2.setVisible(false); 
        frame2.dispose(); 
       } 
      } 
     }; 

     showButton.addActionListener(action); 
     hideButton.addActionListener(action); 

     contentPane1.add(showButton); 

     frame1.getContentPane().add(contentPane1); 
     frame1.setSize(300, 300); 
     frame1.setVisible(true); 
    } 
    public static void main(String... args) 
    { 
     /* 
     * Here we are Scheduling a JOB for Event Dispatcher 
     * Thread. The code which is responsible for creating 
     * and displaying our GUI or call to the method which 
     * is responsible for creating and displaying your GUI 
     * goes into this SwingUtilities.invokeLater(...) thingy. 
     */ 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new TwoFrames().createAndDisplayGUI(); 
      } 
     }); 
    } 
} 

Y la salida será:

Frame1 y Frame2

+1

Nos volvemos a encontrar ... otro gran ejemplo +1. – ron

+1

@ron: Este [ejemplo] (http://stackoverflow.com/a/9443609/1057230), no permite que un usuario abra más de un 'JFrame', esto también verifica la condición, si un' JFrame' está abierto, luego no para abrir uno nuevo. –

+0

¡Encantador, muchas gracias! – ron

1
 final File open = new File("PicDic.exe"); 
     if (open.exists() == true) { 
      if (Desktop.isDesktopSupported()) { 
       javax.swing.SwingUtilities.invokeLater(new Runnable() { 

        public void run() { 
         try { 
          Desktop.getDesktop().open(open); 
         } catch (IOException ex) { 
          return; 
         } 
        } 
       }); 

       javax.swing.SwingUtilities.invokeLater(new Runnable() { 

        public void run() { 
         //DocumentEditorView.this.getFrame().dispose(); 
         System.exit(0); 
        } 

       }); 
      } else { 
       JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy"); 
      } 
     } else { 
      JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found"); 
     } 

// puede iniciar otra mediante el uso de aplicaciones y puede rajar todo el proyecto en muchas aplicaciones. que trabajará mucho

0

Uso this.dispose para la ventana actual para cerrar y next_window.setVisible(true) para mostrar la siguiente ventana detrás de la propiedad botón ActionPerformed, Ejemplo A continuación se muestra en la foto para su ayuda.

enter image description here

+0

Asegúrese de haber escrito 'this.dispose()' primero que el que está abriendo tu próximo 'JFrame' –

0

de llamadas por debajo método que se acaba después de llamar al método para abrir una nueva ventana, esto cerrará la ventana actual.

private void close(){ 
    WindowEvent windowEventClosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING); 
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowEventClosing); 
} 

También en propiedades de JFrame, asegúrese de defaultCloseOperation se establece como DESHÁGASE.

Cuestiones relacionadas