Dynamically adding action listener to buttons - java

i think this is wrong. i want my code to add actionlistener as soon as button is created.Is there a way to do that dynamically. look at the inner for loop i have a problem adding there
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;
/* <applet code = "Gridl.java" width=300 height=200>
</applet> */
public class Gridl extends Applet
{
TextField t1=new TextField(" ");
public void init()
{
int n = 1;
setLayout(new GridLayout(4,4));
add(t1);
setFont(new Font("Tahoma",Font.BOLD,24));
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
add(new Button(""+n));
this.addActionListener(this); // this didnt work :(
n++;
}
}
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
t1.setText(str);
}
}

I think you have some conceptual misunderstandings reflected in your code here. It's important to consider which component you are adding the ActionListener onto. At the moment, your code adds the ActionListener to the Gridl object extending Applet, rather than the button itself. It won't throw an exception, because that's valid, but it won't give you the behaviour you want
To get you working, I suggest you replace
add(new Button(""+n));
with
Button b = new Button(""+n);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked button "+e.getSource().toString());
}
});
this.add(b);
Note that this sets up a new ActionListener for every Button object, with its behaviour determined by what you put in the actionPerformed() method. You can have the same behaviour for all buttons, or different for each.
I would suggest that you might want to read the oracle Java Swing GUI tutorials, in particular the one on actions. There are code samples there too.
EDIT:
I have realised you might want to have your Gridl be the listener for all buttons. In which case - you can achieve this by:
public class Gridl extends Applet implements ActionListener
{
TextField t1=new TextField(" ");
public void init()
{
int n = 1;
setLayout(new GridLayout(4,4));
add(t1);
setFont(new Font("Tahoma",Font.BOLD,24));
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
Button b = new Button(""+n));
b.addActionListener(this);
this.add(b);
n++;
}
}
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
t1.setText(str);
}
}

try like this when creating button new button().add without ending that statement.
new Button("").addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});

Related

I'm trying to make a button to count characters in a text field

I'm trying to use the JButton count to count the number of characters entered into the JTextField t. I'm new to Java and GUIs but here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends Frame implements ActionListener{
TextField t;
Button count;
int a;
Choice choice;
public GUI1(){
this.t = new TextField("", 30);
this.count = new Button("count");
this.count.addActionListener(this);
JTextField x = new JTextField();
x.setEditable(false);
this.setTitle("Character count");
this.setLayout(new FlowLayout());
this.add(x);
this.add(t);
this.add(count);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.count)
t.setText(choice.getSelectedItem()+ " " +a);
}
I'm also trying to enter the value in another uneditable JTextField x. Any help is appreciated.
Add this to your code
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = t.getText().length();
}
});
OR
You can use lambda expression like this
count.addActionListener(e -> a = t.getText().length());
For More
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
You need to add a listener
TextField t = new TextField();
Button b = new Button("Count");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
}
});
You can read more about here
http://www.tutorialspoint.com/awt/awt_button.htm
First of all, I recommend you not to use AWT elements, since it brings tons of problems and it has little to no support, instead you can try using Swing components which are a replacement/fix for AWT. You can read more about here. You might also want to read AWT vs Swing (Pros and Cons).
Now going into your problem:
You should avoid extending from JFrame, I might recommend you to create a new JFrame object instead. Here's the reason to why. That being said, you can also remove all your this.t and other calls with this.
I'm glad you're using a Layout Manager!
And now to count the number of characters on your JTextField and set text to your other JTextField you should use this code:
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
Also I fixed your code, I changed AWT elements to Swing ones and added number of cols to your second JTextField so it would appear.
So, here's a running example that I made from your code (And removed Choice choice line since you didn't posted that code):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 {
JTextField t;
JButton count;
int a;
JFrame frame;
public GUI1(){
frame = new JFrame();
t = new JTextField("", 15);
count = new JButton("count");
JTextField x = new JTextField("", 15);
x.setEditable(false);
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
frame.setTitle("Character count");
frame.setLayout(new FlowLayout());
frame.add(x);
frame.add(t);
frame.add(count);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
new GUI1();
}
}
When you click on a button you should
String str = t.getText(); // get string from jtextfield
To save the text from the texfield. Then you can use something like:
a = str..length(); // get length of string
x.setText(str + " " + a); //set it to the field
To set it to the JTextField.

