How to initiate an action upon clicking a jbutton in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm wondering how to initiate an action if a jbutton is clicked on in my JFrame.
I've tried searching for answers but haven't had much luck.
This is all i have right now, i basically just want some text to be displayed upon clicking the button.
public class Slots {
public static void main(String[] args){
Slots();
}
public static void Slots(){
//JFRAME
JFrame f = new JFrame("Slots Game");
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setResizable(false);
//JButton
JButton Button = new JButton("Start");
f.add(Button, BorderLayout.PAGE_END);
f.setVisible(true);
}
}

There are 3 ways to do that.
Create a class that implements the ActionListener interface. And then add an instance of that class as an action listener to the button.
Making the current class (in your case Slots) implement the ActionListener interface. And then adding "this" as the action listener to the button.
The third method, which is probably the most convenient/efficient method, is using an anonymous inner class like below.
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// your code goes here
}
});
For more details see ActionListener API

Related

Trying to create a really simple button for my Panel, but even though i implement the action listener in the class, it isn't working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I am trying just to get the button to display some text in the console, but whatever i do it isn't working here is the code for the Button class:
public class Button extends JButton implements ActionListener {
JButton button;
Button (){
button = new JButton();
this.setText("Click NOW");
button.addActionListener(this);
this.setForeground(Color.white);
button.setBounds(300, 100, 100, 50);
this.setBackground(Color.red);
this.setBorder(null);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()== button) {
System.out.println("Display if you work");
}
}
}
There are no errors displayed and the code compiles correctly, it just isn't displaying the text in the terminal.
This code creates two JButtons, one the button field inside of the class, that you add the action listener to:
public class Button extends JButton implements ActionListener {
JButton button; // here!
Button (){
button = new JButton(); // here!
this.setText("Click NOW");
button.addActionListener(this); // and add the listener here
and the other which is the instance of this class that extends JButton:
// here !!!
public class Button extends JButton implements ActionListener {
// ....
and which is likely the one that is displayed as elsewhere you likely have this code:
Button button = new Button();
and then add this button to the GUI. Again, this "button" is from your Button class which extends JButton but doesn't have the action listener added to it.
You can solve this in one of two ways:
Don't create the new JButton button field inside of your new class and instead add the ActionListener to the this JButton, the instance of this class,
for example:
public class Button1 extends JButton implements ActionListener {
// JButton button;
Button1() {
// button = new JButton();
this.setText("Click NOW");
// button.addActionListener(this);
this.addActionListener(this);
this.setForeground(Color.white);
// button.setBounds(300, 100, 100, 50); // You really don't want to do
// this
this.setBackground(Color.red);
this.setBorder(null);
}
#Override
public void actionPerformed(ActionEvent e) {
// no need for the if block
// if (e.getSource() == button) {
System.out.println("Display if you work");
// }
}
}
Don't create a class that extends JButton but instead create code that creates a single JButton (not two) and add the ActionListener to the same object that is added to the GUI.
I'd go with number 2 myself and make it a method that returns a button with my properties of interest:
private JButton createMyButton(String text) {
JButton button = new JButton(text);
button.setForeground(Color.WHITE);
button.setBackground(Color.RED);
button.setBorder(null);
button.addActionListener(e -> {
System.out.println("Display if you work");
});
return button;
}
Side notes:
Avoid giving your class names that clash with core Java classes, such as class Button which clashes with the java.awt.Button class.
Avoid use of null layouts and setBounds. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For that reason you're far better off learning about and using the layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.
In your actionPerformed method, use equals in the if statement, like this:
if (e.getSource().equals(button)) {
System.out.println("Display if you work");
}
It should work. == doesn't work in this case.

how to make a button run a loop in java

I understand how to create a button and it's application in Java. Would anyone be able to show me the code to be able to make the button in the code below be able to print something as simple as hello world in the terminal. I am using bluej if that is of any matter. I am very sorry I am a beginner coder.
JButton button = new JButton();
button.setActionListener(e -> System.out.println("Clicked"));
This uses a lambda expression. Inside it, you can add as much code as you like, but add it between {} if it's more than a line.
More on buttons here
You need a listener for your button.
JButton button= new JButton("Button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Hello World");
}
});
the button will 'listen' for the action and preform whatever task you define for it.
ActionListener is what you are looking for. There is a very nice guide on Oracle's website. You should look into this tutorial and understand different ways of creating ActionListeners. I will give you a simple example which doesn't involve Anonymous Classes because I am not sure of how much you know about them.
public class Frame extends JFrame implements ActionListener {
public Frame() {
super("Test"); // calling the superclass
setLayout(new FlowLayout()); // creating a layout for the frame
setDefaultCloseOperation(EXIT_ON_CLOSE);
// create the button
JButton jbTest = new JButton("Click me!");
/* 'this' refers to the instance of the class
because your class implements ActionListener
and you defined what to do in case a button gets pressed (see actionPerformed)
you can add it to the button
*/
jbTest.addActionListener(this);
add(jbTest);
pack();
}
// When a component gets clicked, do the following
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Hello!");
}
}

