Problem to Close a JFrame from a Button inside a JPanel

0

Good afternoon,

As the title says, my drawback is that I made 2 JPanel that I then added to a JFrame.

The problem is that in a JPanel, I have the button that should close me or leave the JFrame invisible, but when placing an event on the button, it does not close said JFrame.

Try passing the JPanel class to the JFrame, but it did not work. I appreciate any help you can give me.

I have the following JPanel:

Then This Panel:

And both in the JFrame:

What I need is for the final button to leave the Frame invisible, but being in the JPanel, it does not do it.

SOLVED Remove the JPanel button and put it directly on the JFrame.

The handler that implements is:

    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            setVisible(false);
        }
    });
    
asked by Osky 07.11.2017 в 23:51
source

2 answers

-1

SOLVED Remove the JPanel button and put it directly on the JFrame.

Marked in yellow.

    
answered by 12.11.2017 / 14:29
source
0

I understand that you could solve in a certain way, removing the visibility of the JFrame. However, the dispose () method is usually used; if memory does not fail me to close windows within the same application and System.exit (0); to exit the application. I'm going to leave a screen as an example of the use of the dispose () method;

package Vista;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class Ventana_libreria extends JFrame implements ActionListener  {

public JPanel panelsuperior, panelcentral, panelinferior;
public JButton botonatras, botonadelante, botonsalir;
public JTextArea textarealibreria;
public JLabel titulo;
public JScrollPane scroll;



public Ventana_libreria()
{


    panelsuperior= new JPanel();
    panelcentral= new JPanel();
    panelinferior= new JPanel();
        textarealibreria= new JTextArea(33,50);
            botonatras= new JButton(new ImageIcon("../Juego_avion/src/Vista/flechaverdeatras.png"));
            botonadelante= new JButton(new ImageIcon("../Juego_avion/src/Vista/flechaverde.png"));
            botonsalir= new JButton(new ImageIcon("../Juego_avion/src/Vista/eject.png"));
                titulo= new JLabel();
                scroll= new JScrollPane(textarealibreria);  // Acá creo el scroll
                scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);   //acá lo declaro sólo vertical

                this.setTitle("Librería de ayuda y orientación");

                this.setLayout(new BorderLayout());
                    this.add(panelsuperior, BorderLayout.NORTH);
                    panelsuperior.add(titulo);
                    titulo.setText("Datos a tener en cuenta:");

                    this.add(panelcentral, BorderLayout.CENTER);
                //  panelcentral.add(textarealibreria);     // Acá adhiero el JTextArea al centro, no sirve esta linea, se adhiere mediante el scrollpane
                    this.add(scroll, BorderLayout.CENTER);// Acá lo adhiero al lado oeste del borderlayout



                    textarealibreria.setEditable(false);

                    this.add(panelinferior, BorderLayout.SOUTH);
                    //panelinferior.add(botonatras);  //Por ahora van a estar desactivados
                //  panelinferior.add(botonadelante);   //Por ahora van a estar desactivados
                    panelinferior.add(botonsalir);


                    textarealibreria.setText("\nÁrea de soporte, debés tener en cuenta que: \n\n• Como todas las cosas existentes los aviones tienen peso y está ligados a las fuerza de gravedad.\n• Este avión tiene un alcance máximo de 1000 km sin repostar en el aire. \n• Su capacidad de carga entre combustible y armamento nunca puede ser mayor a 3000 kg\n• Para despegar 'sin carga' necesita mínimo unos 2000 metros de pista a velocidad mínima aprox 250 km/h.\n• No es efectivo en los duelos a corta distancia.\n• Carga como máx 6 misiles de media corta distancia AMRAAM.\n• Su techo máximo de vuelo son 30000 feet o 99900 metros.\n• Su tren de aterrizaje es extremadamente sensible al vient y/o golpes.\n• Su maniobrabilidad es buena pero su rango de giro nunca es mayor a 65 grados superando los 350 km/h.\n• Cuenta con medidas electromagnéticas o E.C.M , junto con Chaff y Flares o bengalas.\n• El ECM hoy en día es casi obsoleto, no sirve para missiles modernos a menos que esté a menos de 100 m del objetivo.\n• El rango de efectividad de éxito de un AMRAAM a x<100km y x>=1km es del 99%.\n• El rango de efectividad de un Sidewinder moderno es de x<10km y x>=500m es del 99%.\n• Apartir de los 30000 feet pierde sustentabilidad por la liviandad del aire y/o se congelan sus partes.\n• En algunos casos con la turbina apagada y dependiendo del angulo de caída puede planear largas distancias.\n• La cuenta correspondiente al recorrido planeando es= distancia_recorrida*segundos_hasta_la_pista. depende del grado.\n• Para refueling envuelo se necesitan almenos 300 litros de combustible con un consumo menor a 20litros/seg.\n• Los dos modelos más conocidos son el F-16C y F-16B ,el B con una maniobrabilidad 10º menor al C por la plaza extra.\n• Es absolutamente inefectivo ante operaciones contra buques o cruceros.\n• Es altamente reflectivo ante las ondas del radar y el vuelo bajo no sirve a menos que los radares tengan ángulo de 60º.\n• Apesar de su popularidad y su bajo costo, no a todas las naciones les conviene esta unidad por su poca autonomía.\n• Su competidor directo desde el lado URSS es el mig 29, superándolo sólo en tecnología pero con menos maniobravilidad.\n• Los Sidewinder son guiado por calor a muy corta o corta distancia.\n• Los AMRAAM son guiados por radar a corta-media-larga distancia.\n• El AIM-7 Sparrow es un missil de los años 70, hoy en día se evaden hasta con confeti.\n• El AIM-54 Phoenix sólo lo carga el F-14 por su peso, y es 100% efectivo sólo a distancias mayores a 200km.\n• Para que la turbina encienda por la chispa debe pasar por un tiempo de calentanmiento aprox de 5 a 10 min.\n• El corte del sistema de EPU retorna en el corte anexo del la chispa y el combustible.\n• El alcance máximo de su radar nunca supera los 320 km, ganando claridad mientras se baja la distancia análisis.\n• Su sistema de armas no funciona sin radar.\n• No está diseñados para aterrizar en portaviones ni distancias de pista menores a 3 km.\n• La vlocidad de despegue ideal sin carga es de 250 a 450 km/h.\n• La distancia de aterrizaje nunca puede ser menor a 3 km.\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\n• Este software está inspirado en el legendario simulador de vuelo Falcon 4.0 del año 1998 que hoy en día se sigue actualizando\n• Su secuela es el Falcon BMS el cual es un soft hijo nutrido por la comunidad Falcon BMS.\n• Este software no intenta ser copia de ningun otro y mantiene originalidad en su temática.\n• Este sofware fue diseñado por Axel Berlot, sin Netbeans ni otro gestor gráfico, sólo código puro en Eclipse IDE.");

                this.botonsalir.addActionListener(this);


}

  public void actionPerformed(ActionEvent e)
  {
      Object obj=e.getSource();
      if(obj.equals(botonsalir))
      {
          this.dispose();
      }
  }


}

This screen is only part of a game or application I did a few years ago, note that in this.botonsalir.addActionListener (this); We are saying that we are assigning an action to the button. and below we tell you to close the window if you press the button with the dispose () method, we say this.dispose (); close the JFrame of the current class.

After quite some time using swing, awt, I understood that it has several interesting methods that simplify the existence and that are not absolutely necessary but work well.

Keep in mind that this method closes a JFrame, not the entire program as System.exit (0), and that a similar result can be obtained with the setVisible (true / false) method; however, the dispose () is more suitable for closing a JFrame.

    
answered by 12.11.2017 в 19:30