The button declared in the frame is not working properly when it is pressed

import java.awt.*;
import java.sql.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class nava extends JFrame implements ActionListener
{
Button b1=new Button("clear");
TextField t1=new TextField();
public nava()
{
this.setLayout(new GridLayout(2,2));
b1.addActionListener(this);
this.setSize(200,200);
add(t1);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText(""); //without space
}
}
public static void main(String r[])
{
new nava().show();
}
}
On clicking the button b1 the TextField should get empty but it is not
getting empty.The textfield just remain the same .But when I put space in the actionPerformed function it add a space in textfield. Please tell me what is the problem with the code.
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText(" "); //with space
}
}
Use Swing components, not AWT components and the code should work. For example use JButton and JTextField not Button and TextField. Also don't call deprecated methods such as show(). Please consider checking the Swing tutorials as they'll teach you much you'll find useful. For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Nava extends JFrame implements ActionListener {
JButton b1 = new JButton("Clear");
JTextField t1 = new JTextField("Fubar", 10);
public Nava() {
this.setLayout(new GridLayout(2, 2));
b1.addActionListener(this);
// this.setSize(200, 200);
add(t1);
add(b1);
b1.setMnemonic(KeyEvent.VK_C); // alt-c to activate button
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
t1.setText("");
}
}
public static void main(String r[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Nava nava = new Nava();
nava.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nava.pack(); // let components and layout managers size themselves
nava.setLocationByPlatform(true);
nava.setVisible(true);
}
});
}
}
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
As for why your code doesn't work -- I honestly don't know as I don't work directly with AWT library components; very few people do. Edit: note this similar question. The authors of that question don't know why setText("") but offer a work-around:
// first this:
tf.setText(" ");
// followed by this:
tf.setText("");

Java: Counting clicks on button