How to close current JFrame? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have read similar topics but i did find answer there.
I created JFrame with close button. After click I want to close current window. I try setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE), or setVisible(false).
public class Windows {
JFrame frame;
JFrame frame1;
public Windows(){
}
public JFrame getCreateFrame(){
frame1 = new JFrame("Create User");
frame1.setSize(500,500);
frame1.setVisible(true);
frame1.getContentPane().add(new Panels().getwelcomTxtLabelPanel1(), BorderLayout.NORTH);
frame1.getContentPane().add(new Panels().getCreateUser(), BorderLayout.SOUTH);
frame1.getContentPane().add(new Panels().getUserLabel(), BorderLayout.WEST);
frame1.getContentPane().add(new Panels().getUserField(), BorderLayout.CENTER);
return frame1;
}
}
Here is a button.
public JButton getCancelButton(){
cancel = new JButton("cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
new Windows().getCreateFrame().setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
});
return cancel;
}
The problem is the following action (and not only this):
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
new Windows().getCreateFrame().setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
});
here you create a new Windows object and call getCreateFrame() which creates a new JFrame and then you call setDefaultCloseOperation() on it.
So you work with different Windows / JFrame instances.
Instead you should create your JFrame in the constructor of Windows and call setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE) of this JFrame in the constructor as well.
Afterwards you can use setVisible(false) in your action - but for this JFrame and not for a new created one.
BTW. getCancelButton() should most probably not create a new button every time it is called.
You have to make the frame invisible and dispose it.
JFrame frame;
frame.setVisible(false);
frame.dispose();
This completely closes the frame. If only this frame is open and no nondeamon threads are running, the program will quit after disposing the frame.

Swing - Dispose a frame [duplicate]

