Go Back   Java Programming Forums > Learning Java > Java Code Snippets and Tutorials


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-03-2009, 12:27 PM
JavaPF's Avatar
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Post How to Add ActionListener to a JButton. Java 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.

Java Code:
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();
            }
        });
    }
}



__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote Share this thread on Facebook
Sponsored Links
Java Training from DevelopIntelligence
  #2 (permalink)  
Old 07-07-2009, 04:54 PM
Junior Member
 

Join Date: Jul 2009
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
IDK12 is on a distinguished road
Default 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
Reply With Quote
  #3 (permalink)  
Old 20-10-2009, 07:13 AM
Junior Member
 

Join Date: Oct 2009
Posts: 19
Thanks: 1
Thanked 0 Times in 0 Posts
chinni is on a distinguished road
Default 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.
Reply With Quote
  #4 (permalink)  
Old 20-10-2009, 11:15 AM
Json's Avatar
Super Moderator
 

Join Date: Jul 2009
Location: Manchester, United Kingdom
Posts: 1,181
Thanks: 55
Thanked 137 Times in 133 Posts
Json will become famous soon enoughJson will become famous soon enoughJson will become famous soon enough

I'm feeling Happy
Default Re: How to Add ActionListener to a JButton. Java Swing

Are you on about servlets chinni?

// Json
Reply With Quote
  #5 (permalink)  
Old 26-05-2010, 01:25 PM
Junior Member
 

Join Date: May 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
shelexelex is on a distinguished road
Default 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
Reply With Quote
  #6 (permalink)  
Old Yesterday, 12:56 PM
Junior Member
 

Join Date: Sep 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
_Alvin is on a distinguished road
Default Re: How to Add ActionListener to a JButton. Java Swing

Quote:
Originally Posted by JavaPF View Post
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.

Java Code:
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.

Java 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);
		
	}
	
}
Reply With Quote
  #7 (permalink)  
Old Yesterday, 04:41 PM
Norm's Avatar
Senior Member
 

Join Date: May 2010
Location: SW Missouri
Posts: 760
Thanks: 0
Thanked 139 Times in 138 Posts
Norm is on a distinguished road

I'm feeling Fine
Default 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.
Reply With Quote
Reply

Tags
actionlistener, java swing, jbutton

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to Add a JMenu toolbar to a Java Swing application JavaPF Java Code Snippets and Tutorials 3 30-04-2010 02:00 PM
JAVA ImageIcon and JButton resizing problem -- please go easy on me. :)? antitru5t AWT / Java Swing 1 13-03-2009 08:39 AM


100 most searched terms
Search Cloud
2d arraylist java actionlistener actionlistener in java actionlistener java addactionlistener addactionlistener in java addactionlistener java applications of oops could not create java virtual machine xp double format java double to int double to int java double to integer in java double to integer java eclipse shortcut keys eclipse tutorial for beginners exception in thread "awt-eventqueue-0" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.nullpointerexception exception in thread "main" java.lang.outofmemoryerror: java heap space format double java get mouse position java java 2d arraylist java actionlistener java addactionlistener java convert list to map java double format java double formatting java double to int java double to integer java format double java forum java forums java get mouse position java list to map java mouse position java programming forum java programming forums java programming help java sendkeys java two dimensional arraylist java.lang.classformaterror: truncated class file java.lang.outofmemoryerror: java heap space java.util.arraylist jbutton actionlistener jtextarea font jtextfield font size jxl.read.biff.biffexception: unable to recognize ole stream programming mutators and generics two dimensional arraylist java writing ipod apps

All times are GMT. The time now is 09:06 AM.
Powered by vBulletin® Copyright ©2000-2009, Jelsoft Enterprises Ltd.