Tutorial 9:
First remember our imports
import javax.swing.*;
import java.awt.event.*;
the java.awt.event provided us with the power to add actions to buttons items and what not.
Lets call a reference to our class but first lets declare our classname
public class Gui2 implements ActionListener {
public Gui2() {
this method is where were going to add a JButton and JFrame and a JPanel
declare our Stuff
JFrame frame = new JFrame("Gui2");
JButton button = new JButton("Click");
JPanel panel = new JPanel();
Now we need to add an actionlistener to the button like so
button.addActionListener(this);
now add the panel to the frame and the button to the panel.
frame.add(panel);
panel.add(button);
frame.show();
frame.pack();
Now all we do to refrence this is call it in the main method.
public static void main(String[] args) {
Gui2();
}
that tells the main method to execute the method Gui2.
now we need to add a method the listens for actions like so.
public static void actionPerformed(ActionEvent e) {
if(e.getActionCommand.equalsIgnoreCase("Click")) {
System.out.println("Hi");
}
}
Full Code
import javax.swing.*;
import java.awt.event.*;
public class Gui2 implements ActionListener {
public Gui2() {
JFrame frame = new JFrame("Gui2");
JButton button = new JButton("Click");
JPanel panel = new JPanel();
button.addActionListener(this);
frame.add(panel);
panel.add(button);
frame.show();
frame.pack();
}
public static void main(String[] args) {
Gui2();
}
public static void actionPerformed(ActionEvent e) {
if(e.getActionCommand.equalsIgnoreCase("Click")) {
System.out.println("Hi");
}
}
}
If anyone see's any erros just post and ill fix them