Monday 24 April 2017

java - Implementing and calling JFrame/ActionListener class from main



I'm trying to get my program to launch a gui that gathers information before the actual programs starts. In main I try to call the JFrame which should then run until the start button is pressed and then the main program should launch. Everything seems to be correct except for the base class of the initializeLauncher. Thanks!



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

import java.awt.event.*;

class InitializeLauncher implements ActionListener {

InitializeLauncher() {
JFrame frame = new JFrame("launcherClient");

Container c = frame.getContentPane();
Dimension d = new Dimension(700,400);
c.setPreferredSize(d);


JButton startButton = new JButton("Start");
JPanel pane = new JPanel();

startButton.addActionListener(this);

pane.add(startButton);
frame.add(pane);
frame.pack();
frame.setLocationRelativeTo(null);

frame.setResizable(false);
frame.setVisible(true);
}

public void buttonClicked(ActionEvent e)
{
ApplicationDeploy displayExample = new ApplicationDeploy();
displayExample.initializeGameClient();
}
}



...and then in main I call this:



InitializeLauncher launcher = new InitializeLauncher();
launcher.InitializeLauncher();

Answer



By making your class abstract, you're fixing the wrong thing. Instead you should give your class the missing method, public void actionPerformed(ActionEvent e) {...}




The basic rule here is, if you state that your class is going to implement an interface, here the ActionListener interface, then the class must implement all of the methods of the interface.



@Override
public void actionPerformed(ActionEvent e) {
// ... your code that should occur when the button is pressed goes here
}


Note that your buttonClicked(...) method will do nothing useful for you. Likely you'll want to get rid of that method and put its code into the actionPerformed method.




As an aside, I often use a JOptionPane for the functionality that you're using a JFrame for.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...