0

Hi,

I am confused as to all the posts by newbies. If they are new (which I am) how do they know all this code they post? I have a question and it is very basic. All I want to do is to get one JButton to pull up an array. First, I need to get the JButton working. The following code I got from the book "Java for dummies". It will not compile and says that "this" is leaking in the constructor. Here is what I have in code. Could someone please let me know what is wrong. I have taken tutorials but they all seem way advanced for a new person. Is it a matter of memorization? Even if I get the button to work where does the code for the array get placed? I tried to use the code-tags to place this question but I guess they did not work.

package OneButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.*;

public class FirstButton extends JFrame implements actionListener {

   public static void main(String[] args) {

    new FirstButton();

    }
    private  JButton button1;

    public FirstButton()

    {this.setSize (200,100);
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     this.setTitle("Wine");

     JPanel buttonPanel = new JPanel();
     button1 = new JButton("Wine");
     button1.addActionListener(this);
     buttonPanel.add(button1);
     this.add(buttonPanel);
     this.setVisible(true);

}
}

Edited by mike_2000_17: Fixed formatting

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by yancouto
0

I don't usually extend JFrame or implement ActionListener (You forgot to put the first "A" in Upper Case, and Java is case sensitive), but this is what your code could look like

package OneButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.*;

public class FirstButton extends JFrame {

public static void main(String[] args) {
new FirstButton();
}
private JButton button1;

public FirstButton()

{
  //initialize the frame here
button1 = new JButton("Wine");
button1.addActionListener(new ButtonListener());
//more stuff here
}

public class ButtonListener implements ActionListener {
        public void actionPerformed (ActionEvent e) {
               if(e.getsource() == button1) //makes sure that what you clicked is button1
                    {
                           //what happens if the button is clicked
                     }
  }

}



}

And the book you're reading is pretty good :), I read Java All-in-One Desk Reference for Dummies :Dl

Ps. To use code tags for java try. [*code=java] your code [/code*] (Without "*")

Edited by yancouto: Adding something

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.