This question already has answers here:
The Use of Multiple JFrames: Good or Bad Practice? [closed]
(9 answers)
Closed 7 years ago.
My aim is for an action listener to close a specific JFrame when the user hits the JButton to quit.
Overall, when the program starts a large JFrame opens then a small one in front....in my code the user enters some details in this small one and hits submit(for the sake of simplicity, ive omitted this code here and replaced submit with quit)
So when this quit buttons pressed. I expect this small JFrame to close. I can't seem to figure this out. The action listeners in a different class and ive tried making instances and had no luck. I've commented out the code I've tried below when attempting to solve this issue.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test
{
public static void main(String Args[])
{
makeGUI m = new makeGUI();
}
}
class makeGUI
{
JButton close = new JButton("CLOSE ME");
makeGUI()
{
frame f1 = new frame();
JFrame smallframe = new JFrame(); //want to close this one
JPanel jp = new JPanel(new FlowLayout());
smallframe.setSize(300,300);
smallframe.setLocationRelativeTo(null);
smallframe.setDefaultCloseOperation(smallframe.DISPOSE_ON_CLOSE);
close.addActionListener(new action());
jp.add(close);
smallframe.add(jp);
smallframe.setVisible(true);
}
class action implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//makeGUI s1 = new makeGUI();
if (e.getSource () == close)
{
//s1.smallframe.dispose();
System.out.println("gotcha");
}
}
}
}
class frame extends JFrame
{
frame ()
{
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("big one");
setVisible(true);
}
}
First, it's not a good practice to name classes with a lowercase, so try renaming to something like MakeGUI instead of makeGUI.
The problem with your commented code is that it creates a new instance of makeGUI every time the button is clicked and the action listener is invoked. The result is that when you click on the close button, a new frame is created, then an inner one and this inner one gets immediately closed. The only thing you'd be doing is creating more and more frames. You should keep the instance as a state, for instance as a class member:
class MakeGUI {
JFrame smallframe;
JButton close = new JButton("CLOSE ME");
MakeGUI() {
frame f1 = new frame();
smallframe = new JFrame(); //want to close this one
JPanel jp = new JPanel(new FlowLayout());
smallframe.setSize(300, 300);
smallframe.setLocationRelativeTo(null);
smallframe.setDefaultCloseOperation(smallframe.DISPOSE_ON_CLOSE);
close.addActionListener(new action());
jp.add(close);
smallframe.add(jp);
smallframe.setVisible(true);
}
class action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close) {
// use this instead of dispose
smallframe.dispatchEvent(new WindowEvent(smallframe, WindowEvent.WINDOW_CLOSING));
System.out.println("gotcha");
}
}
}
}
If you want to simulate someone pressing the [X] button then you can use this code to programmatically trigger this event:
smallFrame.dispatchEvent(new WindowEvent(smallFrame, WindowEvent.WINDOW_CLOSING));
Aside from that, your code is not working because you are not closing your instance of the small window, instead you are creating another instance and disposing of it. Inside your close event you should be closing the smallFrame instance.
You can do this by either passing your JFrame to the constructor of your ActionListener or making smallFrame a class variable.
It appears you are using the small JFrame as a pop up to get information or display information. If so, you may want to look into the JOptionPane class which is made for "Dialogue Boxes".
Documentation:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

Java GUI Action Listener with Inner Classes

I am working on a LAB for one of my classes and am in need of some assistance.
I am building an Apartment Complex GUI which will have a menu system and individual functions between many different classes. The complex with consist of Tenants, Employees and a Bank.
I currently have the whole project working based out of the console but now I am assigned to convert it to a GUI interface.
This is the code in my main function for GUI:
ApartmentComplex mavPlace = new ApartmentComplex(); //creates a new apartment complex object
mavPlace.aptBank.setBalance(ANNUAL_BUDGET); //sets the apartment bank budget
readFile(mavPlace);
mavPlace.goThroughAndAssignValues(mavPlace);
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
mavPlace.lease(mavPlace);
}
});
With the action listener, when the button is pressed it should call a lease function in another class of mine. From there I want it do go back to console output.
The error netbeans is giving me is: local variable mavPlace is accessed from within inner class; needs to be declared final
.... now I went an made the decleration final just to see what happened and it worked, but i couldnt edit my complex details so that was not possible.
What can i do?
Thank You!
Make your class implement the ActionListener interface and use this to add an action listener ie
button.addActionListener(this);
http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
If you use Anonymous Class, you should set the parameter used in the class as final type in current block or as a member private variable.
class MyGUI
{
ApartmentComplex mavPlace;
public MyGUI()
{
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
mavPlace = new ApartmentComplex(); //creates a new apartment complex object
mavPlace.aptBank.setBalance(ANNUAL_BUDGET); //sets the apartment bank budget
readFile(mavPlace);
mavPlace.goThroughAndAssignValues(mavPlace);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
mavPlace.lease(mavPlace);
}
});
}
}
I think you should reconsider your structure of your program.
If you told us the complete purpose, you would get better answer.

Categories

Resources