What is wrong with this.

Hi, i have been programming with java for 2 days and now i am stuck can some one please help me?

It says that i can not use actionlistener with the button, but why?

Thanks in advance

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

publicclass whyimplements ActionListener{

publicstaticvoid main (String[] args){

why gui =new why();

gui.go();

}

publicvoid go(){

Container contentPane;

JFrame frame =new JFrame();

JPanel panel =new JPanel();

panel.setBackground(Color.darkGray);

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JButton button =new JButton("click me");

JButton button2 =new JButton("do not click me");

JTextField field =new JTextField("Tedstt");

button2.addActionListener(field);

panel.add(button);

panel.add(button2);

contentPane.add(field);

frame.getContentPane().add(BorderLayout.EAST, panel);

frame.setSize(400,400);

frame.setVisible(true);

}

publicvoid actionPerformed(ActionEvent event){

JButton button;

button.setText("yrdy");

}

}

[2200 byte] By [Foodmana] at [2007-10-3 2:47:44]
# 1

This:

button2.addActionListener(field);

should be this:

button2.addActionListener(this);

You added the text field as the ActionListener by mistake.

Your actionPerformed method won't compile as is--your button hasn't been initialized. You need to make some of your variables instance variables in the "why" class. And some of the stuff in "go" probably makes more sense in a constructor.

MLRona at 2007-7-14 20:36:31 > top of Java-index,Java Essentials,Java Programming...
# 2
thanks i will try it :)
Foodmana at 2007-7-14 20:36:31 > top of Java-index,Java Essentials,Java Programming...
# 3

Also, the button you create in the actionPerformed method is a completely new button, not the same as teh one you created in the go method. Since it is new and has not been added to the gui, you will not see it.

If you wanted to change the text on the button you have already created then you will need it to be an instance variable of your why class (should be Why) and then delete the JButton button line of code.

floundera at 2007-7-14 20:36:31 > top of Java-index,Java Essentials,Java Programming...