How to Add ActionListener to a JButton in Swing?
This code is an example of how to add ActionListener to a JButton.
When the JButton is clicked, the desired action is performed. In this case it prints a message to the console.
Code Java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonAction {
private static void createAndShowGUI() {
JFrame frame1 = new JFrame("JAVA");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton(" >> JavaProgrammingForums.com <<");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Re: How to Add ActionListener to a JButton. Java Swing
Thank you for helping. I think this book is moving a bit too quick for me. My friend says he learned nothing about Gui until his second year. I have started reading a new book, and I will post another question soon. Thanks again.
IDK12
Re: How to Add ActionListener to a JButton. Java Swing
inside the post method u can call get method. if u r sending post request.
if u r sending get request u can call post method inside the Get method
try it once.
Re: How to Add ActionListener to a JButton. Java Swing
Are you on about servlets chinni?
// Json
Re: How to Add ActionListener to a JButton. Java Swing
please i really need you to help me with a material to read on Java programming.. I will really appreciate
Re: How to Add ActionListener to a JButton. Java Swing
Quote:
Originally Posted by
JavaPF
This code is an example of how to add ActionListener to a JButton.
When the JButton is clicked, the desired action is performed. In this case it prints a message to the console.
Code Java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonAction {
private static void createAndShowGUI() {
JFrame frame1 = new JFrame("JAVA");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton(" >> JavaProgrammingForums.com <<");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Hi!
What code do I use instead of " System.out.println("You clicked the button");"
if I want the button to open a new class from my code? In this case I want the button to randomly
select five cards from my deck of cards in the code.
Code :
//Necessary imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SlumpaKort extends JPanel {
private static final long serialVersionUID = 1L;
//Knappvariabler
private static String buttonString = "Slumpa Kort";
private JButton btnRefresh;
/*
* SlumpaKort-konstruktor
*/
public SlumpaKort() {
//Skapa en JPanel
super(new BorderLayout());
//Skapa knappen
btnRefresh = new JButton(buttonString);
btnRefresh.setActionCommand(buttonString);
btnRefresh.addActionListener(new Clicked());
//Skapa en panel som knappen kan ligga på
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(btnRefresh);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
//Lägg till allt ovan till fönstret
add(buttonPane, BorderLayout.PAGE_END);
}
/*
* Klick-Event för knappen
*/
class Clicked implements ActionListener {
class Kort {
private String[] farg ={"Hjärter", "Spader", "Ruter", "Klöver"};
private String[] valor ={"Ess", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Knäckt", "Dam", "Kung"};
//* Visar vilka färger samt valörer som finns representerade i kortleken *//
public int f, v;
public Kort(int farg, int valor) {
if (farg < 1 || farg > 4 ||
//* Fyra fäger *//
valor <1 || valor > 13) {
//* 13 valörer *//
}
f = farg;
v = valor;
}
public int geFarg() {
return f;
}
public int geValor() {
return v;
}
public String toString() {
return farg[f - 1] + " " + valor[v - 1];
}
}
public class Kortlek {
public Kort[] bunt = new Kort[52];
public int antal = 0;
public int geAntal () {
return antal;
}
public void laggOverst(Kort k) {
bunt[antal] = k;
antal++;
}
public Kort geOversta() {
antal--;
return bunt[antal];
}
public void görKortlek() {
for (int f=1; f<=4; f++)
for (int v=1; v<=13; v++)
laggOverst(new Kort(f, v));
}
public void blanda() {
for (int i=0; i<antal; i++) {
int n = i + (int)(Math.random() * (antal - i));
Kort temp = bunt[n];
bunt[n] = bunt[i];
bunt[i] = temp;
}}
public void main( String args[]){
//* Blanda kortlek *//
Kortlek kortlek = new Kortlek();
kortlek.görKortlek();
kortlek.blanda();
//*Loopar kortlek.geOversta fem gånger för att sedan dela ut fem slumpade kort*//
for (int i=0; i<5; i++){
Kort k = kortlek.geOversta();
System.out.println(k.toString());
}
}
}
public void actionPerformed(ActionEvent e) {
//Vad som ska hända när man klickar på knappen
JOptionPane.showMessageDialog(null, "Detta fungerar!");
}
}
/*
* Startpunkten för programmet.
* Här skapas fönstret.
*/
public static void main(String[] args) {
//Skapa formen
JFrame frame = new JFrame("Cards");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
//Skapa TestButton
JComponent contentPane = new SlumpaKort();
contentPane.setOpaque(true);
frame.setContentPane(contentPane);
//Visa fönstret
frame.pack();
frame.setVisible(true);
}
}
Re: How to Add ActionListener to a JButton. Java Swing
It will be better for you to open your own thread with your own topic, instead of adding to an existing thread.
You should isolate the code for
Quote:
I want ... to randomly select five cards from my deck of cards
into a separate small program and get that logic to work and then merge that code into the larger program.
Re: How to Add ActionListener to a JButton. Java Swing
Hello _Alvin,
Yes please create a new thread and we will answer you there :)
Re: How to Add ActionListener to a JButton. Java Swing
hi people,
i'm finishing one application very simple, and i realise that i need more feedback messages.
This button send packages into a device until it answers, but my info label didn't work.
JButton okButton = new JButton("START");
okButton.setAlignmentY(0.5f);
okButton.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
statusLabel.setText("Status: Sending..."); <-- doesn't appear unless i put in the comment line handleOKConfig();
System.out.println(statusLabel.getText()); <-- always appears.
handleOKConfig(); <-- call the method that send the packages
}
});
Inside the method handleOKConfig() i have another indication of when the application has finished sending the packet, success message --> statusLabel.setText("Status: Target device in bootload mode!"); and work always.
I think the problem is with addActionListener or actionPerformed. Someone can help me?
Thanks!
Re: How to Add ActionListener to a JButton. Java Swing
Quote:
doesn't appear unless i put in the comment line handleOKConfig();
Not sure that adding a comment line to your code changes how it executes.
Your problem could be with changing Swing GUI values from the Swing Event Thread. Swing can't update the GUI while your code is using the thread. Try putting the setText() in a SwingUtilities thread using an invoke... method.
Re: How to Add ActionListener to a JButton. Java Swing
Can you give me a smal example? I don't understand cleary...
Re: How to Add ActionListener to a JButton. Java Swing
Quote:
Originally Posted by
Norm
Not sure that adding a comment line to your code changes how it executes.
Your problem could be with changing Swing GUI values from the Swing Event Thread. Swing can't update the GUI while your code is using the thread. Try putting the setText() in a SwingUtilities thread using an invoke... method.
When i comment the handleOkConfig() line, my label show what i want. But i need that execute this method too.
can you give a small example...I don't understand cleray...
Re: How to Add ActionListener to a JButton. Java Swing
Do a Search for SwingUtilities. There should be sample code that you can copy.
Re: How to Add ActionListener to a JButton. Java Swing
What does frame.pack do?
Also, what is all that with invoke later and stuff like that? Why not invoke now?
:))=))=))
Seriously though, what's that about?
Also, this is unrelated, but when is jdk 7.0 coming out?
(And do you have to go download it yourself and go to the website every time a new one comes out or can you get Eclipse or some other compiler to alert you and take you to the download site or even download it for you automatically without having to have you do anything?)
I'm not familiar with Swing Utilities or threads. I've seen examples like that a few times before and I've always wondered what it meant and what the purpose of it was.
Re: How to Add ActionListener to a JButton. Java Swing
If I'm not mistaken, frame.pack(); applies all of the changes to the content pane.
Re: How to Add ActionListener to a JButton. Java Swing
API Javadoc for frame.pack (inherited from Window.pack):
Quote:
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. If the window and/or its owner are not yet displayable, both are made displayable before calculating the preferred size. The Window will be validated after the preferredSize is calculated.
Re: How to Add ActionListener to a JButton. Java Swing
Thanks a lot this posted helped me a lot and saved me a lot of my hair :-D
Re: How to Add ActionListener to a JButton. Java Swing
I am not sure I find it useful to post a solution where a function call has a parameter that is itself a function definition:
(I know this started from post #1 of this thread)
For example
...
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
...
Twently levels of doing that and who can follow???
I tried redoing this code w/o {ie separating definitions) I ended up a compiler error that I couldn't do this
because all my functions were static. If I were to do the construction of the GUI elements in the body of the
constructor - say ButtonAction(), I shouldn't have to worry.
So how would I add an ActionListener() to a button while w/i the constructor???
maddog