addActionListener not working - java

I followed a tutorial on how to do this - Here's the code I used:
package soundboard;
import javax.swing.*;
import java.awt.event.*;
public class Soundboard {
JButton Button1;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
Button1 = new JButton("1");
Button1.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(Button1);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent event){
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}
The code seems to not be working. Could anyone explain why?
The JPanel is used as a background. The problem is in Button1.addActionListener(this); , as it says that "this" is not convertible to ActionListener or something like so.

If you want to add your class as an Onclicklistener:
Button1.addActionListener(this);
then your class must implement the appropriate interface ActionListener like this:
public class Soundboard implements ActionListener{
//...
#Override
public void actionPerformed(ActionEvent e){
//...
}
}
EDIT
If you have multiple buttons, that need separated implementation, you could f.e. use anonymous classes:
mybutton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//does something, that probably interests only mybutton
//declare mybutton as **final** if you must use it
}
});

You need to implement the ActionListener interface if you want to override the actionPerformed method:
public class Soundboard implements ActionListener {

You can only add ActionListeners to a Component with addActionListener().
Your class has to implement ActionListener e.g.
public class Soundboard implements ActionListener {

I got it working. Here's how I implemented it, the other buttons don't do a thing quite yet.
All the code is in a class called Soundboard, which implements ActionListener, while javax.swing* and
java.awt.event* are also imported.
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int times;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
loadButton.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent event){
times += 1;
System.out.println("Test successful - this was the #"
+ times + " press");
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}

Related

Composition over Inheritance

i saw an example of ActionListener use in code by implementing ActionListener.
but here i wanna use functionality of ActionListener by using Ref.Var. of ActionListener.
JButton createButton(){
ActionListener al;
JButton button = new JButton();
button.setBounds(130, 100, 100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
frame.add(button);
return button;
}
look at ActionListener reference here . how to use this ref.var on button to listen event on button
JButton createButton(){
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
// run code;
}
};
JButton button = new JButton();
button.setBounds(130, 100, 100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.addActionListener(al);
frame.add(button);
return button;
}
OR
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//run code;
}
} );
It's basically exactly the same as having the containing class implement ActionListener: you provide an implementation, and you configure your button to listen to it.

Why launching does it random?

When i run this program sometimes shows me all buttons, but sometimes only 2 or 3 or 4 or 5 or even just 1.. why is that??
I really do not get it. There should always be 6 buttons, but it doesnt show them. Is there any logical reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class testnet
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Knjigarna");
frame.setVisible(true);
frame.setSize(800,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("Prikazi vse");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("Prikazi knjigo");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Dodaj knjigo");
panel.add(button3);
button3.addActionListener (new Action3());
JButton button4 = new JButton("Brisi knjigo");
panel.add(button4);
button4.addActionListener (new Action4());
JButton button5 = new JButton("Uredi knjigo");
panel.add(button5);
button5.addActionListener (new Action5());
JButton button6 = new JButton("Izhod");
panel.add(button6);
button6.addActionListener (new Action6());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("Pikaz vseh knjig");
frame2.setVisible(true);
frame2.setSize(500,800);
JLabel label = new JLabel("Seznam vseh knjig:");
JPanel panel = new JPanel();
JTextField text1=new JTextField("Naslov: ");
JTextField text2=new JTextField("Avtor: ");
frame2.add(panel);
panel.add(label);
panel.add(text1);
panel.add(text2);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("Prikaz knjige");
frame3.setVisible(true);
frame3.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige:");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Dodajanje knjige");
frame4.setVisible(true);
frame4.setSize(600,300);
JLabel label = new JLabel("Vpisi podtke o knjigi");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
static class Action4 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame5 = new JFrame("Brisanje knjige");
frame5.setVisible(true);
frame5.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis brisati");
JPanel panel = new JPanel();
frame5.add(panel);
panel.add(label);
}
}
static class Action5 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame6 = new JFrame("Urejanje knjige");
frame6.setVisible(true);
frame6.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis urejati");
JPanel panel = new JPanel();
frame6.add(panel);
panel.add(label);
}
}
static class Action6 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
try something with layout. JFrame and or remove managed by inside with a content pane. content pane default layout is BorderLayout. so you need to try border layout stuff.
or you can try this code in you main method
frame.setLayout(new FlowLayout());
this will add component by one by one.
for more about layout you can get in here
This is just a fix and not really an explanation of why the problem is occurring.
Call frame.revalidate() after adding all the buttons.
From the Java Docs,
public Component add(Component comp)
This method
changes layout-related information, and therefore, invalidates the
component hierarchy. If the container has already been displayed, the
hierarchy must be validated thereafter in order to display the added
component.

Setting functions to individual buttons

