JTextField ActionListener Help

Hallo Guys,
I have an JTextField . when the user inputs the number and clicks the InsertString button i generate that many JTextField for the user to insert some Strings.
if the user enters 10 and clicks the InsertString Button then 10 JTextFields appear. it works fine
but my problem is how to access the text entered in the different JTextFields.
i can access only the last textField
Here is the piece of code
if(cmd.equals("InsertString"))
     if(numvaluesField.getText().equals(""))
     ImageIcon icon = new ImageIcon("Images/warning_large.gif");
     JOptionPane.showConfirmDialog(null,"Please Input the Number of Values and then Press the InsertString Button","Alert",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,icon);
     else
          stringButton.setEnabled(false);
          deleteButton.setEnabled(true);
          Container contentPane = valueFrame.getContentPane();
          GridBagLayout gridbag = new GridBagLayout();
          sub1 = new JPanel(gridbag);
          GridBagConstraints c = new GridBagConstraints();
          GridBagConstraints d = new GridBagConstraints();
          c.anchor = GridBagConstraints.CENTER;
         c.fill = GridBagConstraints.BOTH;
         c.insets = new Insets(5, 5, 5, 5);
         c.weightx = 1.0;
         c.weighty = 1.0;
         try{
          numValue = Integer.parseInt(numvaluesField.getText());
         catch(NumberFormatException exception){};
     if(numvaluesField.equals(""))
          JOptionPane.showConfirmDialog(null,"The number of values field Cannot be NULL","Alert",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE);
     else{
     for(int i = 1; i <= numValue ; i++)
          c.gridx = 2 ;
          c.gridy = i ;
          lengthField.setText(String.valueOf(Integer.parseInt(lengthField.getText()) + 2));
          JLabel stringLabel= new JLabel("String"+i+":");
          sub1.add(stringLabel,c);
          //stringField = new JTextField[numValue];
          stringField = new JTextField(10);
          stringField.addActionListener(this);
          stringField.setToolTipText("Enter the String name for Parameter Acquisition");
          c.gridx = 3;
          c.gridy = i;
          sub1.add(stringField,c);
          d.gridx = 1;
          d.gridy = 0;
          main.add(sub1,GridBagConstraints.RELATIVE);
          contentPane.add(main);
          valueFrame.setContentPane(contentPane);
          valueFrame.pack();
}here is the code where i access the JTextFields
for(int i = 1 ; i <= numValue1 ; i++)
     StringBuffer buff = new StringBuffer();
     buff.append(stringField.getText());     
value = messageString.createStringField(value,buff.toString());
     buff.setLength(0);
}

Hi freedomjava,
Torajirou is right you'r overwrite the reference so the only textfield available is the last one..
For simple example you just think what should be the out put of the following ?? and you should got your mistake..
         int i=0;
         i=1;
         i=100;
         System.out.println("Value of i  = "+i);You should got the last value....

