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

Similar Messages

  • When button clicked help

    I have buttons for help, back, next, finish, cancel.
    initially I have the back and finish buttons setEnable(false)
    but when I click on Next button I want the Back button to be setEnable(true)
    I wrote the following
    //ActionListener for jButton_Next Of NavigationButtons Panel
    newNavigationButtonsClass.jButton_Next.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    newNavigationButtonsClass.jButton_Back.setEnabled(true);
    When I click on the jButton_Next the jButton_Back is not enabled. May I know what I can change in this to get this working. Thanks.

    Is the code where you initially disable the button
    getting called again somehow? I'd check to make
    sure this code isn't getting called again after you
    enable the button within actionPerformed.

  • How to create authorisation object for save button please help in abap

    how to create authorisation object for save button please help in abap

    Hi
    In general different users will be given different authorizations based on their role in the orgn.
    We create ROLES and assign the Authorization and TCODES for that role, so only that user can have access to those T Codes.
    USe SUIM and SU21 T codes for this.
    Much of the data in an R/3 system has to be protected so that unauthorized users cannot access it. Therefore the appropriate authorization is required before a user can carry out certain actions in the system. When you log on to the R/3 system, the system checks in the user master record to see which transactions you are authorized to use. An authorization check is implemented for every sensitive transaction.
    If you wish to protect a transaction that you have programmed yourself, then you must implement an authorization check.
    This means you have to allocate an authorization object in the definition of the transaction.
    For example:
    program an AUTHORITY-CHECK.
    AUTHORITY-CHECK OBJECT <authorization object>
    ID <authority field 1> FIELD <field value 1>.
    ID <authority field 2> FIELD <field value 2>.
    ID <authority-field n> FIELD <field value n>.
    The OBJECT parameter specifies the authorization object.
    The ID parameter specifies an authorization field (in the authorization object).
    The FIELD parameter specifies a value for the authorization field.
    The authorization object and its fields have to be suitable for the transaction. In most cases you will be able to use the existing authorization objects to protect your data. But new developments may require that you define new authorization objects and fields.
    http://help.sap.com/saphelp_nw04s/helpdata/en/52/67167f439b11d1896f0000e8322d00/content.htm
    To ensure that a user has the appropriate authorizations when he or she performs an action, users are subject to authorization checks.
    Authorization : An authorization enables you to perform a particular activity in the SAP System, based on a set of authorization object field values.
    You program the authorization check using the ABAP statement AUTHORITY-CHECK.
    AUTHORITY-CHECK OBJECT 'S_TRVL_BKS'
    ID 'ACTVT' FIELD '02'
    ID 'CUSTTYPE' FIELD 'B'.
    IF SY-SUBRC <> 0.
    MESSAGE E...
    ENDIF.
    'S_TRVL_BKS' is a auth. object
    ID 'ACTVT' FIELD '02' in place 2 you can put 1,2, 3 for change create or display.
    The AUTHORITY-CHECK checks whether a user has the appropriate authorization to execute a particular activity.
    This Authorization concept is somewhat linked with BASIS people.
    As a developer you may not have access to access to SU21 Transaction where you have to define, authorizations, Objects and for nthat object you assign fields and values. Another Tcode is PFCG where you can assign these authrization objects and TCodes for a  profile and that profile in turn attached to a particular user.
    Take the help of the basis Guy and create and use.
    Regards
    ANJI

  • I'm getting a similar message: There was an error opening the database..." and the only option I get is a "quit" button. Help!

    I'm getting a similar message: First it offers me chance to repair - but if I it repair, it crashes.  Then if I select do not repair I get the following warning: There was an error opening the database..." and the only option I get is a "quit" button. Help!

    From the path in the error message you posted it appears that the library is not on your internal (root) drive.
    What type of disk is the library on and how is it formatted?
    The crash log Léonie is referring to is what is printed out when Aperture crashes. You wrote that Aperture crashes in your first post so if the app crashes you must have gotten a crash report.
    Message was edited by: Frank Caggiano

  • How to "un-grey" the "Updates" button under Help in PS CS6?

    I had uninstalled the CS5.5 and installed the CS6 Master collection. But the "Updates" button under Help in PS is greyed out, that means I cannot update the ACR to 7.1 or any subsequent updates. How can I overcome this problem? BTW, my computer is windows based.

    " Sure you can - simply download them from the support pages/ download section.”
    What should I download from that page?
    ATongT

  • I downloaded the new version of firefox, now my flash player wont work, the html text box is gone and so is the back and forward buttons. please help??

    I downloaded the new version of firefox, now I cant watch any movies, the html text box is totally gone, and so is the back and forward website buttons, please help? can i just have the old version back?

    Not sure whether for instance you initially had a Yahoo optimised version of Firefox, and have now overwritten it with an official Mozilla version. Although the Mozilla version should NOT add unwanted features, but the Yahoo version may well do.
    If you merely need to find the Yahoo emails page quickly just add it as a bookmark or as a bookmark on the Bookmarks toolbar and make sure that is visible.
    Clicking the star icon on the location bar whilst looking at your emails will bookmark the page.
    * [[How to use bookmarks to save and organize your favorite websites]]
    * [[Bookmarks Toolbar - Display your favorite websites at the top of the Firefox window]]
    I do not use Yahoo myself,and am not sure what add-ons are available. You could search yourself using
    * FirefoxButton -> add-ons
    ** see [[Find and install add-ons to add features to Firefox]]
    ** examples [https://addons.mozilla.org/en-us/firefox/addon/yahoo-toolbar/ yahoo toolbar] & [https://addons.mozilla.org/en-us/firefox/addon/yahoo-mail-notifier/ mail notifier]
    * also look at Yahoo's own information such as http://help.yahoo.com/tutorials/toolbar/cl3/c3_ff_toolbar1.html

  • How do I update my iPad 2 to iOS 5, I tried going to settings,general ,software update but I can't seem to find the software update button pls help :)

    How do I update my iPad 2 to iOS 5, I tried going to settings,general ,software update but I can't seem to find the software update button pls help :)

    Go to Settings > General > About and see what iOS version you are running.  If it is lower than 5, you won't find the software update button.  It was added when iOS 5 came out.  The current iOS is 5.1.1.  To update to the current OS, you'll need to connect to the computer you sync with (this is important - do not connect to a computer you do not sync with as you will lose you apps) and update the software in iTunes.  Once you have updated to the 5.1.1, the software update button will be in Settings going forward.  Make sure you have a lot of time.  Updating from below 5 to 5 or higher is a somewhat lengthy process.
    This link will provide the guidance you need:
    http://www.macworld.com/article/1162925/how_to_upgrade_your_ios_device_to_ios_5. html

  • When I start my mac book pro the screen flashes on and off and then a blue color before it open to the log in screen. Sometime a program will shot down buy it's self without me clicking the quit button. Help?!

    When I start my mac book pro the screen flashes on and off and then a blue color before it open to the log in screen. Sometime a program will shot down buy it's self without me clicking the quit button. Help?!

    If you keep getting a 'red' message it means that the HDD is faulty and will have to be replaced.  You will have to format the new HDD in Disk Utility>Erase and then install the OSX and your data from Time Machine.
    Ciao.

  • A friend of mine was recently in an accident and we need to delete some photos from her iPhone's "Photo Stream From my Computer" album, but cannot figure out a way to do it (there's no delete button). Help?

    A friend of mine was recently in an accident and we need to delete some photos from her iPhone's "Photo Stream From my Computer" album, but cannot figure out a way to do it (there's no delete button). Help?

    Sounds like it was synced from her computer using iTunes.  Connect the phone to her computer, open iTunes, click on the name of her phone in iTunes, go to the Photos tab and see if this folder is checked.  If so, unchecking it and syncing will remove them all, or deleting/moving the photos from the folder on her computer and syncing will remove the deleted/moved photos.

  • When my computer and monitor go to sleep, the system locks up and I have to do an hard reset with the power button.  help?

    when my imac and display go to sleep, the computer locks up and will not restart without a hard restart with the power button.  help?

    Hello, what all especially USBwise do you have connected to it?
    One way to test is to Safe Boot from the HD, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, Test for problem in Safe Mode...
    PS. Safe boot may stay on the gray radian for a long time, let it go, it's trying to repair the Hard Drive
    Reboot, test again.
    If it only does it in Regular Boot, then it could be some hardware problem like Video card, (Quartz is turned off in Safe Mode), or Airport, or some USB or Firewire device, or 3rd party add-on, Check System Preferences>Accounts (Users & Groups in later OSX versions)>Login Items window to see if it or something relevant is listed. Or an errant process eating up RAM.
    Check the System Preferences>Other Row, for 3rd party Pref Panes.
    Also look in these if they exist, some are invisible...
    /private/var/run/StartupItems
    /Library/StartupItems
    /System/Library/StartupItems
    /System/Library/LaunchDaemons
    /Library/LaunchDaemons
    Open console in Applications>Utilities, check the system log for the date/time of the last problem  & the Startup right after that for clues.

  • 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 with Button actionlistener

    Hi friends , I have simple question but i am not getting any idea how to solve this..
    I want to call a method in one class from other class...ie
    I have a class called checklistmod which contains method called onClickDeleteButton(CheckInfoItem checkInfoItem) where Checkinfoitem is another help class in the same checklistmod class.
    I have another class called showlist which contains a button called "Delete".
    my question is i want to add a actionlistenet for "Delete" button such that when i click the "Delete" button it should call the method onclickDeleteButton(CheckInfoItem checkinfoitem) method in checklistmod class..
    Does anyone has an idea
    sorry if my question in not clear..
    Thanks in advance

    So call it. These are just classes and methods. They should be treated like any other classes and methods. Of course since (I assume) onClikcDeleteButton is an instance method (not static) the class showlist will have to have access to (a reference to) an instance of the class checklistmod.
    Also, the class CheckInfoItem has to be public so that showlist can create an instance of it to pass to the method.
    One general technique would be for checklistmod to register itself to be called when the delete is pressed.

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

  • Opening dbs thru button events, help, i`m a newbie..

    i have the following fn for opening the db
    public static void main(String args[]) throws Exception
    new login(new javax.swing.JFrame(), true).show();
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    open();
    select();
    static void open() throws SQLException
    // ODBC data source name
    String dsn = "jdbc:odbc:dslogin";
    String user = "";
    String password = "";
    // Connect to the database
    con = DriverManager.getConnection(dsn, user, password);
    // Shut off autocommit
    con.setAutoCommit(false);
    static void select() throws SQLException
    Statement stmt; // SQL statement object
    String query; // SQL select string
    ResultSet rs; // SQL query results
    boolean more; // "more rows found" switch
    query = "select user,password from dblogin";
    stmt = con.createStatement();
    rs = stmt.executeQuery(query);
    // Check to see if any rows were read
    more = rs.next();
    if (!more) {
    System.out.println("No rows found.");
    return;
    // Loop through the rows retrieved from the query
    while (more)
    // System.out.println("kkkk");
    System.out.println("umm" + rs.getString("user"));
    System.out.println("ummmm" + rs.getString("password"));
    more = rs.next();
    rs.close();
    stmt.close();
    now my problem is this..while the above open and select fns work fine in void main, i`m trying to open the db upon clicking a button..heres what i tried to do :
    cmdsubmit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    cmdsubmitActionPerformed(evt);
    private void cmdsubmitActionPerformed(java.awt.event.ActionEvent evt) {
    open();
    seelct();
    when i try it i get the error message exceptions must be caught or throw or sumthing like that and i`m new to java so i`ve no idea how to go about doing it..help please..

    On JDBC:
    You only need to register a driver with the DriverManager once, and this is done (by JDBC conform drivers) when the driverclass is loaded. You may want to do this in a static initializer:
    import java.sql.*;
    class MyClass{
        static {
            try {
                // load driver class, which automatically registers itself
                Class.forName("sun.jdbc....");
            } catch(Exception ex) { /* handle it, throw error */ }
        // later
        Connection con = DriverManager.getConnection(...);
    }Even better is NOT to hard-code the driver at all. Use
    java -Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver;oracle.jdbc.OracleDriver MyClassinstead.
    Fritz

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

Maybe you are looking for

  • My Media Encoder CC grace period ran out - now stuck

    Hey there forum-goers, So my grace period for using Adobe Media Encoder CC expired some time recently while I was out of action due to illness. Upon trying to open the program it informs me I need a CC subscription - however I only need use of the pr

  • IPad going crazy after Music More Shared Mac

    I was listening to my Mac's music library on my 3rd generation iPad via Music>More>Shared>Mac. All of a sudden, after one song, my iPad went a little nuts and wouldn't play anything anymore: it'd just show, in rapid succession, some of the song title

  • Use Acrobat Professional to make text editable in Adobe Reader

    Hello, I have a .pdf document that needs to be edited. There are certain fields in the .pdf that needs to be editable in Adobe Reader. For example; we need information from other companies in that .pdf. It says "[company name]", can I make it in a ce

  • Object name & name

    Hi all, When we try to create a bussiness object through transaction SWO1,it asks us for object name & name. Can anyone please tell me the difference between them & what actually they are? Regards, Bhumika

  • Why does my original iPad keep failing on many Applications that worked well before?

    ALMOST EVERY time I start a movie on a Safari page (Or a lot of other programs) it fails and I have to start the program again! Only one out of 3 or 10 times I try it works. Sometimes I does not work no matter how many times I try !! DIfferent browse