Basic action listener tutorial
Lol i was bored so i want to make a tutorial on actionlisteners.
make these classes
Code:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Example extends JFrame {
private static final long serialVersionUID = 6053976325880914070L;
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
public x() {
super("JMenuBar");
super.setSize(390, 300);
super.setJMenuBar(menubar);
super.setVisible(true);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.populate();
}
void populate() {
menubar.add(file);
file.add(exit);
menubar.setVisible(true);
}
}
Code:
public class Main {
public static void main(String... args) {
new Example();
}
}
Basically, an action listener is what happens when you do something. for example(what i will be showing you), you will hit the exit button, and the action will close the frame. So, what we are gonna do is the following:
in populate add:
Code:
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Make the button close.
}
});
also add these imports:
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
this declared a new ActionListener object, letting it know that we want to do something when we hit the "exit" button.
now to make the frame close.
Code:
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
test it and it should work.