my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Events1 extends JFrame {
private JLabel label;
private JButton button;
public Events1() {
setLayout(new FlowLayout());
label = new JLabel("");
button = new JButton("Click for text");
add(button);
add(label);
event e = new event();
button.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerfomed(ActionEvent e) {
label.setText("See motherfucker it does do stuff");
}
}
public static void main(String[] args) {
Events1 window = new Events1();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 500); //.pack();
window.setVisible(true);
window.setTitle("Attempt 2");
}
}
Basically I'm new to GUI's and get the error message when I try to compile the above code:
Events1.java:25: error: Events1.event is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
public class event implements ActionListener {
^
1 error
I basically made this code based on the information on the Oracle Docs and and pretty confused of why this doesn't work/how to fix it.
Any help is greatly appreciated thanks.
You have a typo in overriden method
public void actionPerformed(ActionEvent e)
That's why you should use #Override annotation for overriden methods and IDE support for this kind of operations.
Related
I was trying to change the text "Java" to "Love Java" by using MouseAdapter. The text "Java" comes out when mouseEntered and "Love Java" comes out when mouseExited. So I created class MyMouse extends MouseAdapter and trying to use the methods.
But there is the error message "The method getSource() is undefined for the type MouseEvent". When I searched it, this code is nothing wrong with it but I don't know why I'm getting this error message, and also of course the result is not working.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEvent extends JFrame{
MouseEvent(){
setTitle("Practicing mouse event");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lb = new JLabel("Java");
MyMouse mym = new MyMouse();
lb.addMouseListener(mym);
lb.setSize(300,100);
add(lb);
setSize(400,200);
setVisible(true);
}
public static void main(String[] args) {
new MouseEvent();
}
}
class MyMouse extends MouseAdapter{
public void mouseEntered(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Love Java");
}
public void mouseExited(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Java");
}
}
The MouseEvent object e you are using inside public void mouseEntered(MouseEvent e) or public void mouseExited(MouseEvent e) should be from java.awt.event.MouseEvent.
But, as you have named your main class also as MouseEvent, in that case the MouseEvent object e inside mouseEntered() and mouseExited() methods are actually the object of your main class. That's why it was searching for getSource() method in your main class and failed.
Please change your main class name to something other than MouseEvent. For example:
public class MyMouseEvent extends JFrame {
MyMouseEvent() {
...
...
public static void main(String[] args) {
new MyMouseEvent();
...
The problem can be solved through these changes to the code:
Rename the main class of the program so that its name does not conflict with that of the class (java.awt.event.MouseEvent) imported from Java library.
Add #Override annotations to mouseEntered and mouseExited methods to avoid compiler warnings
Call setVisible(true) on the frame to display after instantiation
Here is the working example with the above mentioned changes:
// File name: Demo.java
// This name was chosen to avoid conflict with java.awt.event.MouseEvent
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyMouse extends MouseAdapter{
// Add #Override annotation to overridden methods
#Override
public void mouseEntered(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Love Java");
}
// Add #Override annotation to overridden methods
#Override
public void mouseExited(MouseEvent e) {
JLabel lb = (JLabel)e.getSource();
lb.setText("Java");
}
}
public class Demo extends JFrame{
Demo() {
setTitle("Practicing mouse event");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lb = new JLabel("Java");
MyMouse mym = new MyMouse();
lb.addMouseListener(mym);
lb.setSize(300,100);
add(lb);
setSize(400,200);
}
public static void main(String[] args) {
Demo demo = new Demo();
// Display the frame
demo.setVisible(true);
}
}
Output:
> javac Demo.java
> java Demo
I had a problem and found a solution, but I can't understand why this following code is not working.
What I want to do is, that the tab is switching when a button gets pressed in the "Administration.class".
I got a JTabbedPane which is added in the "Main.class". It is declared as a private variable.
private JTabbedPane JPT;
then I have a simple method, which shall change the tab, when called:
public void SetPane() {
JTP.setSelectedIndex(2);
}
Then I am creating a object of the Main.class in the Administration.class and calling this method, when the button is pressed:
btnRework.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main m = new Main();
m.SetPane();
}
});
But this is not working. Nothing happens, when the button gets clicked, I even get not error.
This works:
Main.class
public static JTabbedPane JTP;
Administration.class
btnRework.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.JTP.setSelectedIndex(2);
}
});
Why example first is not working, and maybe you guys have a link, where I could have a look to a content which is describing this problem. If you just wanna handle a variable and their methods, what is the better way?
Thanks in advance!
Main.class:
public class Main extends JDialog {
private static final long serialVersionUID = 1L;
private Home home = new Home();
private Insertation insertation = new Insertation();
private Edit edit = new Edit();
private Administration administration = new Administration();
private Addition addition = new Addition();
public static JTabbedPane JTP;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Main dialog = new Main();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Main() {
super(null, java.awt.Dialog.ModalityType.TOOLKIT_MODAL);
setResizable(false);
setSize(1030, 720);
getContentPane().setLayout(new BorderLayout());
setTitle("Ebay Manager");
JTP = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
JTP.addTab("Home", home);
JTP.addTab("Inserat", insertation);
JTP.addTab("Bearbeitung", edit);
JTP.addTab("Verwaltung", administration);
JTP.addTab("Zusatz", addition);
getContentPane().add(JTP);
}
}
Administration.class:
public class Administration extends JPanel {
private static final long serialVersionUID = 1L;
private JButton btnRework;
private Main main;
/**
* Create the panel.
*/
public Administration() {
setLayout(null);
setSize(1000, 650);
setDoubleBuffered(true);
btnRework = new JButton("Bearbeiten");
btnRework.setBounds(42, 571, 116, 32);
add(btnRework);
btnRework.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
main.SetPane();
}
});
}
}
You are switching panes in a new undrawn frame that you create and throw away inside your action listener. You need to switch panes in the frame that you have (presumably) packed and drawn in your application.
So instead of
Main m = new Main();
m.SetPane();
you need
myMainFrame.SetPane();
Exactly how you create and remember myMainFrame is beyond the scope of this answer (unless you add more code to your question).
Main m = new Main();
m.SetPane();
Here, you are creating an instance of Main but you are not adding to it anywhere.
Edit:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Administrator extends JFrame {
private Main main;
public Administrator() {
main = new Main();
add(main);
JButton button = new JButton("Set");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
main.setPane();
}
});
add(button, BorderLayout.SOUTH);
}
public static void main(String[] args) {
Administrator adminFrame = new Administrator();
adminFrame.setSize(400, 400);
adminFrame.setVisible(true);
}
}
class Main extends JPanel {
private JTabbedPane jtp;
public Main() {
super(new BorderLayout());
jtp = new JTabbedPane();
jtp.add("tab1", new JLabel("Content1"));
jtp.add("tab2", new JLabel("Content2"));
add(jtp);
}
public void setPane() {
jtp.setSelectedIndex(1);
}
}
I found my own solution because of the answer of rdonuk. Since I can't make another instance of the Main.class I set the JTabbedPane as variable in the Administration.class when creating the Main.class. Just a easy setter method. Thanks for all answers!
I have been coding for a card game and cannot get my method to wait for a button to be pressed.
The general code goes like this. When I run the code, doTask() has a segment where it needs to wait for a button to be pressed. However, the method does not wait for the button and just loops through.
I am currently thinking to have a while loop with a boolean (buttonIsPressed) which will be triggered true in actionPerformed(e). However, is there a simpler way to do this?
Any help would be appreciated.
Thank you.
public class Test {
public Test()
{
// all vars instantiated
while (!(taskLeft==0))
{
doTask();
taskLeft--;
}
}
private class Handler implements ActionListener
{
public void actionPerformed(ActionEvent arg0) {
// update information in doTask()
}
}
}
Yours is a classic XY Problem where you ask how to solve a specific code problem when the best solution is to use a completely different approach. You're thinking of how do I code this event-driven GUI program to work as a linear console program, and that's not how you should approach this. Instead look at changing object state and basing response of the object to events based on its state.
So get rid of the while loop, and instead do your task when the button is pushed based on the state of the GUI. The details of any solution will depend on the details of your problem, something you may wish to share with us.
So for instance, here taskLeft represents a "state" of the TaskEx object, and your Handler's response will depend on the state of this variable.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TaskEx extends JPanel {
private int taskLeft = 10;
public void doTask() {
//
}
private class Handler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (taskLeft > 0) {
doTask();
taskLeft--;
}
}
}
}
An actually functioning example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class TaskEx extends JPanel {
private int taskLeft = 10;
private JLabel taskCountLabel = new JLabel(String.valueOf(taskLeft));
public TaskEx() {
JPanel northPanel = new JPanel();
northPanel.add(new JLabel("Tasks Left:"));
northPanel.add(taskCountLabel);
JPanel centerPanel = new JPanel();
centerPanel.add(new JButton(new Handler("Push Me")));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
public void doTask() {
taskCountLabel.setText(String.valueOf(taskLeft));
}
private static void createAndShowGui() {
TaskEx mainPanel = new TaskEx();
JFrame frame = new JFrame("Task Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private class Handler extends AbstractAction {
public Handler(String name) {
super(name);
putValue(MNEMONIC_KEY, (int) name.charAt(0));
}
#Override
public void actionPerformed(ActionEvent e) {
if (taskLeft > 0) {
taskLeft--;
doTask();
}
}
}
}
I am coding one applet that will show the number of mouse clicks on a button, and another that will show the coordinates of a mouse click and change the background color to a random color.
In both cases, I encountered the "is not abstract and does not override abstract method" error in BlueJ, and I need help understanding what I am doing wrong. I'm very new to this, so any tips/proofreadings are welcome as well :)
here's the first applet:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Option1 extends Frame implements ActionListener {
public void main (String[] args) {
int click = 0;
JFrame base = new JFrame ("Button Click Counter");
base.getContentPane().setLayout(null);
base.setSize(500,500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
click++; }
});
JTextField count = new JTextField(click);
this.add(button);
this.add(count);
}}
and the coordinates one:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
public class Option2 extends Frame implements MouseListener {
double x;
double y;
public void init() {
addMouseListener(this);
JFrame base = new JFrame("Mouse Coordinates");
base.getContentPane().setLayout(null);
base.setSize(500,500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField answer = new JTextField(x + "," + y);
}
public void mouseClicked( MouseEvent e ) {
x = e.getX();
y = e.getY();
this.setBackground(new Color((int)(Math.random() * 0x1000000)));
}}
Thanks in advance!
Option1 declares to implement the ActionListener interface:
public class Option1 extends Frame implements ActionListener {
If a class does so, it must be either abstract (which Option1 is not) or it must implement the methods declared in the interface. When you take a look at the API for ActionListener, you'll find one method there:
void actionPerformed(ActionEvent e)
You need to implement this method in Option1, e.g.
#Override
public void actionPerformed(ActionEvent e) {
click++;
}
and then register Option1 as ActionListener:
button.addActionListener(this);
The thing you tried is to implement the ClickListener in an anonymous inner class, which is also ok, but in this case Option1 must not implement ActionListener.
Your main method in Option1 is not declared properly, a main method usually is
public static void main(String[] args)
But the initialization you do in the main method should be done in the constructor or (as with Option2) in a separate method
public class Option1 extends Frame implements ActionListener {
private int click = 0;
public Option1() {
JFrame base = new JFrame("Button Click Counter");
base.getContentPane().setLayout(null);
base.setSize(500, 500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
button.addActionListener(this);
JTextField count = new JTextField(click);
this.add(button);
this.add(count);
}
#Override
public void actionPerformed(ActionEvent e) {
click++;
}
}
The problem with Option2 is that you only implement the method mouseClicked from the interface MouseListener. There are a couple others that need to be implemented:
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
Even if you do not want to handle these events, you need to have the empty methods.
A final tip: I don't know your IDE, but many IDEs (Eclipse, Netbeans, IntelliJ) have an option to generate the required methods for an interface for you, which saves a lot of typing ;)
you're implementing an interface...
at least you pronouce you do it when you write
public class Option1 extends Frame implements ActionListener
but you don't keep your contract! if you say you implement ActionListener, then you guaranteed that you have this method
public void actionPerformed(ActionEvent e) {
}
but your code lacks this method - and that's your error message...
I am a beginner java programmer, trying to implement ActionListener through an Inner class. Following is the simple code where I want to change label text on button click but instead of using getSource for more than one components I want to use Inner Class. Here is my code :
public class InnerClasses extends JPanel {
static JFrame frame ;
static JButton button ;
static JLabel label ;
public static void main(String[] args) {
InnerClasses i= new InnerClasses();
frame= new JFrame("Inner class");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(i);
label = new JLabel(BorderLayout.NORTH);
label.setText("I m label");
i.add(label);
button = new JButton(BorderLayout.SOUTH);
button.setText("Click me ");
button.addActionListener(new innerclass() );
i.add(button);
frame.setVisible(true);
}
class innerclass implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("i have been changed");
}
}
now when i try to register listener to button it gives error
No enclosing instance of type InnerClasses is accessible. Must qualify
the allocation with an enclosing instance of type InnerClasses (e.g.
x.new A() where x is an instance of InnerClasses).
Please help me with it if i am doing something agaisnt the syntax or whats wrong here
Your inner class is not static, so you cannot instantiate it from a static method, and in general, it is better to define inner classes as static, otherwise a new class (not instance) will be created for each instance of the enclosing class:
static class Innerclass implements ActionListener
to create any GUI required some hierarchy, based on Oracle tutorials and good practicies, code ordering could be important
don't to create any Swing GUI Objects inside main methods
I can't found any reason to declare anything static in Java
for example
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class InnerClasses {
private JFrame frame;
private JPanel panel;
private JButton button;
private JLabel label;
public InnerClasses() {
label = new JLabel();
label.setText("I m label");
button = new JButton();
button.setText("Click me ");
button.addActionListener(new MyActioListener());
panel = new JPanel();
panel.add(label);
panel.add(button);
frame = new JFrame("Inner class");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
}
class MyActioListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setText("i have been changed");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
InnerClasses innerClasses = new InnerClasses();
}
});
}
}