I am trying to do something similiar as cookie clicker, nevertheless it does not work. I have not managed to create a "counter" that shows the amount of clicks. This is what I got hitherto, any ideas?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Stocks implements ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Stocks().createGui();
}
});
}
public void createGui() {
JFrame frame = new JFrame("Clicker");
frame.setSize(175, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
frame.add(panel);
frame.getContentPane().add(panel, BorderLayout.WEST);
GridBagConstraints c = new GridBagConstraints();
JButton button1 = new JButton("Click this");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(40, 40, 40, 40);
panel.add(button1, c);
button1.addActionListener(this);
}
You can have a variable int cnt = 0; inside your Stocks class and everytime someone clicks on the button you increase cnt by one in the actionPerformed method.
As you said, your actionPerformed method is empty, meaning you coded your application to do nothing when the button is clicked.
This answer is assuming you only have one component using that class as ActionListener:
In earlier versions of Java, it would be:
#Override
public void actionPerformed(ActionEvent e) {
counter++;
}
Java 8, however, provides us with Lambda expressions, and allows this to be a lot easier (with less code).
button1.addActionListener(event -> counter++);
You don't need to create an implementation of ActionListener, Java 'll take care of this for you. If you write your code like this, it is even easier if you have more components using that class as ActionListener, since you won't be able to mix them up.
If you need them to call shared parts of code, you can still call methods from within the Lambda expression
button1.addActionListener(event -> {callSharedMethod(); counter++;});
In this example, first the shared method will be called. After that, the counter will be augmented, which will/might only be done from clicking this button.
You should first add a counter as a attribute of your class `Stock``
public class Stocks {
private int counter;
Initialize counter variable with 0:
public static void main(String[] args) {
this.counter = 0;
And then add the action listener to increase the variable:
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
}
});
I'm surprised nobody proposed resolving this by inheritance. The button you want is a JButton but slightly more specialized (it must count the number of clicks performed on itself).
public final class CountButton extends JButton {
private int counter = 0;
public CountButton(String text) {
super(text);
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
}
});
}
public final int getCounter() {
return counter;
}
}

Why won't my .isSelected() method work?

Well what i'm trying to do is change the text of the JRadioButton's when they're selected, i got them to change the color. I know I can do it by putting the code to change the text inside the dedicated event handling method specific to each button, but how do I do it so that I use A DIFFERENT event handling method that just changes the buttons? I already created one but it doesn't work, here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LessonTwenty extends JFrame implements ActionListener{
JRadioButton b1,b2;
JTextArea t1;
JScrollPane s1;
JPanel jp = new JPanel();
public LessonTwenty()
{
b1= new JRadioButton("green");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp.setBackground(Color.GREEN);
}
});
b2= new JRadioButton("red");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp.setBackground(Color.RED);
}
});
//Method to change the text of the JRadion Buttons, what i'm trying to make work
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b1.isSelected()){
b1.setText("Welcome");
}
else if(b2.isSelected()){
b2.setText("Hello");
}
}
};
jp.add(b1);
jp.add(b2);
this.add(jp);
setTitle("Card");
setSize(700,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String [ ] args){
new LessonTwenty();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
if i understand you right, you want do do something like this:
//Method to change the text of the JRadion Buttons, what i'm trying to make work
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b1.isSelected()){
b1.setText("Welcome");
}
else if(b2.isSelected()){
b2.setText("Hello");
}
}
};
b1= new JRadioButton("green");
b1.addActionListener(al);
b2= new JRadioButton("red");
b2.addActionListener(al);
ie. you define one ActionListener which you use in all your objects.
The anonymous object you define in your original code does absolutely nothing, it just creates an ActionListener which nobody can ever access, since it is not assigned to any Button.
Maybe this could help
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1){
b1.setText("Welcome");
} else if(e.getSource() == b2){
b2.setText("Hello");
}
}
};

Java button do the same thing, how do I change this?

Alright, I have a simple java applet with two buttons and a screen. Both the buttons do the same thing. I want to change this. I can't find what it is that changes the action that is performed when either one of the buttons is pressed. They both to the same thing and I don't want this. So my question is how would I change the Inventory button to display "Hello world" instead of a line count?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class projectApplet extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private int lineNumber = 0; // this is just to test
public void init() {
JPanel panel = new JPanel();
textArea = new JTextArea();
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.WHITE);
JScrollPane sp = new JScrollPane(textArea);
panel.add(sp);
Container window = getContentPane();
window.setLayout(new BorderLayout());
window.add(sp,BorderLayout.CENTER);
// this is just to test------------------
JButton b = new JButton("Clik to add a line");
b.addActionListener(this);
window.add(b, BorderLayout.SOUTH);
JButton inventory = new JButton("Inventory");
inventory.addActionListener(this);
window.add(inventory, BorderLayout.NORTH);
//---------------------------------------
}
public void actionPerformed(ActionEvent arg0) {
lineNumber++;
textArea.append("\nLine number: " + lineNumber);
}
public void actionPerformed1(ActionEvent arg0) {
lineNumber++;
textArea.append("RPFL");
}
}
Add a new action listener to it. Typically you can use an anonymous inner class:
inventory.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
textArea.append("Hello, world");
}
});
Just have the one actionPerformed method and then find out which button triggered it.
For example:
public void actionPerformed(ActionEvent arg0) {
if(arg0.getLabel()=="Inventory") // Do the following
if(arg0.getLabel()=="Click to add a new line") // Do the following
}
Note, getLabel() method is deprecated so you'll have to use another... can't remember off the top of my head which you should though... maybe getName(). But this is a simple way to test which button was clicked ;)
You can't do arg0.getSOurce() inside the action performed method to checkout which button has generated this event.

Categories

Resources