Re: Newbie: Whats wrong with this little program?

From: Kozynenko Ganna (gkoz_at_isd.dp.ua)
Date: 03/27/04


Date: Sat, 27 Mar 2004 12:10:45 +0200

Hello, Piet!

It's been several years that I have not been writing in Java, but let's
see...

It'd help if you write exactly what errors you get, but so far I can see
strange things in your program:

1) You are catching an event. Should the type of the event be checked? Or do
you simply want the button to react to all events? I don't remember if with
Java it's different, but common sense suggests, there are many events except
button click (regardless of the language): focus lost, focus gained, mouse
over, right mouse button click etc.

2) Pay very close attention to the line
JTextArea myTextField = new JTextArea(5,20);
This line declares a local variable, and this variable "shadows" your class'
private member, that is, this JTextArea is NOT the same as what you use in
event handler (action listener). Your private member remains uninitialized
and is not added anywhere
I am sure this causes at least part of the errors (you are trying to use an
uninitialized object!!!!)

Regards,
Anna

 P> import javax.swing.*;
 P> import java.awt.*;
 P> import java.awt.event.*;

 P> public class JavaTest extends JFrame {
 P> private JTextArea myTextField;
 P> class myButtonEvent implements ActionListener {
 P> public void actionPerformed(ActionEvent evt) {
 P> java.awt.Toolkit.getDefaultToolkit().beep();
 P> myTextField.setText("Hi there!");
 P> }
 P> }
 P> JavaTest(String title) {
 P> super(title);
 P> JLabel myLabel = new JLabel("Label");
 P> JButton myButton = new JButton("Test");
 P> myButton.addActionListener(new myButtonEvent());
 P> getContentPane().setLayout(new FlowLayout());
 P> getContentPane().add(myLabel);
 P> getContentPane().add(myButton);
 P> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 P> JTextArea myTextField = new JTextArea(5,20);
 P> getContentPane().add(myTextField);
 P> }
 P> public static void main(String[] args) {
 P> JavaTest rahmen = new JavaTest("Test");
 P> rahmen.pack();
 P> rahmen.show();
 P> }
 P> }

 P> I think (or hope) that this error should be easily corrected. Any
 P> help and explanations will be greatly appreciated! Thanx in advance

 P> Peter

With best regards, Kozynenko Ganna. E-mail: gkoz@isd.dp.ua