how to make a button run a loop in java - 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!");
}
}

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.

actionPerformed with JButton [duplicate]

private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed().
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:
jBtnSelection.addActionListener(e -> selectionButtonPressed());
In this case, e is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e).
The second method also allows you to call the selectionButtonPressed method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
I don't know if this works but I made the variable names
public abstract class beep implements ActionListener {
public static void main(String[] args) {
JFrame f = new JFrame("beeper");
JButton button = new JButton("Beep me");
f.setVisible(true);
f.setSize(300, 200);
f.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert code here
}
});
}
}
To add an action listener, you just call addActionListener from Abstract Button.

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.

java swings to display different panel in same frame (java)

the below given is a java class which get invoked on clicking "next" button in first frame .and i send a parameter is i send getContentPane() to this given below program , here ill access the parameter and set its visibality to false , here i use "Back" button to go to previous page dats for ma first frame , but on clicking Back its not showing the previous frame for me , plz help me out with dis
its just a simple program , if i need to take some text input from second frame and again i need to come back to home screen so, how can i achieve this in this program
public class firstframe extends JFrame{
public firstframe()
{
getContentPane().setLayout(null);
JButton next=new JButton("Next");
next.setBounds(100,100,100,100);
getContentPane().add(next);
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
Container c=getContentPane();
}
new signup(c);
});
}
public static void main(String ar[]){
firstframe f=new firstframe();
f.setVisible(true);
f.setSize(1365,740);
f.show();
}
}
public class signup extends JFrame{
public signup(Container d)
{
final Container c=d;
c.setVisible(false);
final Container e;
e=c.getParent();
e.setLayout(null);
JButton back=new JButton("Back");
back.setBounds(100,100,100,100);
e.add(back);
e.setVisible(true);
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
e.setVisible(false);
d.setVisible(true);
}
});
}
}//
Sorry, but your code style is not good. Too many unnecessary assignments which prevents me to understand code meaning and too short variables names.
Look what you do. In signup() method you assign e=c.getParent(); it means e is parent component of c and d. Then in back action listener you make e unvisible and try to make d visible. But so as e is parent of d, d never becomes visible while its parent is unvisible.
Quick fix for this code is change back button action listener to
back.setVisible(false);
d.setVisible(true);
And of course make back final
final JButton back=new JButton("Back");

How to disable javax.swing.JButton in java?

I have created a swings application and there is a "Start" button on the GUI. I want that whenever I clicked on that "Start" button, the start button should be disabled and the "Stop" button be enabled.
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
startButton.setEnabled(false);
stopButton.setEnabled(true);
But the above code is not creating the desired affect on the GUI.
Is the above code correct for what I want to do?
It's not working with "repaint()" too.
Edit:
The code is very long so I can't paste all the code. I can tell, though, more about the code.
In the "ActionPeformed" method of "start" button, after calling the above two statements, I am executing a "SwingWorker" thread.
Is this thread creating any problem?
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.
You can add a simple ActionListener like this:
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
);
note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.
The code is very long so I can't paste
all the code.
There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.
You need to create a SSCCE to post on the forum.
So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.
Learn how the basice work first before writing a 200 line program.
Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.
This works.
public class TestButton {
public TestButton() {
JFrame f = new JFrame();
f.setSize(new Dimension(200,200));
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
final JButton stop = new JButton("Stop");
final JButton start = new JButton("Start");
p.add(start);
p.add(stop);
f.getContentPane().add(p);
stop.setEnabled(false);
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(true);
stop.setEnabled(false);
}
});
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(false);
stop.setEnabled(true);
}
});
f.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
new TestButton();
}
}

Categories

Resources