I have a soundboard program I am designing for school. I'm actually permitted to write whatever program that I want. I have a code written for it, as shown here:
package soundboard;
import javax.swing.*;
import java.awt.event.*;
public class Soundboard implements ActionListener{
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int load;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
loadButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
clearButton.addActionListener(this);
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button1.addActionListener(this);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button2.addActionListener(this);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button3.addActionListener(this);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
Button4.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}
In this example, every single button does the exact same thing. How, using this base code, ca I set it so the buttons do their own individual thing? I plan on designing it so hitting the "load" button and then a number-button loads a sound to that said button. Hitting a number-button without hitting load first plays the previously designated sound. Hitting "clear" unloads all buttons.
Instead of
ButtonX.addActionListener(this);
write
ButtonX.addActionListener(e -> {
//do stuff here
});
The -> signifies that this is a lambda expression, which basically creates an anonymous class from a functional interface and passes it as an argument. For more on lambda expressions, you can read my guide here, or the official (but long) tutorial here.
After you make all the lambda expressions, you can remove the
#Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
and
implements ActionListener
from your class.
You need to attach different action performed to seperate button an e.g. on how to do it is below for load and clear button
import javax.swing.*;
import java.awt.event.*;
public class Soundboard implements ActionListener{
JButton loadButton;
JButton clearButton;
JButton Button1;
JButton Button2;
JButton Button3;
JButton Button4;
JPanel mainsPanel;
int load;
public void windowCreate() {
JFrame frame = new JFrame();
mainsPanel = new JPanel();
loadButton = new JButton("Load...");
loadButton.setSize(80, 30);
loadButton.setLocation(4, 4);
loadButton.addActionListener(e -> System.out.println("load action"));
clearButton = new JButton("Clear");
clearButton.setSize(80, 30);
clearButton.setLocation(92, 4);
clearButton.addActionListener(e -> System.out.println("Clear action"));
Button1 = new JButton("1");
Button1.setSize(80, 80);
Button1.setLocation(4, 45);
Button1.addActionListener(this);
Button2 = new JButton("2");
Button2.setSize(80, 80);
Button2.setLocation(92, 45);
Button2.addActionListener(this);
Button3 = new JButton("3");
Button3.setSize(80, 80);
Button3.setLocation(4, 133);
Button3.addActionListener(this);
Button4 = new JButton("4");
Button4.setSize(80, 80);
Button4.setLocation(92, 133);
Button4.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(loadButton);
frame.add(clearButton);
frame.add(Button1);
frame.add(Button2);
frame.add(Button3);
frame.add(Button4);
frame.add(mainsPanel);
frame.setSize(183,245);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent event){
load += 1;
System.out.println(load);
}
public static void main(String[] args){
Soundboard window = new Soundboard();
window.windowCreate();
}
}

JButton - How to connect?

I found this code online and modified it and it stopped working. I'm thinking it has something to do with when I added the Jpanel but what I am doing works best with a JPanel. How do I make it that the events in the action performed if statements work?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class GUI extends JFrame implements ActionListener {
static JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1));
public GUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setSize(100, 100);
//setLocation(100, 100);
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(this);
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(this);
panel.add(button2);
//Button 3
JButton button3 = new JButton("3");
button3.addActionListener(this);
panel.add(button3);
//Button 2
JButton button4 = new JButton("4");
button4.addActionListener(this);
panel.add(button4);
//Button 2
JButton button5 = new JButton("5");
button5.addActionListener(this);
panel.add(button5);
//Button 2
JButton button6 = new JButton("6");
button6.addActionListener(this);
panel.add(button6);
//Button 2
JButton button7 = new JButton("7");
button7.addActionListener(this);
panel.add(button7);
//Button 2
JButton button8 = new JButton("8");
button8.addActionListener(this);
panel.add(button8);
//Button 2
JButton button9 = new JButton("9");
button9.addActionListener(this);
panel.add(button9);
panel.setVisible(true);
}
public static void main(String[] args) {
new GUI();
JFrame f = new JFrame("Calc");
f.setContentPane(panel);
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
ArrayList numbers = new ArrayList();
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("button1")) {
numbers.add(2);
System.out.println("2");
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}
You need to change the part actionPerformed as:
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
myMethod();
numbers.add(1);
System.out.println("1");
}
if (command.equals("2")) {
numbers.add(2);
System.out.println("2");
}
}
Here, when a button is clicked, your e.getActionCommand() will give the constructor string. i.e. "1", "2" ,"3" and so on
reference
I put comments in code, but the first thing you should do is to read official tutorials. How to use Buttons
public class GUI /*extends JFrame implements ActionListener*/ {
//don't extend JFrame is you don't have too neither implement ActionListener in top-container classes that breaks single responsability principle
private JPanel panel = new JPanel(new GridLayout(5, 5, 1, 1)); // why static??
public JPanel getPanel(){
return panel;
}
public GUI() {
//i use anonymous classes for this, then you don't have to use if-else
//Button 1
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
myMethod();
numbers.add(1);
System.out.println("1");
}
});
panel.add(button1);
//Button 2
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//put here logic for button2
}
});
panel.add(button2);
//and goo on with other buttons
//panel.setVisible(true); you don't need to call this!!
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI gui = new GUI();
frame.add(gui.getPanel());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private List<Integer> numbers = new ArrayList<>();//use generics!
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
System.out.println("Hey");
}
}

