I am a new comer to java and currently teaching myself via the HeadFirst java book.
I was going through GUI interfaces and the code from the book does not seem to run,
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1 implements ActionListener {
JButton Button;
public static void main(String[] args) {
SimpleGui1 gui = new SimpleGui1();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent event) {
Button.setText("I have been clicked");
}
}
The exception :
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Can someone tell me what's wrong?
The class member variable Button is never initialized. Rather another with a different name (Java is case sensitive) is defined locally in the go method.
In the ActionListener you can simply use the ActionEvent source to determine the source of the Action:
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
button.setText("I have been clicked");
}
This removes the need to have the JButton as a class member variable.
Initialize button, it's still null.
You're having a NullPointerException.
Related
So I have this calculator when you first run it you will have to input name and section and then press submit and when you press submit 4 buttons will appear and each of those buttons will bring you to another JFrame. The problem is when I press back from that other JFrame it will direct me back from that main frame and you will again have to input name and section. How do I maintain the data which the user first inputted?
You can manage that using array of Jframes , when click frame you know the index of it
May be beacuse you are Extending JFrame. Which is a bad habit .
Here I have done a short EG which creates the Object of respective Frames and calls the method
setVisible(T/F) accordingly :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TestMultiFrames {
JFrame mainFrame,frame2,frame3;
public TestMultiFrames(){
mainFrame =new JFrame();
frame2 =new JFrame();
frame3 =new JFrame();
JPanel p=new JPanel();
JButton but1=new JButton("frame2");
JButton but2=new JButton("frame3");
JButton but3=new JButton("back to frame 3");
p.add(but1);
frame2.add(but2);
frame3.add(but3);
but1.addActionListener(new CustomActionListener1());
but2.addActionListener(new CustomActionListener2());
but3.addActionListener(new CustomActionListener3());
mainFrame.add(p);
mainFrame.setSize(200,200);
frame2.setSize(200,200);
frame3.setSize(200,200);
mainFrame.setVisible(true);
}
public static void main(String... args)
{
new TestMultiFrames ();
}
class CustomActionListener1 implements ActionListener{
public void actionPerformed(ActionEvent e) {
mainFrame.setVisible(false);
frame2.setVisible(true);
}
}
class CustomActionListener2 implements ActionListener{
public void actionPerformed(ActionEvent e) {
frame2.setVisible(false);
frame3.setVisible(true);
}
}
class CustomActionListener3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
frame3.setVisible(false);
frame2.setVisible(true);
}
}
}
I just started learning Java 1 week ago, and I'm a 100% totally beginner. In this code, I can't seem to be able to put an actionlistener/get one to work. I don't even know where/how/in what way to put it, despite reading dozens of tutorials. I've created a JFrame with a JPanel in it, and on the JPanel there's a button. So far so good (and working). But then, I want it to be so that if the button is clicked, another button appears. Thank you sooo much in advance!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {
public static void main(String[] args) {
//------------------------------------------------
JFrame frame = new JFrame("Skeleton");
JPanel panel = new JPanel();
frame.setContentPane(panel);
frame.setSize(600,600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JButton button = new JButton("This is a button.");
JButton button2 = new JButton("Hello");
panel.setLayout(null);
button.setBounds(20,20,200,25);
button2.setBounds(20,70,200,25);
panel.add(button);
//-------------------------------------------
button.addMouseListener(this);
}
public void ActionPerformed(ActionEvent e) {
System.out.println("Hello");
}
}
i will give you some advice
1) Don't implement ActionListener in top classes, use anonymous classes or private classes instead.
Example :
Anonymous class (also call Swing Actions)
myComponent.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//code here
}
})
or
//inner class
public class Skeleton{
// in some part
private class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
//code here
}
}
}
2) Your code won't compile cause you are not implementing ActionListener interface
public void actionPerformed(ActionEvent evt) is the signature.
You have to addActionListener to your component
button.addActionListener(this);
3) Don't use null layout, cause you'll have a lot of problem if you want to add more components or resize windows cause you have to setBounds manually and it will be frustrating instead use [Layout Manager][1].
4) Try to not extends JFrame if is not necesary instead have a reference in your class, for example.
public class Skeleton{
private JFrame frame;
}
You need to add the actionlistener.
Register an instance of the event handler class as a listener on one or more components. For example:
yourdesiredcomponent.addActionListener(this);
For more details check the doc
Hi take a look on this code:
package arkanoid;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.*;
public class Arkanoid extends JFrame
{
private static final long serialVersionUID = 6253310598075887445L;
static JFrame frame;
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
//frame = new JFrame("Arkanoid");
frame.setLocationRelativeTo(null);
frame.setIgnoreRepaint(true);
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(500,400);
frame.add(new Gra());
}
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
frame.dispose();
System.exit(0);
}
}
public static void main(String[] args)
{
//new Arkanoid();
frame = new JFrame("Arkanoid");
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Arkanoid BETA");
frame.setLocationRelativeTo(null);
frame.setIgnoreRepaint(true);
frame.setResizable(false);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Nowa Gra");
panel.add(button);
button.addActionListener (new Action1());
JButton button2 = new JButton("Wyjscie");
panel.add(button2);
button2.addActionListener (new Action2());
}
}
This code almost works, I want to make a button2 a quit button working like X button in top right frame's icons and button1 need to open a Gra() in the same window. When im doing it like this it isnt work fine:/ i need to click 2 times on button1 to go to Gra() and what is more KeyListeners in Gra() arent working :(
Im new in buttons, frames and panels in java so please help with this code. Correct it please.
There are a number of fundamental problems with your code, the least of which is why your button1 requires 2 clicks.
However, for your problem you should try rearranging the order of your button1 listener, so that your Component is added to the frame first, before setting it to be visible. An example that should work:
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
frame.add(new Gra());
frame.revalidate();
}
}
Note you have already set the size, location etc of frame in main, so there is no need to set them again every time the button is clicked.
I stress that there are more important problems with your code than this issue. You should take a look at Java's Modifier Types (static does not seem applicable here), as well as object-oriented concepts such as inheritance (you define your Arkanoid class to extend JFrame, yet have a JFrame object as a class variable).
I want to make a button2 a quit button working like X button in top right frame's
You can use the ExitAction class found in Closing an Application.
For other examples of how to use buttons read the Swing tutorial on How to Use Buttons. This is the place to start for all you Swing related questions.
There are many problems with your code. I've refactored it a little. With below code & #ricky116 answer I think you should get all of them.
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
public class Arkanoid extends JFrame
{
public Arkanoid() {
super("Arkanoid");
setSize(500,400);
setTitle("Arkanoid BETA");
setLocationRelativeTo(null);
setResizable(false);
final JPanel panel = new JPanel();
setContentPane(panel);
panel.add(new JButton(new AbstractAction("Nowa Gra") {
public void actionPerformed (ActionEvent e) {
panel.removeAll();
panel.add(new Gra());
panel.revalidate();
panel.repaint();
}
});
panel.add(new JButton(new AbstractAction("Wyjscie") {
public void actionPerformed (ActionEvent e) {
Arkanoid.this.setVisible(false);
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Arkanoid frame = new Arkanoid();
frame.setVisible(true);
}
});
}
}
How can I call a method by pressing a JButton?
For example:
when JButton is pressed
hillClimb() is called;
I know how to display messages etc when pressing a JButton, but want to know if it is possible to do this?
Many thanks.
If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.
With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.
You can use an anonymous class too:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hillClimb();
}
});
Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonSample extends JFrame implements ActionListener {
public ButtonSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(100, 100);
setLocation(100, 100);
JButton button1 = new JButton("button1");
button1.addActionListener(this);
add(button1);
setVisible(true);
}
public static void main(String[] args) {
new ButtonSample();
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
}
}
Fist you initialize the button, then add ActionListener to it
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});
You need to add an event handler (ActionListener in Java) to the JButton.
This article explains how to do this.
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
with lambda
Ok, i started learning java, and this is a code from internet that doesn't work on my pc
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class form2
{
public static void main(String args[])
{
// Create Frame 1
JFrame frame = new JFrame("Frame 1");
frame.setSize(333,333);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create panel
JPanel panel = new JPanel();
// Create button
JButton button = new JButton("Press me!");
// Add things
panel.add(button);
frame.add(panel);
frame.setVisible(true);
// Add the action listener to that button
button.addActionListener(new action());
static class action implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
// Create Frame 2
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(200,200);
frame2.setVisible(true);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Clicked!");
JPanel panel2 = new JPanel();
// First add to frame2 the panel just create
frame2.add(panel2);
// Add to panel the label
panel2.add(label);
}
}
}
}
And it give me an error about action and i don't understand why.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
action cannot be resolved to a type
Illegal modifier for the local class action; only abstract or final is permitted
at form2.main(form2.java:26)
What is my problem?? On that guy's computer works
http://www.youtube.com/watch?v=jEXxaPQ_fQo&feature=channel_video_title
Can anyone help me??
You are declaring a static class inside of a method which you shouldn't do. So take it out of the method, or better, make it an anonymous inner class:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Create Frame 2
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(200, 200);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Clicked!");
JPanel panel2 = new JPanel();
// First add to frame2 the panel just create
frame2.add(panel2);
// Add to panel the label
panel2.add(label);
frame2.setVisible(true);
}
});
What does this question have to do with java-ee by the way??
You declare a class inside a method, in this case main, however, it should be outside of it, like the guy in the video says.
Hope that helps!
Static classes cannot be defined inside a method. Move the class definition static class .... { } outside of your main method. Also, it is good practice to start classes with an uppercase character (e.g AddPanelAction).
The actionlistener class must be declared outside of the main method like this:
import javax.swing.*;
import java.awt.event.*;
public class Main
{
public static void main(String args[])
{
// Create Frame 1
JFrame frame = new JFrame("Frame 1");
frame.setSize(333,333);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create panel
JPanel panel = new JPanel();
// Create button
JButton button = new JButton("Press me!");
// Add things
panel.add(button);
frame.add(panel);
frame.setVisible(true);
// Add the action listener to that button
button.addActionListener(new action());
}
public static class action implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Create Frame 2
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(200,200);
frame2.setVisible(true);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Clicked!");
JPanel panel2 = new JPanel();
// First add to frame2 the panel just create
frame2.add(panel2);
// Add to panel the label
panel2.add(label);
}
}
}
Or you can declare the actionlistener by using an anonymous inner class like this:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do things here
}
});
Static classes can not be defined inside a method. Move that class outside the main method or declare your class non-static within the main method itself, if you need . A static class always requires one outer non-static class.
A day late and dollar short.... but I'll still add it.
Most of the Java actionListener examples on the web are too darn complex. To understand it, you just really need a form, button, and the actionListener. In the example below, the form server as the listener through the addition of 'implements ActionListener'.
import java.applet.Applet;
import java.awt.Button;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Sample extends Applet implements ActionListener {
Button button;
public void init() {
setLayout(new BorderLayout());
button = new Button("Test");
add("Center", button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// your code to do what you want when the button was clicked goes here
}
}