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.

Similar Messages

  • 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();
    }

  • 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.

  • 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.

  • 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.

  • 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....

  • 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

  • Help with commandLink, actionListener, param in a simple CRUD example

    Hi All,
    I'm trying to build a very simple CRUD (create read update delete) interface as a proof of concept (concept being that I have some aptitude with JSF) and here is my problem:
    I have a dataTable, each row of which represents a campaign object. I want an "edit" link in each row that will load a single-edit page for the campaign in that row. I am not sure how to access the value of the param (campaignId) within the backing bean's actionListener method. Below is the code for the link and thanks in advance.
    Matt
    <h:commandLink
       actionListener="#{CampaignBean.chooseCampaign}"
       action="#{CampaignBean.editCampaign}"
       rendered="#{not campaign.editable }">
                   <h:outputText value='#{campaign.campaignName}'
                                 rendered="#{not campaign.editable }"/>
                   <f:param name="chosenCampaign"
                                 value="#{campaign.campaignId }"/>
              </h:commandLink>

    Thank you very much! Actually a co-worker had pointed me to your site yesterday afternoon and I was going to post a link to it. Your articles are very helpful!!!

  • Help actionlistener in a seperate class

    Hello,
    Thank you thus far for yout help. I'm currently having a probelm with calling action listener form a seperate class file:
    The codes are as belows:
    the main class i call my action listener assaveButton = new Button("SAVE");
         saveButton.setBounds(80,350, BUTTON_WIDTH, BUTTON_HEIGHT);
         detailPanel.add(saveButton);
         saveButton.addActionListener();
    and in the other class file in which i put it as a panel i put it as:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    public class ActionTPanel extends Panel{
    public ActionTPanel(){
    cancelButton.addActionListener (
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   RecordTFrame lala = new RecordTFrame();
                   lala.show();
         saveButton.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent e) {
                             try{
                             Statement stmt = con.createStatement();
                             if(!tf1.getText().equals ("")){
                             String query =     "INSERT INTO HarvestFile (" +
                                                 "TreeID, SegmentCode, DateOfHarvest, NumberOfTrees, NumberRemaining," +
                                                      "Revenue, ForestOfficer, Comments" +
                                                      ") VALUES ('" +
                                                      tf1.getText() + "','" +
                                                      tf.getText() + "','" +
                                                      tf2.getText() + "','" +
                                                      tf3.getText() + "','" +
                                                      tf5.getText() + "','" +
                                                      tf4.getText() + "','" +
                                                      tf6.getText() + "','" +
                                                      tf7.getText() + "')";
                             System.out.print("\nSending query: " +
                                                      con.nativeSQL (query) + "\n");
                             int result = stmt.executeUpdate(query);
                                  if(result==1)
                                  System.out.print("\nInsertion successful\n");
                                  else{
                                  System.out.print("\nInsertion failed\n");
                                  tf1.setText("");
                                  tf.setText("");
                                  tf2.setText("");
                                  tf3.setText("");
                                  tf5.setText("");
                                  tf4.setText("");
                                  tf6.setText("");
                                  tf7.setText("");
                             else
                             System.out.print("\nEnter Tree ID!");
                             stmt.close();
                             catch (SQLException sqlex){
                             sqlex.printStackTrace();
                             System.out.print(sqlex.toString() );
         resetButton.addActionListener (
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   tf.setText("");      
                   tf1.setText("");
                   tf2.setText("");
              tf3.setText("");
              tf4.setText("");
              tf5.setText("");
              tf6.setText("");
              tf7.setText("");
         show();
    public static void main( String args[] )
              final HAddFrame app = new HAddFrame();
              app.addWindowListener(
                   new WindowAdapter() {
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    I'm not sure how to call it inthe class
    i hope u guys can help me!
    Thanks!
    -pal-
    your help is greatly appreciated!

    hello again!
    I have another question do i have to reclare the textfields in the separate class file...
    Thanks
    pal

  • URI Redirecting Problem in JSF ActionListener !!Please help!

    Hi, i have 2 pages: A.jsp and B.jsp.
    I have a command link in A.jsp, and its code is like this:
    <h:commandLink actionListener="#{navigator.goBSite}">    
         <h:outputText value="GoB" />
    </h:commandLink> in the action listener goBSite(ActionEvent e), i need to clear some flag values in session beans, so i cannot jump to B.jsp simply, i need to use an actionListener, and in the actionListener, first clear the flags and then redirect the page to B.jsp. i tried the code below:
    HttpServletResponse response = (HttpServletResponse) context
                        .getExternalContext().getResponse();
              try
                   response.sendRedirect("/Platform/publish/registry.faces");
              catch (IOException e1)
                   e1.printStackTrace();
              }But it does not work, and an exception with the message "java.lang.IllegalStateException: Cannot forward after response has been committed" is thrown, so i think this method can only be used in servlet.
    I think i can write a C.jsp, i write the java code in C.jsp to clear the flag values, and then redirect the page the B.jsp, this may be a solution, but not a good one.
    So is it possible to redirect my page in my actionListener?
    Best Regards:)
    Robin

    Hi Robin,
    First, let me make sure I understand your issue. You have two JSPs A (A.jsp) and B (B.jsp) where A contains a command link which should take you to page B, and you want to manipulate some flag in the a session bean,(sbean). If I miss understood your issue you may stop here :-)
    In the JSF life cycle phase, action and actionListeners are processed during the "Invoke Application" phase. You may assign one or more actionListeners to a component, in your case the commandLink, and a single action. The actionListeners perform user interface logic and NOT navigation, where as actions perform business logic (you can get for session bean and update it in this code) and it returns an out-come string (navigation). The processing of actionListeners precede the processing of the single action method. The actionListener's interfaces is public void myActionListener(ActionEvent e), while the action's interface is the public String myAction(), where the returned string is an outcome string defined in the a navigation-rule element in the faces.configation file.
    In a nutshell you need to switch from the actionListener to the action interfaces and create/update and add some configuration to your faces-config file (managed bean and nagivation)
    Here's a a quick and dirty example:
    ========================
    ===> A.jsp
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
    <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <html>
    <f:view>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSF Command Link Test</title>
    </head>
    <body>
    <h1>JSF Command Link Test</h1>
    <h:form>
    <h:commandLink value="goto B" action="#{mbean.gotoViewB}"/>
    <%-- note the action attribute instead of the actionListener attribute with calls teh gotoVeiwB method in the mbean --%>
    </h:form>
    </body>
    </f:view>
    </html>
    ===> B.jsp
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
    <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <html>
    <f:view>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSF Command Link Test</title>
    </head>
    <body>
    <h1>JSF Command Link Example: View B</h1>
    <h:form>
    <h:commandLink value="goto A" action="gotoViewA"/>
    </h:form>
    </body>
    </f:view>
    </html>
    ===> faces-config.xml
    <navigation-rule>
    <from-view-id>/index.jsp</from-view-id>
    <navigation-case>
    <from-outcome>gotoB</from-outcome>
    <to-view-id>/response.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    <navigation-rule>
    <from-view-id>/response.jsp</from-view-id>
    <navigation-case>
    <from-outcome>gotoViewA</from-outcome>
    <to-view-id>/index.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    <managed-bean>
    <managed-bean-name>mbean</managed-bean-name>
    <managed-bean-class>net.wpb.example.presentation.ManagedBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    ===> ManagedBean Class:
    package net.wpb.example.presentation;
    * Sample JSF Managed Bean, see the WEB-INF/faces-config.xml file
    public class ManagedBean {
    // the action to goto JSP B
    public String gotoViewB() {
    // Do any business logic here
    return "gotoB";
    I have not included the web.xml (assume that's okay ). Sorry about the format.
    Hope this Helps,
    William
    .

  • AppletContext within ActionListener..Help!!

    Hello,
    How can I use AppletContext in actionlistener that is being called by an applet in another class. All I need is on click on that applet, I wanted to open a document or an HTML page. I am using this code, Please see below and help me.
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.util.*;
    import java.applet.*;
    import java.net.*;
    public class Chat1 extends Applet
         Color color1 = Color.white;
         public void init()
              setLayout(new FlowLayout());
              Chat2 button1 = new Chat2("Chat"); // this string "Chat" acts as an applet. On click of this string, I wanted to opea a document
              add(button1);
              setBackground(color1);
              ChatActionListener listener = new ChatActionListener();
              button1.addActionListener(listener);
    class ChatActionListener implements ActionListener
         public ChatActionListener(){ }
         public void actionPerformed(ActionEvent ae)
              if(ae.getActionCommand().equalsIgnoreCase("Chat"))
         System.out.println("Clicked:" +ae.getActionCommand());
         try{
         //AppletContext ac;
         ac = getAppletContext();
         //URL url1 = new URL("YellowPages1.html");
         //ac.showDocument(url1);
         catch(Exception e){e.printStackTrace();}
    Thanks for any help.
    Uma

    Change
    ChatActionListener listener = new ChatActionListener();
    to
    ChatActionListener listener = new ChatActionListener(getAppletContext());
    And rewrite the listener like this:
    class ChatActionListener implements ActionListener
    private AppletContext ac;
    public ChatActionListener(AppletContext ac) {
        this.ac = ac;
    public void actionPerformed(ActionEvent ae)
    if(ae.getActionCommand().equalsIgnoreCase("Chat"))
    System.out.println("Clicked:" +ae.getActionCommand());
    try{
    URL url1 = new URL("YellowPages1.html");
    ac.showDocument(url1);
    catch(Exception e){e.printStackTrace();}
    }

  • How to stop ActionListener... HELP!

    Hi all!
    I have a function in my imaging application which adds "stamps" to the image. This functions adds a picture as a stamp to any location on the image loaded into my app. The stamp functions works perfectly, as the user can add the stamp picture to the loaded image as many times as they wish to.
    The problem is when the user clicks on another function to edit the image (ie. brightness, etc), the actionlistener is somehow still active allowing the user to continuously add stamps to the loaded image if the user clicks on to the loaded image
    Is there anyway to stop the actionlistener so that when the user clicks on another function they can no longer add stamps to the screen if they click on the image???
    This is the code for the button for the stamp function:
            else if(obj == stampButton)
                   stampLoc = new String("images/censored.gif");
                   stampImage = new ImageIcon(stampLoc).getImage();
                   ImageIcon stampIcn = new ImageIcon("images/stamp.gif");
                   Image stampImg = stampIcn.getImage();
                   Toolkit tk = getToolkit();
                   Cursor stampCursor = tk.createCustomCursor(stampImg, new Point(16,16), "Stamp Cursor");
                   displayPanel.setCursor(stampCursor);
                   displayPanel.addMouseListener(new MouseAdapter()
                        public void mousePressed(MouseEvent e)
                             displayPanel.createUndo();
                             stx = e.getX();
                             sty = e.getY();
                             System.out.println("JPanel: " + stx + "  " + sty);
                             displayPanel.drawImage(stx, sty, stampImage);
                        public void mouseClicked(MouseEvent e) {}
                        public void mouseReleased(MouseEvent e) {}
                        public void mouseEntered(MouseEvent e) {}
                        public void mouseDragged(MouseEvent e) {}
                        public void mouseMoved(MouseEvent e) {}
                        public void mouseExited(MouseEvent e) {}
                     //displayPanel.removeMouseListeners();
                   displayPanel.validate();
                   repaint();
                   stx = 0;
                   sty = 0;
              }This line below draws the stamp on screen, and i have tried placing it outside of the mousePressed listener, but then the stamp feature does not work propely. What it then does is place the image at coordinates (0,0) of the image, and when user clicks on the image no stamp is added to it.
    displayPanel.drawImage(stx, sty, stampImage);
    This is the drawImage() method which is located in my DisplayPanel class:
         public void drawImage(int x, int y, Image stmpImg)
              mBufferedImageStamp = copy(mBufferedImage);
              Graphics graphics = mBufferedImageStamp.getGraphics();
              Image image = new ImageIcon(stmpImg).getImage();
              graphics.drawImage(image, (x-(image.getWidth(this)/2)), (y-(image.getHeight(this)/2)), this);
              graphics = mBufferedImage.getGraphics();
              graphics.drawImage(mBufferedImageStamp, 0, 0, this);
              repaint();
         }I hope someone can help me! :)
    This is a huge bug in my app and i have no idea on how to correct it :(
    Thanks for anyways help or advice in advance!
    Claire
    x

    The idea is to do only what you need to do inside an event handler.
    In your stampButton event handler you define a string, load an image, create an ImageIcon, create and set a new Cursor and add a MouseListener(!).
    Most of this can be taken out of the event handler. You only need to load the image and create the cursor once (you can set the cursor in the event handler). Same with the mouse listener. Add it to displayPanel one time, perhaps as an inner named or outer class extending MouseAdapter; and it will always have the mouse location available. You can get this position from the mouse listener when you need it inside stampButton.
    You want to design the stampButton handler so that it only draws a stamp, only when the stamp button is pressed.

  • JRadioButton actionListener shows troble.plz help.

    hai forum,
    My project has a part where i select a class file,display its methods and then display JTextFields for the parameters of the method in a separate panel.
    My problem is that clicking different radio buttons(methods) do not bring about a change in the panel.
    my code for selecting and displaying method is
            public void selectClass_actionPerformed(ActionEvent e)
                if(e.getSource()==selectClass)
                    //refresh panel
                    methodPanel.removeAll();
                    methodPanel.revalidate();
                    //  Code To Generate a FileChooser
                     //instantiate class FilterClass
                    JFileChooser jfilechooser=new JFileChooser();
                    Filterclass filter=new Filterclass();
                    //Set selection mode for file chooser
                    jfilechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    //set file filter
                    jfilechooser.setFileFilter(filter);
                    int returnVal = jfilechooser.showOpenDialog(this);
                    if(returnVal == JFileChooser.APPROVE_OPTION)
                        try
                                String str = jfilechooser.getSelectedFile().getName();
                                String parent=jfilechooser.getSelectedFile().getParent();
                                classFileList.addItem(str);
                                classFileList.disable();
                                // Create a File object on the root of the directory containing the class file
                                File file = new File(parent);
                                // Convert File to a URL
                                URL url = file.toURL();         
                                URL[] urls = new URL[]{url};
                                // Create a new class loader with the directory
                                ClassLoader cl = new URLClassLoader(urls);
                                StringTokenizer st = new StringTokenizer(str,".");
                                String s = st.nextToken ();
                                 Class c = cl.loadClass(s);
                                //Get the Methods Of the Selected Path
                                Method methods[]=c.getDeclaredMethods();
                                for(int i=0;i<methods.length;i++)
                                    int modifiers=methods.getModifiers();
    if(Modifier.isPublic(modifiers)||Modifier.isStatic(modifiers))
    String a= "";
    a=methods[i].getName();
    //Get the Parameters
    Class[] parameterTypes=methods[i].getParameterTypes();
    String parameterString = "";
    for(int k=0;k<parameterTypes.length;k++)
    if(k==0)
    parameterString = parameterTypes[k].getName();
    else
    parameterString = parameterString+","+parameterTypes[k].getName();
    parameterCount = parameterTypes.length;
    System.out.println("num of para"+parameterCount);
    /*Create RadioButton Dynamically*/
    String radioName=a+"("+parameterString+")";
    j=new JRadioButton(radioName);
    methodPanel.add(j,true);
    methodlistPane.getViewport().add(methodPanel,null);
    j.setBounds(100,(100+(i*50)),100,50);
    group.add(j);
    //Class methodradioactionlistener implemented below
    j.addActionListener(new MethodRadioActionListener());
    }//end of if loop
    }//end of for loop
    }//end of try loop
    catch(Exception e1)
    StringWriter sw = new StringWriter();
    e1.printStackTrace(new PrintWriter(sw));
    String stacktrace = sw.toString();
    System.out.println("stacktrace = " + stacktrace);
    }//end of catch loop
    }//end of if loop
    }//end of e.getsource loop
    }//end of method loop
    And my MethodRadioActionListener is
            private class MethodRadioActionListener implements ActionListener
                public void actionPerformed(ActionEvent e1)
                        if(parameterCount==0)
                            textfieldPanel.removeAll();
                            textfieldPanel.repaint(); 
                            JLabel nopara = new JLabel();
                            nopara.setText("NULL PARAMETER");
                            nopara.setBounds(new Rectangle(210, 80, 175, 25));
                            textfieldPanel.add(nopara);
                            textFieldPane.getViewport().add(textfieldPanel,null);
                        } //END OF IF LOOP
                        else if(parameterCount>0)
                            textfieldPanel.removeAll();
                            textfieldPanel.repaint();
                            tf = new JTextField[parameterCount];
                            for(int j = 0; j < tf.length; j++)
                                //DISPLAYS TEXT FIELDS
                                tf[j] =new JTextField(null,5);
                                textfieldPanel.add(tf[j],true);
                                tf[j].setBounds((100+(j*100)),100,100,10);
                                textFieldPane.getViewport().add(textfieldPanel,null);
                            } //END OF FOR LOOP
                        } //END OF ELSE IF LOOP
                } //END OF ACTION PERFORMED METHOD
             } //END OF CLASS
             Clicking the radio button do not bring about any change.A single textfield is generated always.
    Plz help me fix my mistake.
    Thank you.

    Yes, as you mentioned only one action is being done that is of the last method.I tried bringing the code ,ParameterCount=k; ,inside for loop so that it takes thenumber of parameters of only one method that i select.But still i find the same kind of action takes place.
    Is there any other way out to solve my problem?How can i get the parameterCount of only one single method?
    Is it advisable to write the radioButton actionPerformed method inside the actionPerformed method for selectClass menuItem, rather than as a separate class.
    Thank you

  • Need help creating actionListener for an array of text fields

    I am working on a school project, so I am very new to Java. I have a program which is basically a unit converter. Each unit type has its own tab. I was able to dynamically create text fields in each tab and now I need to add actionListener to each of those text fields. Probelm is, the text fields are not really unique. I guess they're only unique within their tab. So now I am having difficulty referring to my text fields. If you look at my actionListener in the code below, I am trying to refer to it as unitTFs[0].getText() and that's not working. Please help. Thanks in advance.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class UnitConverter extends JPanel
    public UnitConverter()
    String[] lengthUnits = {"cm","m","inch","feet","yard","mile"};
    String[] areaUnits = {"m2","a","feet2","yd2","Acre","ha"};
    String[] massUnits = {"g","kg","ton","ounce","pound"};
    String[] volumeUnits = {"liter","m3","inch3","feet3","Gallon","Barrel"};
    String[] tempUnits = {"C","F"};
    ImageIcon lengthICN = new ImageIcon("java-swing-tutorial.JPG");
    ImageIcon areaICN = new ImageIcon("java-swing-tutorial.JPG");
    ImageIcon massICN = new ImageIcon("java-swing-tutorial.JPG");
    ImageIcon volumeICN = new ImageIcon("java-swing-tutorial.JPG");
    ImageIcon tempICN = new ImageIcon("java-swing-tutorial.JPG");
    JTabbedPane tabPaneJTP = new JTabbedPane();
    JPanel lengthPNL = tabContents(lengthUnits);
    tabPaneJTP.addTab("Length", lengthICN, lengthPNL);
    tabPaneJTP.setSelectedIndex(0);
    JPanel areaPNL = tabContents(areaUnits);
    tabPaneJTP.addTab("Area", areaICN, areaPNL);
    JPanel massPNL = tabContents(massUnits);
    tabPaneJTP.addTab("Mass", massICN, massPNL);
    JPanel volumePNL = tabContents(volumeUnits);
    tabPaneJTP.addTab("Volume", volumeICN, volumePNL);
    JPanel tempPNL = tabContents(tempUnits);
    tabPaneJTP.addTab("Temperature", tempICN, tempPNL);
    //Add the tabbed pane to this panel.
    setLayout(new GridLayout(1, 1));
    add(tabPaneJTP);
    protected JPanel tabContents(String[] units)
    JPanel tabPNL = new JPanel();
    JTextField[] unitTFs = new JTextField[units.length];
    JLabel[] unitLs = new JLabel[units.length];
    for (int i = 0; i < units.length; i++)
    unitTFs[i] = new JTextField("0");
    unitLs[i] = new JLabel(units);
    tabPNL.add(unitTFs[i]);
    tabPNL.add(unitLs[i]);
    tabPNL.setLayout(new GridLayout(units.length, 1));
    return tabPNL;
    private class CmHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    double cm, m;
    cm = Double.parseDouble(unitTFs[0].getText());
    public static void main(String[] args)
    JFrame frame = new JFrame("Unit Converter Demo");
    frame.getContentPane().add(new UnitConverter(), BorderLayout.CENTER);
    frame.setSize(500, 500);
    frame.setVisible(true);

    Variables only have scope in the method (or block) in which they are created. That means if you create a variable in one function, you can't use it in another.
    If you want to use a variable in two different functions, you have to make it a member variable.
    [Declaring Member Variables|http://java.sun.com/docs/books/tutorial/java/javaOO/variables.html]

Maybe you are looking for

  • Error while sending PO output through mail in PDF format - Urgent

    Dear friends, Developed program to send sapscript output through mail in pdf format, the program running properly, even function module SO_NEW_DOCUMENT_ATT_SEND_API1 returning sy-subrc 0. But the external mail is not going to user lying in SAP outbox

  • HT201210 iphone won't charge or restore, keep getting error message

    Last night I plugged my iPhone 4 into the APPLE wall charger and it would not recognize it to charge it, I unplugged it and plugged my iPad into the same charger and it worked so it was clearly my phone.  I called my service provider because I was go

  • FMLE won't detect audio devices

    FMLE won't detect any of my audio devices even when I set them to default device. It only detects my microphone, and I've searched online for many fixes and to no avail.

  • How To: On Form Submit move to Next Tab with Spry Tabbed Panels

    I've got a page set up with 3 different forms in three different panels. When the form in Panel one is submitted, I need the form in panel two to open up. When form two is submitted, I panel three to open. I've made sure that the following is located

  • Broadwell Intel Audio Only HDMI Output

    I have been trying for the last couple of days to get audio working on my Dell New XPS 13 (too new, maybe?). I don't think it's a hardware failure because the laptop is only four days old and the audio works when booted into Windows 8.1 (which is my