0

I have searched many websites and the java documentations to look how I must use a window listener.

This is my problem: I want to open a new frame with a button, (this is successful) and close the previous one. I have seen how to write a window Listener but where do I put it in my code and how can I invoke this in the button handler? (start handler) Can anybody show me how? I have searched it also here and try different things.

I am very inexperienced and still must learn a lot.

Thanks in advance.

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



public class Startvenster extends JFrame {
public static void main(String[] args) {

JFrame frame = new Startvenster();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle("Rekentrainer - Startvenster");
frame.setSize(450, 400);
frame.setLocationRelativeTo(null);
frame.setContentPane( new Startpaneel());
frame.pack();

} 
}


class Startpaneel extends JPanel {

private JLabel welkom_Lbl, naamLeerling_Lbl;
private JTextField naam;
private JButton start;
private Font font;
private JPanel centrumStart, begin;


public Startpaneel() {

setBackground(Color.WHITE);

begin = new JPanel();
begin.setVisible(false);
begin.setLayout(new GridLayout(8, 2));
begin.setBackground(Color.white);

centrumStart = new JPanel();
centrumStart.setBackground(Color.white);
centrumStart.setLayout(new GridLayout(3,1));

Component bovenStrut = Box.createVerticalStrut(200);

font = new Font("Dialog", Font.PLAIN, 14);
//onderdelen van het venster

welkom_Lbl = new JLabel("Vul hieronder je naam in om de rekentrainer te starten. ");
welkom_Lbl.setFont(font);

//invoer leerling
naam = new JTextField(10);
naam.setHorizontalAlignment(JTextField.CENTER);
naam.addActionListener(new StartHandler());

start = new JButton("Start");
start.addActionListener(new StartHandler());
start.setFont(font);
start.setMnemonic(KeyEvent.VK_S);

naamLeerling_Lbl = new JLabel();

centrumStart.add(welkom_Lbl);
centrumStart.add(naam);
centrumStart.add(start);
begin.add(centrumStart);

begin.add(naamLeerling_Lbl);


add(bovenStrut);
add(bovenStrut);
add(begin);
add(centrumStart);

}


class StartHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
try { 

if(e.getSource() == start || e.getSource() == naam) {
if(naam.getText().isEmpty()) {
JOptionPane.showMessageDialog(Startpaneel.this, 
"Vul je naam in alsjeblieft.",
"Fout", JOptionPane.ERROR_MESSAGE);
} else {    

String leerling = naam.getText();
Leerling.setLeerling(leerling);
Keuzevenster kz = new Keuzevenster();
kz.setVisible(true);
kz.setSize(400, 300);
kz.setLocationRelativeTo(null);
kz.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
kz.setTitle("Rekentrainer - Keuze scherm");
kz.setContentPane(new Keuzepaneel());
kz.pack();
setVisible(false);

}
}
} catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(Startpaneel.this, 
"Geen getallen invullen alsjeblieft.",
"Fout", JOptionPane.ERROR_MESSAGE);
} 

}
}
}
Elydasian
  • 2,016
  • 5
  • 23
  • 41
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! 3) Words typed in all lower case are hard to read, like trying to listen to someone who is mumbling. Please use an upper case letter at the start of sentences, for the word I, and proper names like `ArrayList` or Oracle. .. – Andrew Thompson Feb 07 '18 at 08:34
  • .. 4) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. 5) Don't extend components without good reason. E.G. `JFrame` & `JPanel` in this case. – Andrew Thompson Feb 07 '18 at 08:34
  • Thank you for you comment! I've had indenting the code lines and blocks in eclipse but pasted in here and forgot to indenting it. – dirk1980 Feb 07 '18 at 08:47
  • About the extending, this is how I learned it from a Java-book, so I guess its useless. Furthermore I will have a look at my naming. Thank you for pointing this out to me. – dirk1980 Feb 07 '18 at 08:48
  • *"..but pasted in here and forgot to indenting it."* You can [edit] the question at any time. – Andrew Thompson Feb 07 '18 at 08:59
  • Why do you need a window listener, open the new button in the `ActionListener` and close the current in the same place – MadProgrammer Feb 07 '18 at 09:30
  • I am using multiple JFrames because its an assignment in my study. I want to clean up the frames by using a windowListener. I would like to use a button to close the previous frame. The only problem is now: how to make it work. And can you help me please? I am a bit desperate and have got square eyes from looking on the internet – dirk1980 Feb 07 '18 at 09:36

1 Answers1

0

This is how I manage listeners in my code. This example is for two buttons. I follow the Model-View-Controller structure. For the Main:

public class Main {
public static void main(String[] args) {
    //create the model
    Model model = new Model();

    //create the view
    MainView view = new MainView();

    //create the controller
    MainController controller = new MainController();        

    //add controller to view
    view.listener(controller);

    //show the view
    view.setVisible(true);
    }
}

For the view:

//create buttons
private JButton firstButton;
private JButton secondButton;
//...
firstButton = new JButton("first button");
secondButton = new JButton("second button");
//add them where you wish in your view. 

//Then link the controller you added previously on them main to this two buttons:
public void listener(MainController controller) {
    firstButton.addActionListener(controller);
    secondButton.addActionListener(controller);
}

And finally in your controller, execute the code you want for each button:

public class MainController implements ActionListener{


@Override
public void actionPerformed(ActionEvent e) {
    //the following line tells you which button has been pressed
    String pressedButton = e.getActionCommand();
    switch (pressedButton){
        case "first button":
            System.out.println("First button pressed!");
            break;

        case "second button":
            System.out.println("Second button pressed!");
            break;
    }
}

}

afarre
  • 512
  • 6
  • 18