Similar Messages

  • ActionListener Help

    Hi
    I am creating a very basic program that has two buttons and a text field. When any button is clicked, then the text in the text field should change. However, I've run into a problem with the actionPerformed method - it doesn't seem to recognise the names of my buttons i.e. *'+button_name +cannot be resolved'*. So, when I click the button then nothing happens. The code is not very large so I'll provide it below.
    import javax.swing.*;*
    import java.awt.event.;
    import java.awt.*;
    public class SGUI extends JPanel implements ActionListener{
    public SGUI() {
    ImageIcon hello = createImageIcon("images/hello.gif");
    ImageIcon bye = createImageIcon("images/bye.gif");
    JButton sayHello = new JButton(hello);
    JButton sayBye = new JButton(bye);
    JTextField message = new JTextField("What shall I say?");
    message.setBackground(Color.blue);
    message.setForeground(Color.WHITE);
    //Listen for actions on the 2 buttons and text field.
    sayHello.addActionListener(this);
    sayBye.addActionListener(this);
    message.addActionListener(this);
    sayHello.setToolTipText("display greeting");
    sayBye.setToolTipText("display farewell");
    //add components to container using flowLayout
    add(sayHello);
    add(sayBye);
    add(message);
    public void actionPerformed(ActionEvent ae){
    if (ae.getSource()==sayHello){
    message.setText("Hello!");
    } //respond to the button pressed
    protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = SGUI.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("HelloGoodbye");
    //Create and set up the content pane.
    SGUI newContentPane = new SGUI();
    newContentPane.setOpaque(true); //content panes must be opaque
    newContentPane.setBackground(Color.yellow);
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setSize(300, 300);
    frame.setVisible(true);
    //run the program
    public static void main(String[] args) {
    createAndShowGUI();
    }The _{color:#ff0000}red lines{color}_ appear underneath sayBye+ and message in the actionPerformed() method, which results in the actionPerformed method not working - although the actual program still runs*. Please help!
    Edited by: aras298 on May 5, 2008 8:49 AM

    you appear to have a problem of scope: your JButtons are declared and defined in the constructor and have a scope that is confined to the constructor. Anything that's outside of the constructor will thus not be able to "see" these components. One solution: make the buttons declared in the class. You can still construct them in the constructor, but make sure that their scope is the entire class, not just the constructor.
    Also, I recommend that you start getting in the habit of not having your main GUI classes implement the ActionListener interface, but rather using anonymous inner classes, or private inner classes, or stand-alone classes for your actionlisteners. It's much cleaner this way.

  • Help Please Needed for Java Calculator - ActionListener HELP

    Hi. I am constructing a simple Java calculator and need help with the actionlistener and how it could work with my program. I am not too sure how to begin constructing the actionlistener. I would like to know the best and most simple solution to get this program work the way it should, like a real calculator. If anyone can help me, that would be much appreciated.
    package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CalculatorGUI extends JFrame implements ActionListener{
    JTextField screen;
    JButton button7;
    JButton button8;
    JButton button9;
    JButton button4;
    JButton button5;
    JButton button6;
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button0;
    JButton add;
    JButton minus;
    JButton multiply;
    JButton divide;
    JButton equals;
    JButton clear;
    private JTextField m_displayField;
    private boolean m_startNumber = true;
    private String m_previousOp = "=";
    private CalculatorLogic m_logic = new CalculatorLogic();
    public CalculatorGUI() {
    CalculatorGUILayout customLayout = new CalculatorGUILayout();
    getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
    getContentPane().setLayout(customLayout);
    screen = new JTextField("textfield_1");
    getContentPane().add(screen);
    button7 = new JButton("7");
    getContentPane().add(button7);
    button7.addActionListener(this);
    button8 = new JButton("8");
    getContentPane().add(button8);
    button8.addActionListener(this);
    button9 = new JButton("9");
    getContentPane().add(button9);
    button9.addActionListener(this);
    button4 = new JButton("4");
    getContentPane().add(button4);
    button4.addActionListener(this);
    button5 = new JButton("5");
    getContentPane().add(button5);
    button5.addActionListener(this);
    button6 = new JButton("6");
    getContentPane().add(button6);
    button6.addActionListener(this);
    button1 = new JButton("1");
    getContentPane().add(button1);
    button1.addActionListener(this);
    button2 = new JButton("2");
    getContentPane().add(button2);
    button2.addActionListener(this);
    button3 = new JButton("3");
    getContentPane().add(button3);
    button3.addActionListener(this);
    button0 = new JButton("0");
    getContentPane().add(button0);
    button0.addActionListener(this);
    add = new JButton("+");
    getContentPane().add(add);
    add.addActionListener(this);
    minus = new JButton("-");
    getContentPane().add(minus);
    minus.addActionListener(this);
    multiply = new JButton("*");
    getContentPane().add(multiply);
    multiply.addActionListener(this);
    divide = new JButton("/");
    getContentPane().add(divide);
    divide.addActionListener(this);
    equals = new JButton("=");
    getContentPane().add(equals);
    equals.addActionListener(this);
    clear = new JButton("Clear");
    getContentPane().add(clear);
    clear.addActionListener(this);
    setSize(getPreferredSize());
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void actionPerformed(ActionEvent event) {
    public static void main(String args[]) {
    CalculatorGUI window = new CalculatorGUI();
    window.setTitle("Calculator");
    window.pack();
    window.show();
    class CalculatorGUILayout implements LayoutManager {
    public CalculatorGUILayout() {
    public void addLayoutComponent(String name, Component comp) {
    public void removeLayoutComponent(Component comp) {
    public Dimension preferredLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    Insets insets = parent.getInsets();
    dim.width = 421 + insets.left + insets.right;
    dim.height = 494 + insets.top + insets.bottom;
    return dim;
    public Dimension minimumLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    return dim;
    public void layoutContainer(Container parent) {
    Insets insets = parent.getInsets();
    Component c;
    c = parent.getComponent(0);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+8,408,64);}
    c = parent.getComponent(1);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+80,96,56);}
    c = parent.getComponent(2);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+80,96,56);}
    c = parent.getComponent(3);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+80,96,56);}
    c = parent.getComponent(4);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+144,96,56);}
    c = parent.getComponent(5);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+144,96,56);}
    c = parent.getComponent(6);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+144,96,56);}
    c = parent.getComponent(7);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+208,96,56);}
    c = parent.getComponent(8);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+208,96,56);}
    c = parent.getComponent(9);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+208,96,56);}
    c = parent.getComponent(10);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+272,96,56);}
    c = parent.getComponent(11);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+80,72,56);}
    c = parent.getComponent(12);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+144,72,56);}
    c = parent.getComponent(13);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+208,72,56);}
    c = parent.getComponent(14);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+272,72,56);}
    c = parent.getComponent(15);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+336,72,56);}
    c = parent.getComponent(16);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+408,408,72);}
    }

    Yeah, I have a rough idea of what the calculator
    should do, like most people would. Its just that I
    dont know how to implement this in Java. Thats the
    problem. Can anyone provide me with code snippets
    that I can try?No I would rather see you make an effort from what has been discussed here. This is not a Java problem this is a general programming problem.

  • JTextField actionListener

    Hi,
    I'm having quite an issue I hope someone can help me with. I want to add an actionlistener to a textField. But I want it respond not only to when press the return key. I want it to respond as soon as i press any button when the jtextfield is in focus.
    Can anyone help me?

    I think it makes more sense to install a document listener:
    import javax.swing.*;
    import javax.swing.event.*;
    public class DocumentListenerExample implements Runnable, DocumentListener {
        private JTextField field;
        @Override
        public void run() {
            field = new JTextField(40);
            field.getDocument().addDocumentListener(this);
            JFrame f = new JFrame("DocumentListenerExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(field);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        @Override
        public void changedUpdate(DocumentEvent e) {
            reactToTextFieldChange();
        @Override
        public void insertUpdate(DocumentEvent e) {
            reactToTextFieldChange();
        @Override
        public void removeUpdate(DocumentEvent e) {
            reactToTextFieldChange();
        void reactToTextFieldChange() {
            System.out.println("field.text is now " + field.getText());
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new DocumentListenerExample());
    }By the way, Swing questions should be posted to the swing forum.

  • Swing ActionListener help?

    Hi there,
    I'm trying to get to grips with Swing and I'm reasonably comfortable with laying out the GUI now. However, I'm still trying to get to grips with ActionListeners. As I understand it, you can have any old class as an ActionListener as long as it implements the ActionListener interface.....then you can just add this ActionListener to a component using .addActionListener().
    Couple of questions though....
    1. Is it generally bad design to just have a component call <whatever>.addActionListener(this) and then just implement the actionPerformed() method within the same class?
    2. Do you have to define a seperate ActionListener class for each type of component, or can you use one ActionListener for, say, one whole GUI screen? How do you usually organise these things?
    3. Anyone point me towards some decent tutorials on Java Swing event-handling?....preferably not the Sun ones, although if they are regarded as the best, I'll take 'em. :)
    Thanks for your time.

    URgent help need.
    i need to link the page together : by clicking the button on the index page.
    it will show the revelant class file. I have try my ationPerformed method to the actionlistener, it cannot work.
    Thanks in advance.
    // class mtab
    // the tab menu where it display the gui
    import javax.swing.*;
    import java.awt.*;
    public class mtab {
    private static final int frame_height = 480;
    private static final int frame_width = 680;
    public static void main (String [] args){
    JFrame frame = new JFrame ("Mrt Timing System");
    frame.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE);
    frame.setSize(frame_width,frame_height);
    JTabbedPane tp = new JTabbedPane ();
    tp.addTab("Mrt Timing System", new sample());
    frame.setResizable(false);
    frame.getContentPane().add(tp);
    frame.setSize(680,480);
    frame.show();
    // index page
    // class sample
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class sample extends JPanel implements ActionListener
    //button
    private JButton TimingButton;
    private JButton ViewButton;
    private JButton FrequencyButton;
    private JButton calculateButton;
    private CardLayout mycard;
    private JPanel SelectXPanel;
    private JPanel SelectYPanel;
    private JPanel SelectZPanel;
    private JPanel bigFrame, mainPane;
    // constructor
    public sample() {
    super(new BorderLayout());
    //create the object
    //create button and set it
    TimingButton = new JButton("MRT Timing Calculator");
    TimingButton.addActionListener(this);
    ViewButton = new JButton("View First and Last Train");
    ViewButton.addActionListener(this);
    FrequencyButton = new JButton("Show the Train Frequency");
    FrequencyButton.addActionListener(this);
    // Layout
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(3,0));
    buttonPane.add(TimingButton);
    buttonPane.add(ViewButton);
    buttonPane.add(FrequencyButton);
    // Layout the button panel into another panel.
    JPanel buttonPane2 = new JPanel(new GridLayout(0,1));
    buttonPane2.add(buttonPane);
    tfrequency x = new tfrequency();
    fviewl2 y = new fviewl2 ();
    timing z = new timing ();
    JPanel SelectXPanel = new JPanel(new GridLayout(0,1));
    SelectXPanel.add(x);
    JPanel SelectYPanel = new JPanel(new GridLayout(0,1));
    SelectYPanel.add(y);
    JPanel SelectZPanel = new JPanel(new GridLayout(0,1));
    SelectZPanel.add(z);
    // Layout the button by putting in between the rigid area
    JPanel mainPane = new JPanel(new GridLayout(3,0));
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane2);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.setBorder(new TitledBorder("MRT Timing System"));
    // x = new tfrequency();
    // The overall panel -- divide the frame into two parts: west and east.
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    //bigFrame.add(x,BorderLayout.EAST); // this is where i want to link the page
    // this page being the index page. there being nothing to display.
    add(bigFrame);
    //Create the GUI and show it. For thread safety,
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == TimingButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectZPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == ViewButton ){
    JPanel bigFrame = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectYPanel,BorderLayout.EAST);
    add(bigFrame);
    else if (e.getSource() == FrequencyButton ){
    JPanel bigFrame2 = new JPanel(new GridLayout(0,2));
    bigFrame.add(mainPane, BorderLayout.WEST);
    bigFrame.add(SelectXPanel,BorderLayout.EAST);
    add(bigFrame);
    // Train Frequency Page
    // class fviewl2
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Image;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.text.*;
    import javax.swing.border.*;
    class fviewl2 extends JPanel implements ActionListener
    //Labels to identify the fields
    private JLabel stationLabel;
    private JLabel firstLabel;
    private JLabel lastLabel;
    //Strings for the labels
    private static String station = "MRT Station:";
    private static String first = "First Train Time:";
    private static String last = "Last Train Time:";
    //Fields for data entry
    private JFormattedTextField stationField;
    private JFormattedTextField firstField;
    private JFormattedTextField lastField;
    //button
    private JButton homeButton;
    private JButton cancelButton;
    private JButton calculateButton;
    public fviewl2()
    super(new BorderLayout());
    //create the object
    //Create the Labels
    stationLabel = new JLabel(station);
    firstLabel = new JLabel (first);
    lastLabel = new JLabel (last) ;
    //Create the text fields .// MRT Station:
    stationField = new JFormattedTextField();
    stationField.setColumns(10);
    stationField.setBounds(300,300,5,5);
    //Create the text fields // First Train Time:
    firstField = new JFormattedTextField();
    firstField.setColumns(10);
    firstField.setBounds(300,300,5,5);
    //Create the text fields //Last Train Time:
    lastField = new JFormattedTextField();
    lastField.setColumns(10);
    lastField.setBounds(300,300,5,5);
    //Tell accessibility tools about label/textfield pairs, matching label for the field
    stationLabel.setLabelFor(stationField);
    firstLabel.setLabelFor(firstField);
    lastLabel.setLabelFor(lastField);
    //create button and set it
    homeButton = new JButton("Home");
    //homeButton.addActionListener(this);
    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(this);
    calculateButton = new JButton("Get Time");
    // Layout
    //MRT Station Label // insert into the panel
    JPanel StationPane = new JPanel(new GridLayout(0,1));
    StationPane.add(stationLabel);
    //MRT Station input field // insert into the panel
    JPanel StationInput = new JPanel(new GridLayout(0,1));
    StationInput.add(stationField);
    //Get Time Button // insert into the panel
    JPanel GetTime = new JPanel(new GridLayout(0,1));
    GetTime.add(calculateButton);
    //Lay out the labels in a panel.
    JPanel FlabelL = new JPanel(new GridLayout(0,1));
    FlabelL.add(firstLabel);
    FlabelL.add(lastLabel);
    // Layout the fields in a panel
    JPanel FFieldL = new JPanel(new GridLayout(0,1));
    FFieldL.add(firstField);
    FFieldL.add(lastField);
    //Lay out the button in a panel.
    JPanel buttonPane = new JPanel(new GridLayout(1,0));
    buttonPane.add(homeButton);
    buttonPane.add(cancelButton);
    // Layout all components in the main panel
    JPanel mainPane = new JPanel(new GridLayout(4,2));
    mainPane.add(StationPane);
    mainPane.add(StationInput);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(GetTime);
    mainPane.add(FlabelL);
    mainPane.add(FFieldL);
    mainPane.add(Box.createRigidArea(new Dimension(0,1)));
    mainPane.add(buttonPane);
    mainPane.setBorder(new TitledBorder("View First and Last Train"));
    JPanel leftPane = new JPanel(new GridLayout(1,0));
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    leftPane.add(mainPane);
    leftPane.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel hahaFrame = new JPanel(new GridLayout(0,1));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    hahaFrame.setBorder(BorderFactory.createEmptyBorder(30, 10, 80, 150));
    hahaFrame.add(Box.createRigidArea(new Dimension(0,1)));
    JPanel bigFrame = new JPanel();
    bigFrame.add(hahaFrame, BorderLayout.NORTH);
    bigFrame.add(leftPane, BorderLayout.CENTER);
    add(bigFrame, BorderLayout.CENTER);
    //Create the GUI and show it. For thread safety,
    private void cancelButtonClicked()
    stationField.setText("");
    firstField.setText("");
    lastField.setText("");
    public void actionPerformed (ActionEvent e){
    if (e.getSource() == cancelButton){
    cancelButtonClicked();
    }

  • JTextField array help

    Hey guys,
    I'm working on a java GUI right now and I've come up with a problem, hopefully you guys can help.
    I have a page that contains 50 text fields in 2 columns, so instead of making 50 lines of text field code, I decided to make an array of text fields and a for loop to cycle through each one (setting sizes, colors, editable, etc). Now the problem I'm running into is I will later down the road like to setText in these but it will be very cumbersome to have to call them by the arrayName[index #]. Just so I can better express what I mean heres is how I have to call each text field right now:
    arrayName[0].setText("1");
    arrayName[1].setText("2");
    This is how I'd like to be able to call each field:
    1stTextField.setText("1");
    2ndTextField.setText("2");
    Is there anyway I can make it so I can make an array of JTextFields and still be able to call an individual text field inside the array by name? If not, is there a way to point to another variable such as making
    1stTextField = arrayName[0] ;
    2ndTextField = arrayName[1];
    Thanks for the help guys.

    50 text fields in 2 columns... why not just use a JTable?
    Is there anyway I can make it so I can make an array of JTextFields and still be able to call an individual text field inside the array by name?Try a HashMap
    is there a way to point to another variable such as making
    1stTextField = arrayName[0] ;
    2ndTextField = arrayName[1]; Yes, exactly as you coded it up

  • Button / actionlistener help

    Hi,
    I'm slowly writing a applet, that when you press a button(a.k.a btnOn), it gets replaced with another button (a.k.a btnOff) and vice versa. I would appreciate any help that anyone would give. This is part of a game that i am trying to make, with very little success. So any help would be appreciated. Thanks.
    p.s. i know this is probably a really easy question, but for some reason i just can't figure it out.
    thanks

    Well i tried to change michael's code, i don't know if i did it right though... i probably didn't
    but here you go:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    * Class l0gixGame - write a description of the class here
    * @author (your name)
    * @version (a version number)
    public class logixGame extends JApplet implements ActionListener {
        JButton btnOn,btnOff;
        private static final ImageIcon image[]={
            new ImageIcon("On.png"),
            new ImageIcon("Off.png")};
       public void init(){
           /** creates the control panel, sets the size,locaiton and the background
            * colour
           JPanel controlPanel = new JPanel();
           controlPanel.setSize(new Dimension(400,275));
           controlPanel.setLocation(10,100);
           controlPanel.setBackground(Color.gray);
           /** creates the background panel, sets the size,locaiton and the
           * background color
           JPanel backGround = new JPanel();
           backGround.setSize(new Dimension(400,400));
           backGround.setLocation(0,0);
           backGround.setBackground(Color.gray);
           /** creates the play panel, sets the size,locaiton and the
           * background color
           JPanel playPanel = new JPanel();
           playPanel.setSize(new Dimension(400,275));
           playPanel.setLocation(500,200);
           playPanel.setBackground(Color.orange);
           /** creates the layout for the play panel, and the control panel
            * creates the content pane, and the three panels to the content pane
            * and sets the dimensions for the content pane
           controlPanel.setLayout(new GridLayout(8,12));
           playPanel.setLayout(new GridLayout(8,12));
           Container cp = getContentPane();
           cp.setSize(new Dimension(5000,5000));
           cp.add(controlPanel);
           cp.add(playPanel);
           cp.add(backGround);
           /**initialize the onbutton and the offbutton with the related graphics*/
           ImageIcon on = new ImageIcon(getImage(getCodeBase(),
           "On.png"));
           ImageIcon off = new ImageIcon(getImage(getCodeBase(),
           "Off.png"));
           ArrayList<String> control = new ArrayList<String>();
           ArrayList<String> play = new ArrayList<String>();
           /** Randimization of control panel and play panel*/
           /**1=off 2=on*/
           int row,column,i,x,y;
             for( column = 0; column <= 8; column = column+1)
                    for (row = 0; row <= 14; row = row+1)
                        i = 1;
                        y = row * 50;
                        x = column * 50;
                        if ( (column % 2) == (row % 2) )
                            Random r = new Random();
                            int n = r.nextInt();
                            if(n % 2 == 0){
                                 JLabel btn2 = new JLabel(off);
                                controlPanel.add(btn2);
                                control.add("1");
                                JButton btnOn = new JButton(on);
                                btnOn.setBackground(Color.orange);
                                playPanel.add(btnOn);
                                play.add("2");
                            else{
                                JLabel btn2 = new JLabel(on);
                                controlPanel.add(btn2);
                                control.add("2");
                                JButton btnOff = new JButton(off);
                                btnOff.setBackground(Color.orange);
                                playPanel.add(btnOff);
                                play.add("1");
                        else
                            Random r = new Random();
                            int n = r.nextInt();
                            if(n % 3 == 0){
                                JLabel btn2 = new JLabel(on);
                                controlPanel.add(btn2);
                                control.add("2");
                                JButton btnOn = new JButton(on);
                                btnOn.setBackground(Color.orange);
                                playPanel.add(btnOn);
                                play.add("2");
                String controlString =""+ control;
                String playString =""+ play;
                if(controlString.compareTo(playString)==0){
                    JLabel winner = new JLabel("Winner!");
                    backGround.add(winner);
    public void actionPerformed (ActionEvent event) {
       if(btn.getIcon().equals(on))
           btn.setIcon(off);
        else
            btn.setIcon(on);
    }what is the difference between your way of getting the image and mine???
    3) for the moment, i don't really care, i just want to get the individual buttons working, and test out my strategy for winning, even though i am on a time restraint, i think it would be better to hand it in with individual buttons working, then none of the buttons working...
    right know i get a "cannot find symbol -- variable on" in my actionlistener is there a specific reason???
    thanks for the help i do really really appreciate it..... you don't know how much..
    p.s. i told you i wasn't very good at this

  • Buttons and actionlistener help.

    the following code has 2 buttons, how would i use a button to get me differnt graphics but inside the same window,
    say i clicked next the graphics would be slightly altered which I will do but it wont open a new window it will be in the same window, but different shapes.
    I am having trouble with action listeners and really need help in how they work iv read up but dont understand, and how this would be implemented for this.
    much help would be appreciated.
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class square extends JPanel
        public square()
            setPreferredSize(new Dimension(800, 700));
            int eb = 80;
            setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            setLayout(new BorderLayout(5, 10));
           JPanel buttonPanel = createButtonPanel();
             add(buttonPanel, BorderLayout.SOUTH);
        private JPanel createButtonPanel()
            JPanel bp = new JPanel();
            bp.setOpaque(false);
                   JButton btn2 = new JButton("<-  Back Step ");
                    JButton btn = new JButton("Next Step   ->");
                    bp.add(btn2);
                    bp.add(btn);
            return bp;
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            Rectangle2D rect = new Rectangle2D.Double(250, 150, 100, 100);
            Rectangle2D     rect2 = new Rectangle2D.Double(400, 150, 100, 100);
             Rectangle2D     rect3 = new Rectangle2D.Double(550, 150, 100, 100);
             Rectangle2D     rect4 = new Rectangle2D.Double(250, 300, 100, 100);
             Rectangle2D     rect5 = new Rectangle2D.Double(400, 300, 100, 100);
             Rectangle2D     rect6 = new Rectangle2D.Double(550, 300, 100, 100);
             Rectangle2D     rect7 = new Rectangle2D.Double(250, 450, 100, 100);
             Rectangle2D     rect8 = new Rectangle2D.Double(400, 450, 100, 100);
             Rectangle2D     rect9 = new Rectangle2D.Double(550, 450, 100, 100);
             g.drawString("b0,0", 300, 130);
            g.drawString("b1,0", 300, 110);
             g.drawString("b2,0", 300, 90);
                 g.drawString("b0,1", 450, 110);
            g.drawString("b1,1", 450, 90);
            g.drawString("b2,1", 450, 70);
                 g.drawString("b0,2", 600, 90);
            g.drawString("b1,2", 600, 70);
            g.drawString("b2,2", 600, 50);
             g.drawString("a0,0", 200, 200);
            g.drawString("a1,0", 150, 200);
             g.drawString("a2,0", 100, 200);
                 g.drawString("a0,1", 150, 350);
            g.drawString("a1,1", 100, 350);
            g.drawString("a2,1", 50, 350);
                   g.drawString("a0,2", 100, 500);
            g.drawString("a1,2", 50, 500);
            g.drawString("a2,2", 15, 500);
            g2.setPaint(Color.black);
            g2.draw(rect);
            g2.draw(rect);
              g2.draw(rect2);
             g2.draw(rect3);
              g2.draw(rect4);
             g2.draw(rect5);
              g2.draw(rect6);
             g2.draw(rect7);
              g2.draw(rect8);
              g2.draw(rect9);
            Stroke oldStroke = g2.getStroke();
            g2.setStroke(new BasicStroke(5));
            g2.setStroke(oldStroke);
        private static void createAndShowUI()
            JFrame frame = new JFrame("Matrix Multiplication - Step by Step ");
            frame.getContentPane().add(new square());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

    ok I had a look over it, I got this
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class square extends JPanel implements ActionListener
        public square()
            setPreferredSize(new Dimension(800, 700));
            int eb = 80;
            setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            setLayout(new BorderLayout(5, 10));
           JPanel buttonPanel = createButtonPanel();
             add(buttonPanel, BorderLayout.SOUTH);
      public void actionPerformed(ActionEvent e) {
            System.out.println("hello");
        private JPanel createButtonPanel()
            JPanel bp = new JPanel();
            bp.setOpaque(false);
                   JButton btn2 = new JButton("<-  Back Step ");
                    JButton btn = new JButton("Next Step   ->");
                    bp.add(btn2);
                    bp.add(btn);
             btn.addActionListener(this);
            return bp;
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            Rectangle2D rect = new Rectangle2D.Double(250, 150, 100, 100);
            Rectangle2D     rect2 = new Rectangle2D.Double(400, 150, 100, 100);
             Rectangle2D     rect3 = new Rectangle2D.Double(550, 150, 100, 100);
             Rectangle2D     rect4 = new Rectangle2D.Double(250, 300, 100, 100);
             Rectangle2D     rect5 = new Rectangle2D.Double(400, 300, 100, 100);
             Rectangle2D     rect6 = new Rectangle2D.Double(550, 300, 100, 100);
             Rectangle2D     rect7 = new Rectangle2D.Double(250, 450, 100, 100);
             Rectangle2D     rect8 = new Rectangle2D.Double(400, 450, 100, 100);
             Rectangle2D     rect9 = new Rectangle2D.Double(550, 450, 100, 100);
             g.drawString("b0,0", 300, 130);
            g.drawString("b1,0", 300, 110);
             g.drawString("b2,0", 300, 90);
                 g.drawString("b0,1", 450, 110);
            g.drawString("b1,1", 450, 90);
            g.drawString("b2,1", 450, 70);
                 g.drawString("b0,2", 600, 90);
            g.drawString("b1,2", 600, 70);
            g.drawString("b2,2", 600, 50);
             g.drawString("a0,0", 200, 200);
            g.drawString("a1,0", 150, 200);
             g.drawString("a2,0", 100, 200);
                 g.drawString("a0,1", 150, 350);
            g.drawString("a1,1", 100, 350);
            g.drawString("a2,1", 50, 350);
                   g.drawString("a0,2", 100, 500);
            g.drawString("a1,2", 50, 500);
            g.drawString("a2,2", 15, 500);
            g2.setPaint(Color.black);
            g2.draw(rect);
            g2.draw(rect);
              g2.draw(rect2);
             g2.draw(rect3);
              g2.draw(rect4);
             g2.draw(rect5);
              g2.draw(rect6);
             g2.draw(rect7);
              g2.draw(rect8);
              g2.draw(rect9);
            Stroke oldStroke = g2.getStroke();
            g2.setStroke(new BasicStroke(5));
            g2.setStroke(oldStroke);
        private static void createAndShowUI()
            JFrame frame = new JFrame("Matrix Multiplication - Step by Step ");
            frame.getContentPane().add(new square());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }it produces hello once I click the button, but how would I produce the same frame once the button is clicked, not a new frame, the same one iv got with slight adjustments inside it..which i will do.

  • JTextField actionListener does not work

    I am writing an application, and I am using Swing and consequently JTextFields. There is a JTextField whose actionListener works when I use the compiling environment to run the application, but it is not working when I run it from a piece of code written in Visual Basic. All the others JTextFields work properly.
    Any idea coming up?
    May it be any conflict with Microsoft?

    Veena,
    Always mention your JDev version.
    When used in combination, the actionListener is either ignored or the popwarning.show does not work.Can you elaborate the above? Does this happen everytime? Can you also check what is the value for validator.addWarningIfCityNotApproved() - you can run the app in Debug mode to see where exactly it fails ?
    -Arun

  • Tabset actionlistener help

    Could someone please tell me how to add an actionlistener to a tabset?
    I've tried this in init():
            Class[] args = new Class[] { ActionEvent.class };
            MethodBinding binding = createBinding("#{MyPage.tabClicked}", args);
            getTabSet1().setActionListener(binding);with a createBinding of
       private MethodBinding createBinding(String expr, Class[] args) {
            ApplicationFactory factory = (ApplicationFactory)
            FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
            Application app = factory.getApplication();
            return app.createMethodBinding(expr, args);
        }and a listener like this:
       public void tabClicked(ActionEvent event) {
            String selectedTabId = getTabSet1().getSelected();
            info(selectedTabId);
         }This builds and runs ok, but the listener never gets called. I don't see the info() message, and a breakpoint set in the listener never gets hit.
    I'm not sure this is the correct way to go about this. There is an actionListener property in the properties for tabsets, but it just brings up a dialog with a prompt:
    Method binding representing a method that receives action from this component.
    and a textarea to start typing in. If this is the preferred method, how do I go about using it?

    OK, I've researched more, and still no success.
    Apparently, the correct way to do this is to enter the binding method into the actionlistener property of the tabset. Here's what I put:
    #{myPage.tabClicked}
    This creates a nice entry in my .jsp file.
    I then still have the same tabClicked method as above.
    When I run it, I get an exception:
    Exception Details: javax.faces.el.MethodNotFoundException
      tabClicked: myApp.myPage.tabClicked(javax.faces.event.ActionEvent)I also notice that the tabset UI doesn't support addActionListener(), but has a method setActionListener(). This makes me wonder.
    Incidentally, I also tried creating a class that implements actionListener, and instantiating such a class in my page, but that worked just as poorly.

  • More help for a newbie please!

    hi everyone
    ive got a list selection listener set up for my view class
    this list shows names retrieved, this has been done by the following
    for (int i=0;i < data.size(); i++)
    Person aPerson = (Person)data.get(i);
    // Compose a string for each object.
    String personNameString = aPerson.getSurname() + ", " + aPerson.getName();
    // Put string into array.
    listArray=personNameString;
    listModel.addElement(listArray[i]);�
    what im stuck on how to do is to select a name from the list and have other data like
    getLicenceNo() or getDateOfBirth() to be shown on jtextfields
    any help would be appreciated... the closest i can get is to have something like this in the listActionListenerameList.addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent event)
    String d1String = aPerson.getName();
    String d2String = aPerson.getSurname();
    String d3String = aPerson.getLicenceNo();
    Object selectedValue = nameList.getSelectedValue();
    licenceField.setText(selectedValue.toString());
    validate();
    but all i get is the terminal window coming up with lots of error messages under NullPointerException

    this is the error that comes up under terminal window upon clicking a name in jlist
    java.lang.NullPointerException
         at View$3.valueChanged(View.java:102)
         at javax.swing.JList.fireSelectionValueChanged(JList.java:1321)
         at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1335)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:167)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:214)
         at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:402)
         at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:411)
         at javax.swing.DefaultListSelectionModel.setSelectionInterval(DefaultListSelectionModel.java:435)
         at javax.swing.JList.setSelectionInterval(JList.java:1608)
         at javax.swing.plaf.basic.BasicListUI$MouseInputHandler.adjustFocusAndSelection(BasicListUI.java:1333)
         at javax.swing.plaf.basic.BasicListUI$MouseInputHandler.mousePressed(BasicListUI.java:1295)
         at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:222)
         at java.awt.Component.processMouseEvent(Component.java:5097)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3195)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    java.lang.NullPointerException
         at View$3.valueChanged(View.java:102)
         at javax.swing.JList.fireSelectionValueChanged(JList.java:1321)
         at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1335)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:157)
         at javax.swing.DefaultListSelectionModel.setValueIsAdjusting(DefaultListSelectionModel.java:554)
         at javax.swing.JList.setValueIsAdjusting(JList.java:1675)
         at javax.swing.plaf.basic.BasicListUI$MouseInputHandler.mouseReleased(BasicListUI.java:1371)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

  • Help on 2 error messages / code request please

    Why am I getting this error message about an abstract when I'm not declearing one.
    error messages I'm getting below -----------
    .\LkList.java:26: Method LinkedList getList() requires a method body. Otherwise declare it as abstract.
    public LinkedList getList();
    DCalc.java:10: class LkList is an abstract class. It can't be instantiated.
    LkList Expression =new LkList(exp);
    code below ------------------------------
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    class JCal extends JFrame implements KeyListener
         JLabel answer, expression;
         JButton b1, b2, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19,
              b20, b21, b22, b23, b24, b25, b26, b27;
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem, menuItem1;
         LkList equation;
         String exp="";
         String ans="";
         double memory=0;
         public JCal()
         {     super("Nicks Swing Calculator");
    //------------------------- labels ---------------------------------------------
              answer = new JLabel(" 0 "); //Answer Lable
              answer.setBounds (20, 20, 220, 30);
              answer.setBorder (BorderFactory.createLoweredBevelBorder());
              answer.setBackground (Color.pink);
    answer.setHorizontalAlignment (SwingConstants.RIGHT);
              expression = new JLabel(" 0 "); // Expression Lable
              expression.setBounds (20, 55, 220, 30);
              expression.setBorder (BorderFactory.createLoweredBevelBorder());
              expression.setBackground (Color.white);
    //------------------------- menu -------------------------------------------------
              menuBar = new JMenuBar();
              setJMenuBar (menuBar);
              menu = new JMenu ("File");
              menuItem = new JMenuItem (" Help", new ImageIcon("help.gif"));
              menuItem1 = new JMenuItem (" Splash Page");
              menuItem.addActionListener(new ActionListener() // Help menu
              {     public void actionPerformed(ActionEvent e)
                   {     new JHelp();
    menuItem1.addActionListener(new ActionListener() // Splash Page
              {     public void actionPerformed(ActionEvent e)
                   {     new JSplash();
    //------------------------ buttons ------------------------------------------------
              JButton b1 = new JButton (new ImageIcon ("mc.gif")); // MR button
              b1.setBounds(20, 100, 55, 50);
              JButton b2 = new JButton (new ImageIcon ("mr.gif")); // MC button
              b2.setBounds(75, 100, 55, 50);
    JButton b3 = new JButton (new ImageIcon ("ms.gif")); // MS button
              b3.setBounds(130, 100, 55, 50);
    JButton b4 = new JButton (new ImageIcon ("mplus.gif")); // M+ button
              b4.setBounds(185, 100, 55, 50);
              JButton b5 = new JButton (new ImageIcon ("seven.gif")); // 7 button
              b5.setBounds(20, 170, 55, 50);
              JButton b6 = new JButton (new ImageIcon ("eight.gif")); // 8 button
              b6.setBounds(75, 170, 55, 50);
              JButton b7 = new JButton (new ImageIcon ("nine.gif")); // 9 button
              b7.setBounds(130, 170, 55, 50);
    JButton b8 = new JButton (new ImageIcon ("div.gif")); // divide button
              b8.setBounds(185, 170, 55, 50);
              JButton b9 = new JButton (new ImageIcon ("four.gif")); // 4 button
              b9.setBounds(20, 220, 55, 50);
              JButton b10 = new JButton (new ImageIcon ("five.gif")); // 5 button
              b10.setBounds(75, 220, 55, 50);
              JButton b11 = new JButton (new ImageIcon ("six.gif")); // 6 button
              b11.setBounds(130, 220, 55, 50);
              JButton b12 = new JButton (new ImageIcon ("times.gif")); // times button
              b12.setBounds(185, 220, 55, 50);
    JButton b13 = new JButton (new ImageIcon ("one.gif")); // 1 button
              b13.setBounds(20, 270, 55, 50);
              JButton b14 = new JButton (new ImageIcon ("two.gif")); // 2 button
              b14.setBounds(75, 270, 55, 50);
              JButton b15 = new JButton (new ImageIcon ("three.gif")); // 3 button
              b15.setBounds(130, 270, 55, 50);
              JButton b16 = new JButton (new ImageIcon ("minus.gif")); // minus button
              b16.setBounds(185, 270, 55, 50);
              JButton b17 = new JButton (new ImageIcon ("zero.gif")); // 0 button
              b17.setBounds(20, 320, 55, 50);
              JButton b18 = new JButton (new ImageIcon ("neg.gif")); // negitive button
              b18.setBounds(75, 320, 55, 50);
              JButton b19 = new JButton (new ImageIcon ("dot.gif")); // decimal button
              b19.setBounds(130, 320, 55, 50);
              JButton b20 = new JButton (new ImageIcon ("add.gif")); // addition button
              b20.setBounds(185, 320, 55, 50);
              JButton b21 = new JButton (new ImageIcon ("left.gif")); // left bracket button
              b21.setBounds(20, 375, 110, 35);
              JButton b22 = new JButton (new ImageIcon ("right.gif")); // right bracket button
              b22.setBounds(130, 375, 110, 35);
              JButton b23 = new JButton (new ImageIcon ("equals.gif")); // equals button
              b23.setBounds(20, 415, 220, 35);
    JButton b24 = new JButton (new ImageIcon ("clear.gif")); // clear button
              b24.setBounds(20, 460, 55, 50);
              JButton b25 = new JButton (new ImageIcon ("ce.gif")); // ce button
              b25.setBounds(75, 460, 55, 50);
              JButton b26 = new JButton (new ImageIcon ("sqrt.gif")); // sqrt button
              b26.setBounds(130, 460, 55, 50);
              JButton b27 = new JButton (new ImageIcon ("percent.gif")); // % button
              b27.setBounds(185, 460, 55, 50);
              //------------------- adding everything on the pane -------------------
              Container contentPane = getContentPane();
              contentPane.setLayout(null);
              // the default layout is BorderLayout
              contentPane.add(b1); // adds buttons
              contentPane.add(b2);
              contentPane.add(b3);
              contentPane.add(b4);
              contentPane.add(b5);
              contentPane.add(b6);
              contentPane.add(b7);
              contentPane.add(b8);
              contentPane.add(b9);
              contentPane.add(b10);
              contentPane.add(b11);
              contentPane.add(b12);
              contentPane.add(b13);
              contentPane.add(b14);
              contentPane.add(b15);
              contentPane.add(b16);
              contentPane.add(b17);
              contentPane.add(b18);
              contentPane.add(b19);
              contentPane.add(b20);
              contentPane.add(b21);
              contentPane.add(b22);
              contentPane.add(b23);
              contentPane.add(b24);
              contentPane.add(b25);
              contentPane.add(b26);
              contentPane.add(b27);
              contentPane.add(answer); // adds answer label
              contentPane.add(expression); // adds expression lable
              menuBar.add(menu); // adds menu
              menu.add(menuItem); // adds menu item "Help"
              menu.add(menuItem1); // adds menu item "Splash Page"
    //------------ button functions ---------------------------------------
              b1.addActionListener(new ActionListener()          // MR
              {     public void actionPerformed(ActionEvent e)
                   {     String TempMemory="";
                        answer.setText(TempMemory.valueOf(memory)); }});
              b2.addActionListener(new ActionListener()          //Mc
              {     public void actionPerformed(ActionEvent e)
                   {     memory=0; }});
              b3.addActionListener(new ActionListener()          //M-
              {     public void actionPerformed(ActionEvent e)
                   {     Double DblTemp=new Double(answer.getText());
                        double dblTemp=DblTemp.doubleValue();
                        memory=memory-dblTemp; }});
              b4.addActionListener(new ActionListener()          //M+
              {     public void actionPerformed(ActionEvent e)
                   {     Double DblTemp=new Double(answer.getText());
                        double dblTemp=DblTemp.doubleValue();
                        memory=memory+dblTemp; }});
    b5.addActionListener(new ActionListener() // Seven
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"7";
                        expression.setText(exp); }});
              b5.addKeyListener(this);
              b6.addActionListener(new ActionListener() // Eight
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"8";
                        expression.setText(exp); }});
              b6.addKeyListener(this);
              b7.addActionListener(new ActionListener() // Nine
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"9";
                        expression.setText(exp); }});
              b7.addKeyListener(this);
              b8.addActionListener(new ActionListener()          // Divide
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"/";
                        expression.setText(exp); }});
              b8.addKeyListener(this);
              b9.addActionListener(new ActionListener() // Four
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"4";
                        expression.setText(exp); }});
              b9.addKeyListener(this);
              b10.addActionListener(new ActionListener() // Five
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"5";
                        expression.setText(exp); }});
              b10.addKeyListener(this);
              b11.addActionListener(new ActionListener() // Six
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"6";
                        expression.setText(exp); }});
              b11.addKeyListener(this);
              b12.addActionListener(new ActionListener()     // Times
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"*";
                        expression.setText(exp); }});
              b12.addKeyListener(this);
              b13.addActionListener(new ActionListener() // One
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"1";
                        expression.setText(exp); }});
              b13.addKeyListener(this);
              b14.addActionListener(new ActionListener() // Two
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"2";
                        expression.setText(exp); }});
              b14.addKeyListener(this);
              b15.addActionListener(new ActionListener() // Three
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"3";
                        expression.setText(exp); }});
              b15.addKeyListener(this);
              b16.addActionListener(new ActionListener()          // Minus
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"-";
                        expression.setText(exp); }});
              b16.addKeyListener(this);
              b17.addActionListener(new ActionListener() // Zero
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"0";
                        expression.setText(exp); }});
              b17.addKeyListener(this);
              b18.addActionListener(new ActionListener() // negative
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"-";
                        expression.setText(exp); }});
              b18.addKeyListener(this);
              b19.addActionListener(new ActionListener()          // Decimal
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+".";
                        expression.setText(exp); }});
              b19.addKeyListener(this);
              b20.addActionListener(new ActionListener()          // Addition
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"+";
                        expression.setText(exp); }});
              b20.addKeyListener(this);
              b21.addActionListener(new ActionListener()     // Left Bracket
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+"(";
                        expression.setText(exp); }});
              b21.addKeyListener(this);
              b22.addActionListener(new ActionListener()          // Right Bracket
              {     public void actionPerformed(ActionEvent e)
                   {     exp=exp+")";
                        expression.setText(exp); }});
              b22.addKeyListener(this);
              b23.addActionListener(new ActionListener() // Equals
              {     public void actionPerformed(ActionEvent e)
                   {     LkList equation = new LkList();
                        equation.ProcessExpress();
                        ans=equation.getAns();
                        answer.setText(ans);
                        exp="";
                        ans="";     }});
              b23.addKeyListener(this);
              b24.addActionListener(new ActionListener()          // Clear
              {     public void actionPerformed(ActionEvent e)
                   {     exp="";
                        ans="";
                        expression.setText(exp);
                        answer.setText(ans); }});
              b25.addActionListener(new ActionListener()          // Clear Entry
              {     public void actionPerformed(ActionEvent e)
                   {     exp="";
                        ans="";
                        expression.setText(exp);
                        answer.setText(ans); }});
              addWindowListener( new WindowAdapter()
                        {     public void windowClosing(WindowEvent e)
                             {     System.exit(0);
              this.setBounds(10, 10, 270, 600);
              this.show();
         public static void main(String[] args)
         {     new JCal();
    public void keyReleased(KeyEvent evt){}
         public void keyTyped(KeyEvent evt) {}
         public void keyPressed(KeyEvent evt)
         {     char x=evt.getKeyChar();
              switch(x)
              {     case '0': exp=exp+"0";
                        expression.setText(exp);
                        break;
                   case '1': exp=exp+"1";
                        expression.setText(exp);
                        break;
                   case '2': exp=exp+"2";
                        expression.setText(exp);
                        break;
                   case '3': exp=exp+"3";
                        expression.setText(exp);
                        break;
                   case '4': exp=exp+"4";
                        expression.setText(exp);
                        break;
                   case '5': exp=exp+"5";
                        expression.setText(exp);
                        break;
                   case '6': exp=exp+"6";
                        expression.setText(exp);
                        break;
                   case '7': exp=exp+"7";
                        expression.setText(exp);
                        break;
                   case '8': exp=exp+"8";
                        expression.setText(exp);
                        break;
                   case '9': exp=exp+"9";
                        expression.setText(exp);
                        break;
                   case '+': exp=exp+"+";
                        expression.setText(exp);
                        break;
                   case '-': exp=exp+"-";
                        expression.setText(exp);
                        break;
                   case '*': exp=exp+"*";
                        expression.setText(exp);
                        break;
                   case '/': exp=exp+"/";
                        expression.setText(exp);
                        break;
                   case '.': exp=exp+".";
                        expression.setText(exp);
                        break;
                   case '(': exp=exp+"(";
                        expression.setText(exp);
                        break;
                   case ')': exp=exp+")";
                        expression.setText(exp);
                        break;
                   default: break;
    // ================================= equation =============================
    class Equation
    {     private double nbr1;
         private double nbr2;
         private char op;
         private double answer;
         private String StrNum1="";
         private String StrNum2="";
         private String StrOper="";
         private String StrAns="";
         //Constructor
         Equation(String number1, String number2, String operator)
         {     StrNum1 = number1;
              StrNum2 = number2;
              StrOper = operator;
              convert();
         public double getNum1() {return nbr1;}
         public double getNum2() {return nbr2;}
         public char getOp() {return op;}
         private void convert()
         {     Double temp=new Double(StrNum1);
              nbr1=temp.doubleValue();
              temp=new Double(StrNum2);
              nbr2=temp.doubleValue();
              op=StrOper.charAt(0);
         private void convertAnswer()
         {     StrAns=StrAns.valueOf(answer);
         public String toString()
         {     return StrAns;
         public void calculate()
         {     switch (op)
              {     case '+': answer=nbr1+nbr2;
                        break;
                   case '-': answer=nbr1-nbr2;
                        break;
                   case '*': answer=nbr1*nbr2;
                        break;
                   case '/': answer=nbr1/nbr2;
                        break;
              convertAnswer();
    // =============================== linked list ================================
    class LkList
    {  char[] operator = {'+','-','*','/','(',')'}; // operators used
    LinkedList Express = new LinkedList(); // Linked list of expression
    String StrExp = null;
    String oper = ""; // operator
    String number1 = ""; // first number used in expression
    String number2 = ""; // second number used in expression
    String answer = ""; // answer of expression
    Exp TempExp; // Temporary expression
    String Temp;
    // Constructor
    LkList (String e)
    { StrExp = e;
         formList (); // expression turn into liked list nodes
         trimList (); // remove spaces from linked list expression
    public String toString()
         { return Express.toString();
    public LinkedList getList();
         { return Express;
    public String getAns()
         { return Express.get(0).toString();
    public void ProcessExpress() // removing brackets
         {  removeBrack();
    private void formList()
    {  int j = 0;
    boolean lastOper = true;
         for (j = 0 ; j < Express.length(); j++ )
    {  if (!(belongTo(operator, StrExp.charAt (j))))
              {  Temp = Temp + StrExp.charAt (j);
         lastOperator = false;
         if (belongTo(operator, StrExp.charAt (j)))
         {   if ((StrExp.charAt (j) =='-') && (lastOperator))
              {   Temp = "-";
         lastoperator = false;
              else
              {   Express.add (Temp);
              Temp = "";
                   Temp = Temp + StrExp.charAt (j);
                   Express.add (Temp);
                   Temp = "";
                   if (StrExp.charAt (j) == ')')
                   {  lastOperator = false;
                   else
                   {   lastOperator = true;
         Express.add (Temp);
         Temp = "";
    private void trimlist ()
    {   int sp = 0;
    while ((sp !=-1))
    {  sp = Express.indexOf ("");
         if (sp !=-1)
         {  Express.remove (sp);
    private static boolean belongTo (char[] ar, char c)
    {  for (int k = 0; k < ar.length; k++)
         {  if (c == ar[k]) return true;
    return false;
    private boolean findBrack ()
    {  if (Express.contains (")"))
    {  return true;
    return false;
    private void removePoints (int pt1, int pt2 )
    {  int range = (pt2 - pt1);
    for (int j = pt2; j >= pt1; j--)
    {  Express.remove (j);
    private void processOperator (String Oper)
    {  int point =-1;
         while (Express.contains (Oper))
         {  point = Express.indexOf (Oper);
         oper = Express.get(point).toString();
              number1 = Express.get(point-1).toString();
              number2 = Express.get(point+1).toString();
              TempExp = new Exp (number1, number2, oper);
              TempExp.calculate();
              answer = Temp.toString();
              Express.add(point-1, point+1);
              removePoints (point-1, point+1);
    point =-1;
    private void removeBrack()
    {  int opBrack = 0;
    int clBrack = 1;
         int j = 0;
         String Temp = "";
         while (findBrack())
         {  clBrack = Express.indexOf (")");
         j = clBrack;
              do
              {  Temp = Express.get(j).toString();
              if (Temp.charAT(0) =='(')
              {   opBrack = j;
                   j--;
              while (opBrack < 0);
              number1 = Express.get(opBrack +1).toString();
    number2 = Express.get(clBrack -1).toString();
              oper = Express.get(opBrack+2).toString();
              TempExp = new Exp (number1, number2, oper)
              TempExp.calculate();
              answer = TempExp.toString();
              Express.add(clBrack+1, answer);
              removePoints(opBrack, clBrack);
              opBrack=-1;
              clBrack=0;
    private void removeDivide()                         
         {     processOperator("/");                    
              remMult();                         
         private void removeTimes()                         
         {     processOperator("*");                         
              remAdd();                         
         private void removeAdd()                         
         {     processOperator("+");                         
              remSub();                         
         private void removeSub()                         
         {     processOperator("-");
    // ================================= help menu ============================
    class JHelp extends JFrame
    {     JTextArea textarea;
         public JHelp()
         {     super ("Help");
              Container contentPane = getContentPane();
         /*     JPanel textPan1 = new JPanel (new BorderLayout());
              textarea = new JTextArea ("How to use Nicks Calculator");
              textarea.setWrapStyleWord(false);
              JScrollPane textAreaPane1 = new JScrollPane (textarea);
              textPan1.add (textarea, BorderLayout.CENTER);
              contentPane.add(textPan1);
              textarea.setEnabled(false); */
              JLabel lab=new JLabel(new ImageIcon("helpmenu.jpg"));
              contentPane.add(lab, BorderLayout.CENTER);
              setBounds(400,200,400,400);
              this.show();
    // ================================ Splash Page =============================
    class JSplash extends JFrame
    {     public JSplash()
    {   super ("Splash Page");
              Container contentPane=getContentPane();
              JLabel lab=new JLabel(new ImageIcon("nick.jpg"));
              contentPane.add(lab, BorderLayout.CENTER);
              setBounds(400,200,250,320);
              this.show();

    Spot the difference:
    public LinkedList getList();
    public LinkedList getList()
    Notice the semi-colon. Thats the problem

  • NullPointerException, how do i get rid of?

    Hey guys,
    I'm totally puzzled by this one. All i'm trying to do is to change the content of JTextField(), but every time i do i get a NullPointerException. Here's the code:
    public class PrivateMessageWindow extends JFrame
        private  Container container;
        private  JTextArea textArea;
        private  JTextField inputField;
        private  String windowId, messageDestination;
        private  Message m;
         public PrivateMessageWindow(String Id)
               super("Private Message");
               Container container = getContentPane();
               JTextArea textArea = new JTextArea();
               textArea.setEditable(false);
               JTextField inputField = new JTextField();
                //ActionListener for inputField
               ActionListener k = new PrivateWindowListener();
               inputField.addActionListener(k);
               //Placement of element on Panel
               container.setLayout(new BorderLayout(5,5));
               container.add(textArea, BorderLayout.CENTER);
               container.add(inputField, BorderLayout.SOUTH);
               //Initializes a message of type private Message
              setSize( 300, 150);
              setVisible(true);
          }//end of constructor
           private class PrivateWindowListener implements ActionListener
                   public void actionPerformed(ActionEvent event)
                        inputField.setText("");
    }// end of  private class PrivateMessageWindowThe problem occurs anytime i access a variable outside the actionPerformed method i get a NullPointerException. I'm not sure if it helps but this class gets triggered by a JButton object.
    any clue of wats happening here?
    Tanx.

    You are not initializing your JTextField inputField. Instead, you instantiate a local variable. The same applies to your JTextArea. You should have:textArea = new JTextArea();
    textArea.setEditable(false);
    inputField = new JTextField();Moreover, I don't think you really need the field container.

  • Count all rows of a Database table

    I want to count all the rows of a table.
    I have made correctly the connection with the database and all the other things (make a statement, make the query and the resultSet), I use the MySQL server v4.0.17
    Here is the code I use:
    int count=0;
    String temp=null;
    String query = "SELECT COUNT(*) FROM customers";//customers is my Database Table
    try {
    rs = stmt.executeQuery(query);
    }//end try
    catch(Exception exc) {
    createFeatures.PlayErrorSound(registerRenter);
    Optionpane.showMessageDialog(registerRenter,
    "MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
    }//end catch
    try {
    while(rs.next()) {
    count++; //I use this variable in order to count the rows because the resultSet doesn't tell me the answer
    countLine=rs.getInt(1);
    }//end while
    }//end try
    catch(Exception exc) {
    createFeatures.PlayErrorSound(registerRenter);
    Optionpane.showMessageDialog(registerRenter,
    "MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
    }//end catch
    count=count++; //i increase it aggain because if the rows are initial 0 i want to make it 1
    temp = String.valueOf(count);//i use this command in order to display the result into a jtextfield
    Any help is appreciated!!!!!

    This program will work just fine against mysql:
    mport java.util.*;
    import java.io.*;
    import java.sql.*;
    public class Test {
    public static void main(String []args) {
    String url= "jdbc:mysql://localhost/adatabase";
    String query = "select count(*) from foo2";
    String createQuery="create table foo2(f1 int)";
    String dropQuery="drop table foo2";
    String insertQuery="insert into foo2 values(1)";
    Properties props = new Properties();
    props.put("user", "auser");
    props.put("password", "xxxxx");
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    System.out.println("Connecting to the msql server");
    Connection con = DriverManager.getConnection(url, props);
    Statement stmt = con.createStatement();
    try {
    stmt.executeUpdate(dropQuery);
    } catch(SQLException e) {}
    stmt.executeUpdate(createQuery);
    stmt.executeUpdate(insertQuery);
    stmt.executeUpdate(insertQuery);
    PreparedStatement pstmt = con.prepareStatement(query);
    System.out.println("***Executing a select");
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
    System.out.println("RowCount="+ rs.getString(1));
    rs.close();
    pstmt.close();
    stmt.close();
    con.close();
    } catch(Exception e) {
    System.out.println(e.getMessage());
    }

  • How to access unamed components

    If I had a frame with 100 text fields which was added to the frame using the following loop. How can I access and identify individual textfields
    for (int i=0;i<100;i++)
       someframe.add(new JTextField());
    }Any help is appreciated

    You could do something like the following:
    for (int i=0;i<100;i++)
    someframe.add(new JTextField(),setName("someUniqueName"));
    code]But that would require searching through the list of fields in the container looking for the correct field (not efficient).
    I suggest using the array suggestion. Or if you don't want to index them numerically, you could use a hashmap and map then to specific names.

Maybe you are looking for

  • PDF files opening and closing slowly in Acrobat version 9.5.2.

    I am running Acrobat 9.5.2.  Last week our server died at work and we converted to a new one.  Since then pdf files have been opening and closing very slowly, sometimes taking 15+ seconds to close.  Strangely enough, if you open and close several in

  • How can i activate and use my iphone?

    Hello! I bought 2 months ago an iPhone 4 from UK. I don't live there, i am from Romania. The phone according to the invoice and the offer from the shop, was SIM Free as i requested, and paid full price for it. The employee from the store told me that

  • Webutil - to check the file/folder path is valid in client pc

    I'm using oracle 10g forms. OS is Windows. When i try to write a file from DB to Client in order to open the file in client system, i 'm using CLIENT_HOST('CMD /C '||<filename>); => which saves the file in desktop. In order to specify a different loc

  • How to set application configuration so that it shows up in Portal

    Hi, In the Floorplan Manager component (FPM_OIF_COMPONENT), I copied an existing component configuration RPM_INITIATIVE_DETAILS_OIF to ZRPM_INITIATIVE_DETAILS_OIF_V01. And then under application RPM_INITIATIVE_DETAILS I created a new application conf

  • I  need help installing mac OS 9.0.4

    I got an Imac from ebay no software whats so ever. I turned it on and the system had an administrator password which I didn't know. It has mac OS 9.2 Installed on it I was told by a freind to buy the OS cd and to boot form it so I ordered mac os 9.0.