How can I implement ActionListener with a non abstract class? Java

I've just recently started learning how to use swing, and have been following a tutorial I found online. I've basically followed the tutorial "word for word" but I get the error:
ScoreBoard is not abstract and does not override abstract method
actionPerformed(ActionEvent) in ActionListener
So my question is, how can I implement ActionListener into my class (ScoreBoard) if the class is not abstract?
Here is the entire code: (Because I have no idea where the problem could be)
package scoreboard;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ScoreBoard implements ActionListener{
//Class Variables
int redScore = 0;
int blueScore = 0;
//Class Objects
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel, redLabelT, blueLabelT;
JButton redButton, blueButton, resetButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createFrame();
}
});
}//End Method
public static void createFrame(){
JFrame frame = new JFrame("ScoreBoard");
JFrame.setDefaultLookAndFeelDecorated(true);
ScoreBoard panel = new ScoreBoard();
frame.setContentPane(panel.contentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(250, 190);
frame.setVisible(true);
}//End Method
public JPanel contentPane(){
JPanel basePanel = new JPanel();
basePanel.setLayout(null);
basePanel.setBackground(Color.black);
//Title
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setOpaque(false);
titlePanel.setLocation(10, 0);
titlePanel.setSize(250, 30);
basePanel.add(titlePanel);
redLabelT = new JLabel("Red Team");
redLabelT.setLocation(0, 0);
redLabelT.setSize(100, 30);
redLabelT.setForeground(Color.red);
redLabelT.setHorizontalAlignment(0);
titlePanel.add(redLabelT);
blueLabelT = new JLabel("Blue Team");
blueLabelT.setLocation(120, 0);
blueLabelT.setSize(100, 30);
blueLabelT.setForeground(Color.blue);
blueLabelT.setHorizontalAlignment(0);
titlePanel.add(blueLabelT);
//Score
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setOpaque(false);
scorePanel.setLocation(10, 40);
scorePanel.setSize(250, 30);
basePanel.add(scorePanel);
redLabel = new JLabel("" + redScore);
redLabel.setLocation(0, 0);
redLabel.setSize(100, 30);
redLabel.setForeground(Color.white);
redLabel.setHorizontalAlignment(0);
scorePanel.add(redLabel);
blueLabel = new JLabel("" + blueScore);
blueLabel.setLocation(120, 0);
blueLabel.setSize(100, 30);
blueLabel.setForeground(Color.white);
blueLabel.setHorizontalAlignment(0);
scorePanel.add(blueLabel);
//Buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setOpaque(false);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(250, 70);
basePanel.add(buttonPanel);
redButton = new JButton("Red Score");
redButton.setLocation(0, 0);
redButton.setSize(100, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score");
blueButton.setLocation(120, 0);
blueButton.setSize(100, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
resetButton = new JButton("Reset");
resetButton.setLocation(0, 40);
resetButton.setSize(220, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
return basePanel;
}//End Method
public void actions(ActionEvent e){
if(e.getSource() == redButton){
redScore ++;
redLabel.setText("" + redScore);
}else if(e.getSource() == blueButton){
blueScore++;
blueLabel.setText("" + blueScore);
}else if(e.getSource() == resetButton){
redScore = 0;
blueScore = 0;
redLabel.setText("" + redScore);
blueLabel.setText("" + blueScore);
}
}//End Method
}//End Class
Also if you can explain what an Abstract class is, that'd help too, but really I just need to know how to get JButtons working for now...
Thanks!
The compiler is complaining because your class is not abstract but it does not implement one or more methods that it is declared to implement (specifically the method actionPerformed of ActionListener). I think you simply need to rename your actions method:
public void actions(ActionEvent e){. . .
public void actionPerformed(ActionEvent e){. . .
Put this method into your ScoreBoard class-
#Override
public void actionPerformed(ActionEvent ae) {
// do something
}
You can also add listener in this way, if you don't want ScoreBoard class to implement ActionListener-
redButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
// do something
}
};
If you want to share the listener, create its instance and add it to all the buttons.
To learn about abstract classes, read this http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
you need to check whether all abstract methods of ActionListener are implemented.
you are missing defination of void actionPerformed(ActionEvent e)

Categories