JButton activity

Hello everyone
I have a little special problem...
I am creating a small game, and for that, I have 9 buttons, which much act together. If I press a button, it's supposed to send it's name to the ActionListener, but the only thing that it sends, is its text on the button...
So if I have a button:
JButton test = new JButton("testing");
and another:
JButton test2 = new JButton("");
and I press both of them in my game, and I print out the action of that event, it looks something like this:
Press the test button: testing
press the test2 button: (Displays nothing)
Thats properly fine, but what I want, is the variabel of the buttons...
So if I press the test button I want it to be able to print test, or if I press test2, I want it to print test2...
Is there any way of doing that?
Hope to hear from you guys soon!
Regards
Claus Nielsen

you just do this:
jButton.setActionCommand("sometext");
Now that button fires and sends this text as the command no matter what the text for the button is. This is what you would trap in the handler.

Similar Messages

  • How do i set Shortcut key for activating some operation for JButton

    while using the JButton component,one question is arising in my mind that is
    (1)how to set Shortcut key instead of using JButton actionPerformed event.
    I need a shortcut key for the similar operation has to be performed

    http://java.sun.com/docs/books/tutorial/uiswing/components/button.html

  • Threaded Socket activated by JButton

    Hi all,
    I am trying to create an FTP server with GUI. I would like to run and stop the server from command line and from the GUI. My problem is that when i press the button to start the server my GUI freezes. My server is using threads in order to serve multiple clients. Does anyone have any idea how I should do that ?
    Thanks
    Section5

    I am going to have to do a similar thing as well.
    The way I more that likely will go about is to
    have a JButton create a new thread for my ServerListener.
    So that i be able to press my button.
    My serverlistener will listen open a serverSocket and listen
    and create a new connectionHandler for each new client that
    needs info etc.
    hope it helps
    let us know.

  • Applet very slow and shows no activity, but its running

    I have a new applet for the users, but I am reluctant to implement until I get some others opinions. It is very slow (30 - 40 seconds)
    Before it outputs a screen with about 20 lines, it reads 90 different html files. It looks at the forth rec of each to extract a name. It also gets the file size to determine if the record needs to be on the screen.
    Anyway, it does 4 reads on 90 files. = 360 reads. Oops, it also reads and loads a 80 record file at the beginning. So total is 440 reads.
    It takes 30 - 40 seconds. Which is not horrible, but it is not good. What really bothers me is that the applet screen shows no activity. At the bottom is shows "done" and "100%". Task Manager shows no activity. But if you just let it sit there, it will finally fill the screen. Pretty amazing to me. I would much rather see a "progress bar" moving on the bottom like other screens. Actually, a progress bar would solve it, because the users are not in a big hurry anyway.
    I am using "openStream" and "readLine" for the files.
    Any opinions?
    import javax.swing.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class urlaa extends JApplet
    //zz  implements Runnable, ActionListener
          implements ActionListener
    // zz added
        private JLabel item;
        private JList itemList;
      int par;
      int errorflag = 0 ;
      int orgsize = 14900 ;
      String par1;
      String s;
      String e1;
      String e2;
      String e3;
      String w1;
      String w2;
      String w3;
      String w4;
      int i = 0;
      int len ;
      int size ;
      String stringsize ;
      URLConnection conn ;
      int i2 = 0 ;
      int k = 0;
      int current = 0;
      String s1 ;
      String s6 ;
      String s7 ;
      String s8 ;
      String printline ;
      String pageLink;
      String arr[]  = new String[150] ;
      String arr2[] = new String[150] ;
      String arr3[] = new String[150] ;
      int arr4[] = new int[150] ;
      String inputLine;
      Thread runner;
      public void init()
             String parameter = getParameter("par1");
             if (parameter != null)
                 par = Integer.parseInt(parameter);
             else
                 par = 99;
    // zz         Button goButton = new Button("Go");
    // zz         goButton.addActionListener(this);
    // zz         add(goButton);
    // zz   added
            this.item = new JLabel();
            this.addButton();
            Container container = this.getContentPane();
            this.itemList = this.getList();
            container.add(this.getPanel());
            URL u;
            InputStream wis = null;
            DataInputStream dis;
            int rcnt = 0;
            int rcn2 = 0;
           //    1)  read filelist.txt file
           //         and load into a table.
           //    2)  close the filelist.txt file
           //    3)  Use the tabled file names to
           //         read and see if the bio
           //         has been done
           //  1) Read filelist.txt and load table
            try
            u = new URL("http://www.classof1961.mysite.com/filelist.txt");
            catch (MalformedURLException e)
              errorflag = 1 ;  // set error flag to stop while loops
              e1 = ("FILELIST.TXT MalformedURLException: " + e.getMessage()) ;
            try
                u = new URL("http://www.classof1961.mysite.com/filelist.txt");
                wis = u.openStream();
            catch (IOException ioe)
              errorflag = 1 ;  // set error flag to stop while loops
              e1 = ("FILELIST.TXT IOException : " + ioe.getMessage()) ;
    //      does not work     size = wis.getContentLength() ;
                // Convert the inputStream to a buffered DatainputStream.
                dis = new DataInputStream(new BufferedInputStream(wis));
                // Read 1st record to set up while loop
                   try
                     s1 = dis.readLine() ;  // get 1st rcd
                   catch (IOException ioe)
                     errorflag = 1 ;  // set error flag to stop while loops
                     e3 = ("FILELIST.TXT IOException : " + ioe.getMessage()) ;
                   while (s1 !=  null)
                   {  // load file names loop
                   if (errorflag == 0)
                   {  // if errors
                    arr[i] = s1 ;
                    i++ ;
                    try
                    s1 = dis.readLine() ;
                    catch (IOException ioe)
                      errorflag = 1 ;  // set error flag to stop while loops
                      s1 = null ; // force end of loop
                      e3 = ("load table read failed" + ioe) ;
                    rcnt++ ;
                    if (rcnt > 100)  // test code
                    {                // test code
                      errorflag = 1;
                      s1 = null ;
                      e3 = "Load table is looping!!" ;
                   }  // end of error check loop
                   }  // end of table load loop
               int lasttableentry = i ;  //
                   // CLOSE the filelist.txt file
                   try
                    wis.close();
                   catch (IOException ioe)
                    errorflag = 1 ;  // set error flag to stop while loops
                    e3 = ("close of filelist.txt file failed" + ioe) ;
    //   End of filelist read and load and close
    //      ptr to whats new names in table arr
            i = 0 ;
    //      While more names in table,
    //        Connect and Open file
    //        Read file until 4th rcd (rel 3rd rcd)
    //          if rcd has date, then move it to table
    //          else
    //          bump to next file name
              w1 = arr[i] ;
              w2 = w1.substring(1, 4) ;   // ONLY USED FOR CHK FOR XXXX
    //    ______________  start of major loop  _____________
            boolean morenames = true ;
            while (morenames)
            {  // Name table loop
            if (errorflag == 0)
            {  //if no errors
              try
                u = new URL(w1);
                try
                  URLConnection conn ;
                  conn = u.openConnection();
                  size = conn.getContentLength();
                catch (IOException e)
                  errorflag = 4 ;
                  morenames = false ;
                  e1 = ("file size logic failed " + w1) ;
              catch (MalformedURLException e)
                    errorflag = 1 ;  // set error flag to stop while loops
                    morenames = false ;
                    e1 = ("next whats new url error : " + w1) ;
    // compile error                break ;
              try
                  u   = new URL(w1) ;
                  wis = u.openStream();
              catch (IOException e)
                errorflag = 1 ;  // set error flag to stop while loops
                morenames = false ;
                e2 = ("next whats new open error :  " + w1) ;
    //   compile error            break ;
    //            Convert the inputStream to a buffered DatainputStream.
                  dis = new DataInputStream(new BufferedInputStream(wis));
                if (errorflag == 0)
                {  //if no errors
                       try
    //  does not work                       String s2 = dis.readLine(3) ;
                         s1 = dis.readLine() ;
                         s1 = dis.readLine() ;
                         s1 = dis.readLine() ;
                         s1 = dis.readLine() ;
                       catch (IOException e)
                         errorflag = 1 ;  // set error flag to stop while loops
                         morenames = false ;
                         e2 = "whats new file MalformedURLException: " ;
                       // file is larger than original non-bio file size
                       if (size > orgsize)  //  if file size > original file size
                       String s2a = s1.substring(0, 5);
                       String s3 = "                       " ;
    //                 Only look at title records to get the name
                       if (s2a.equals("<titl"))
                          int k2 = 7 ;
                          int l = k2 + 1 ;
                            while (!s1.substring(k2, l).equals("<"))
                              k2++ ;
                              l++ ;
                          s3 = s1.substring(7, k2) ;
                       else
                          s3 = "               " ;
    //                 s3 now has blanks or the name
                       arr2[k] = w1 ;    // move name into arr2 (link to bio)
                       arr3[k] = s3 ;    // move name into arr3 (bio name)
                       arr4[k] = size ;  // move in file size
                       k++ ;
                       } // end of if length > 36
                } // end of chk for error flag zero (no errors)
                  //  now we have to close this whats new file
                   // CLOSE the current whats new file
                   try
                    wis.close();
                   catch (IOException ioe)
                    errorflag = 1 ;  // set error flag to stop while loops
                    morenames = false ;
                    e3 = ("close of the current whats new file failed" + ioe) ;
                  //  end of the close
              rcn2++ ;
              if (rcn2 > 100)  // test code
              {                // test code
                 errorflag = 2;
                 morenames = false ;
                 e3 = "Searching files is looping!!" ;
              i++ ;           // bump to next whats up name
              w1 = arr[i] ;   // load it into work string
              if (i > lasttableentry)
                morenames = false ;
              } // end of error checking loop
             else
                  morenames = false ;
            } // end major name table loop
                   // CLOSE the last whats new file
                   try
                    wis.close();
                   catch (IOException ioe)
                    errorflag = 1 ;  // set error flag to stop while loops
                    e3 = ("close of last whats new file failed" + ioe) ;
    // end of init
    //     _________________ other methods  ______________________
    // zz added
        private JList getList() {
            // Create a List
            JList tempList = new JList(arr3);
            tempList.setVisibleRowCount(3);
            // Enable single selection
            tempList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            return tempList;
        private JButton addButton() {
            JButton button = new JButton("Select Item below and click here to go to the bio");
            button.addActionListener(this);
            return button;
        private JPanel getPanel() {
            // set layout to GridLayout 3 rows and 1 columns, no separations
            JPanel panel = new JPanel(new GridLayout(3,1,0,0));
            JScrollPane spane1 = new JScrollPane(this.itemList);
            panel.add(this.addButton());
            panel.add(spane1);
            panel.add(this.item);
    //       panel.add(new JLabel("Example List"));
            return panel;
    //   _______________  actionPerformed method  ____________________
         public void actionPerformed(ActionEvent evt)
           s8 = "actionPerformed";
    // zz added
            String command = evt.getActionCommand();
            // Get the selected value from the list and update the JLabel
            item.setText((String)itemList.getSelectedValue());
    //  try to redirect to selected url
      try
             int idx  = itemList.getSelectedIndex() ;
             String urlvalue = this.arr2[idx] ;
             URL u = new URL(urlvalue);
             this.getAppletContext().showDocument(u, "_self");
         catch(Exception e)
    }

    jagossage wrote:
    But if you just let it sit there, it will finally fill the screen. Pretty amazing to me. The onus is on you, the developer, to decide how to distract your users as they wait for your code to finish. Why should you expect something to do it for you?
    I would much rather see a "progress bar" moving on the bottom like other screens.Ah, I think I see where you're confused. The progress bar and applet loading subtitles, etc are Java's way of presenting the progress of loading the applet. Once it's fully loaded, though (which it is when your code starts running), it hands off control to you. It's in your hands at that point.

  • Custom JButton displays properly on Win2K, not under Solaris

    We have an applet that creates a panel of custom JButtons, each of which has a set of associated icons, two of which are "active" and "inactive" (there are also disabled, rollover, etc. icons). At runtime, when a button is clicked, its icon property is set to the "active" one. If another button in the panel is clicked, the first button has its icon property set to the "inactive" one.
    This displays fine when the applet is running on a Win2k machine (with the Java 1.3 plugin under either Netscape 6.2 or IE 5.5, but when we run it on a SunRay connected to a Sun Ultra80 running Solaris 8 with Netscape 6.2 and the Java 1.3 plugin, the "inactive" icon for one particular button is blank - we get a white rectangle - but when we click on the rectangle (or mouseover it), the appropriate icon appears as it should.
    When I specify a different icon to be used (reusing the .gif file from one of the other buttons)I get the same behaviour. When I reorder the buttons in the panel, the same button (now in a different position) still behaves improperly.
    Any thoughts?
    Thanks,

    No solution, but for what it's worth.
    As part of my "diagnosis by trying things out" (NOT "debugging by..." - or at least I don't admit to that :) I created a second instance of the problem button and stuck it in the panel.
    Lo! the new instance had the problem, BUT THE FIRST WAS FINE. I did a few more experiments, and the first-created instance was the one to have problems, while the second is fine, so the current work-around is to make an instance, ignore it (just leave it as a field of the class that builds the panel, but don't add it to the panel), make another instance and use that in the panel.
    My boss is happy, our client is happy (they have a demo using the a group of Sunrays), but I really wish I knew what was going on. I don't THINK that the problem button was the first instance of its class to be created (I'm at home and the thought just came to me) but it's possible and raises some more hypotheses to test.

  • How can i only allow the activation of the JDialog on top?

    Hi to all,
    i have a problem with a mask swing
    Well, my problem is this:
    In a window, when i click on save button, it's open a customizing JDialog. But i would like how i can deny a click out of this JDialog, that is on top.
    In other words, in this situation, with a jdialog on top, if the user click once again on the save button or out of this jdialog, the jdialog must stay on top and active.
    How i can this?
    Please help me!!
    the code that realize my class is this:
    public class ConsegnaOrdineDialog extends JDialog implements ActionListener {
         private JOptionPane optionPane;
         private String dataOrdine;
         private JButton si, no;
         private JTextField dataConsegna;
         public ConsegnaOrdineDialog(String dataOrdine) {
              this.dataOrdine = dataOrdine;
              dataConsegna = new JTextField();
              si = new JButton("Si");
              no = new JButton("No");
              si.addActionListener(this);
              no.addActionListener(this);
              JPanel panel = new JPanel();
                 panel.setLayout(new BorderLayout(5, 10));
                 panel.add(dataConsegna, BorderLayout.NORTH);
                 panel.add(si, BorderLayout.WEST);
                 panel.add(no, BorderLayout.EAST);
              Object[] options = {panel};
              optionPane = new JOptionPane("La data �:",
                    JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.NO_OPTION,
                    null,
                    options,
                    dataConsegna);
              setContentPane(optionPane);
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == si) {
              if (e.getSource() == no) {
                   super.dispose();               
    }

    in the constructor
    setModal(true);

  • Help needed in activating and deactivating a window

    In my GUI, I have created a window, that is having one textfield, one label and 2 buttons named "Enabled" & "Disabled" .
    MY requirement is: After execution of the window when I will click "Disabled" button, the window should be deactivated, even I can't type in the textfield and then clicking the " Enabled" button the window should be activated, then I can access the textfield.
    Here bellow,I have written the code for visibility of the window, but I haven't written code for the action to be performed by the 2 buttons.
    Can anyof you please write me the updated code satisfying my requirement, sothat I'll proceed further.
    Regards.
    MY CODE:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test7 extends JFrame
         public Test7()
              Container con=getContentPane();
              addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              JPanel p1=new JPanel();
              p1.setBackground(Color.white);
              JPanel p2=new JPanel();
              JPanel p3=new JPanel();
              JTextField txt=new JTextField(10);
              JLabel l=new JLabel("hello world");;
              JButton b1=new JButton("Enable");
              b1.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt)
              System.out.println("gained");
         // The component gained the focus
              JButton b2=new JButton("Disable");
              b2.addFocusListener(new FocusAdapter(){
                   public void focusLost(FocusEvent evt)
              System.out.println("lost");
         // The component lost the focus
              p1.add(txt);
              p2.add(l);
              p3.add(b1);
              p3.add(b2);
              con.add(p1,"North");
              con.add(p2,"Center");
              con.add(p3,"South");
              setSize(300,200);
              show();
         public static void main(String arg[])
              new Test7();

    try modifying code for the button listeners
    JButton b1=new JButton("Enable");
    b1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt)
    System.out.println("gained");
    // The component gained the focus
    txt.setEnabled(true);
    JButton b2=new JButton("Disable");
    b2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt)
    System.out.println("lost");
    txt.setEnabled(false);
    // The component lost the focus
    Hope this helps

  • JButton gains focus when Hitting tab key but hitting Enter has no effect.

    Hi,
    I have a program that has two buttons. When pressed, using the mouse, the buttons text appears in the middle of the screen. I have NOT alerted the focus subsystem. Thus when I press the tab key the buttons are highlighted in turn, to indicate that they currently have focus. However if I press enter the buttons actions (to update the middle of the screen with it's text) does not get activated.
    I am using 1.4.2 on a Windows machine.
    any help on this would be much appreciated !!
    The code is as follows:
    package com.logicacmg.skynet.tms.mmi.ui;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Container;
    public class Test implements ActionListener
    JButton bTwo = new JButton("button 2");
    JButton b = new JButton("button 1");
    JLabel label = new JLabel(" ");
    /** Creates a new instance of Test */
    public Test()
    JFrame frame = new JFrame();
    //Create a panel to hold the MMI screens.
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    b.addActionListener(this);
    bTwo.addActionListener(this);
    mainPanel.add(b, BorderLayout.WEST);
    mainPanel.add(bTwo, BorderLayout.EAST);
    mainPanel.add(label, BorderLayout.CENTER);
    //add the main panel which contains the screens and the status bar
    //to this frame.
    Container contentPane = frame.getContentPane();
         contentPane.add(mainPanel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    public static void main(String [] args)
    new Test();
    public void actionPerformed(ActionEvent e)
    JButton aButton = (JButton)e.getSource();
    if(aButton == b)
    label.setText("one");
    else if(aButton == bTwo)
    label.setText("Two");

    Which plaf are you using? Because when I switch to the windows plaf, the behavior is what you describe.
    Demo:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args) {
            final JFrame f = new JFrame("button focus");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    System.out.println(evt.getActionCommand());
            Container cp = f.getContentPane();
            cp.setLayout(new FlowLayout());
            for(int i=0; i<3; ++i) {
                JButton btn = new JButton("Button " + i);
                btn.addActionListener(al);
                cp.add(btn);
                if (i == 1)
                    f.getRootPane().setDefaultButton(btn);
            final JCheckBox laf = new JCheckBox("platform plaf");
            laf.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    String cls = laf.isSelected() ? UIManager.getSystemLookAndFeelClassName() :
                      UIManager.getCrossPlatformLookAndFeelClassName();
                    try {
                        UIManager.setLookAndFeel(cls);
                        SwingUtilities.updateComponentTreeUI(f);
                    } catch (Exception e) {
                        e.printStackTrace();
            cp.add(laf);
            f.pack();
            f.setVisible(true);
    }

  • Tooltip on JButton doesn't show the correct mnemonic

    Hi everybody,
    i don't understand why creating a JButton (or JToggleButton), associating a mnemonic and a tooltip text, i see into the tooltip window the text + 'Alt - ' + mnemonic !!
    btnHelp = new JButton();
    btnHelp.setBounds( rectBtnFn.x, y, rectBtnFn.width, rectBtnFn.height);
    btnHelp.setIcon(ttSkins.getSkin("BtnHelp_up"));
    btnHelp.setPressedIcon(ttSkins.getSkin("BtnHelp_dw"));
    btnHelp.setDisabledIcon(ttSkins.getSkin("BtnHelp_ds"));
    btnHelp.setActionCommand("OpenHelp");
    btnHelp.setMnemonic(KeyEvent.VK_F1);
    btnHelp.addActionListener(this);
    ParamPane.add( btnHelp, null);
    i'm coding on both 1.4 and 1.5.
    Thanks, regards
    SteM

    I've had FCP lock up on me several times.  The cause seems to always be 1.  That I've got a ton of unrendered stills in the timeline, 2. The project is rather large, with a lot of old sequences.  FCP can only access so much ram.  Stills are only virtual media clips until you render them, but FCP had to create them and hold them in a cache until you do render them.  FCP remembers, IN ACTIVE RAM, every cut, transition, every sequence whether active or not, every filter used, audio levels, all the clip info itself-- and a bunch of stuff you or I will never know.
    When you start reaching the limits of what FCP can handle, wonky stuff starts happening.

  • JButton in table cell in Find Mode

    Hello!
    I have JButton in JTable cell for calling LOV.
    When form goes to Find Mode all JButtons become disabled.
    Accordingly, I want that buttons active. Any help will be appreciated %)

    If the button is bound with an LOV Button binding, then I believe the framework checks the queryable property of the "target" attribute. Make sure that attribute has the "queryable" property checked in the View/Entity.
    Hope this helps.
    Erik

  • How do I modify a specific component within a active internalframe?

    I need to change an icon (toggle like) on a button within an internal frame when it is pressed.. I know what the active frame is. How do I address the specific component (wiithin a deskpane within a internalframe)?
    Thank you in advance,
    BAJH

    Here is a stripped down version of the program:
    i
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.OverlayLayout;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.UIManager;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    public class TestFrameButton extends JDesktopPane{
         private static final long serialVersionUID = 1L;
         JDesktopPane desk;
         JDesktopPane ifdesk;
         JScrollPane scrollpane;
         JInternalFrame iframe;
         JFrame frame;
         JList jList1;
         JInternalFrame currentframe;
         Integer currentframenumber;
         String currentframename;
         Boolean[] downuptracker;
         Integer deskwidth = 1000;
         Integer deskheight = 1000;
         Integer scrollwidth = 1000;
         Integer scrollheight = 1000;
         JButton DownUpButton;
         public static void main(String[] args) {
              TestFrameButton d = new TestFrameButton();
         public TestFrameButton(){
              downuptracker = new Boolean [99];
              frame = new JFrame("Test Frame Button");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              scrollpane = new JScrollPane(desk,
                        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollpane.setPreferredSize(new java.awt.Dimension(scrollwidth, scrollheight));
              desk = new JDesktopPane();
              desk.setPreferredSize(new java.awt.Dimension(deskwidth, deskheight));
              int i = 5;
              for (int j = 0; j <= i; j++){
                   UIManager.getDefaults().put("InternalFrame.icon", "");
                   iframe = new JInternalFrame("Internal Frame: " + j, false, true, false, false);
                   iframe.setName(String.valueOf(j));
                   iframe.setBounds(30*j, 30*j,265 , 80);
                   iframe.addInternalFrameListener(new InternalFrameListener(){
                        public void internalFrameClosing(InternalFrameEvent e) {
                        public void internalFrameClosed(InternalFrameEvent e) {
                        public void internalFrameOpened(InternalFrameEvent e) {
                        public void internalFrameIconified(InternalFrameEvent e) {
                        public void internalFrameDeiconified(InternalFrameEvent e) {
                        public void internalFrameActivated(InternalFrameEvent e) {
                             currentframe = e.getInternalFrame();
                             currentframename = e.getInternalFrame().getName();
                             currentframenumber = Integer.valueOf(currentframename);
                        public void internalFrameDeactivated(InternalFrameEvent e) {
                   iframe.setTitle("Internal Frame :" + j);
                   iframe.setVisible(true);
                   downuptracker[j] = true;
                   ifdesk = new JDesktopPane();
                   iframe.getContentPane().add(ifdesk, BorderLayout.CENTER);
                   DownUpButton = new JButton("Old Icon here");
                   ifdesk.add(DownUpButton);
                   DownUpButton.setBounds(0, 0, 130, 20);
                   DownUpButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (downuptracker[currentframenumber].equals(true)){
                                  // Colapse frame here and change icon
                                  DownUpButton.setText("New Icon here");
                                  downuptracker[currentframenumber] = false;
                             }else{
                                  // Expand frame here and change icon
                                  DownUpButton.setText("Old Icon here");
                                  downuptracker[currentframenumber] = true;
                   desk.add(iframe);
                   iframe.moveToFront();
              scrollpane.setViewportView(desk);
              JPanel overlayPanel = new JPanel();
              OverlayLayout overlay = new OverlayLayout(overlayPanel);
              overlayPanel.setLayout(overlay);
              this.setOpaque(false);
              desk.setOpaque(true);
              overlayPanel.add(this);
              overlayPanel.add(scrollpane);
              frame.add(overlayPanel);
              scrollpane.setVisible(true);
              frame.setSize(800,600);
              frame.setVisible(true);
    }Thank you in advance,
    BAJH - I will never multi-post again!

  • Assigning an ActionListener to an inherited JButton

    Dear all,
    I have a base JPanel class with a button, a border and not much else. This class is extended by 2 other classes in my application.
    I needed a means of associating an action with the button in my application's main class, so I added a static method addButtonListener to the base class, assuming that once I invoked this, the button would be 'activated' in all the panels inheriting from my base class. addButtonListener() simply invokes the button's addActionListener() method.
    Unfortunately this doesn't work, the ActionListener only gets linked to the button in one of the child classes (the first one that's instantiated).
    What's going on? The code for the base class is below...
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.EtchedBorder;
    import javax.swing.border.TitledBorder;
    public class LoadVolPanel extends JPanel {
         protected JPanel buttonPanel;
         protected static JButton loadButton;
         public static void addButtonListener(ActionListener a) {
              loadButton.addActionListener(a);
         public LoadVolPanel(String title) {
              super();
              setBorder(new CompoundBorder(
                        new TitledBorder(new EtchedBorder(), title), new EmptyBorder(3,
                                  5, 3, 5)));
              loadButton = new JButton("Load surfaces");
              loadButton.setMnemonic('L');
              buttonPanel = new JPanel();
              buttonPanel.add(loadButton);
              setLayout(new BorderLayout());
              add(buttonPanel, BorderLayout.SOUTH);
    }

    I apologise for the amount of the code I've posted but it does compile, and will hopefully show you what I'm trying to do.
    I would like:
    - the Load button to appear at the bottom of each tab in the parent JTabbedPane;
    - the Load button perform the same action in all panes;
    - to be able to assign an action to the Load button from the main class.
    Cheers!
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestClass {
         public class LoadVolPanel extends JPanel {
              protected JPanel buttonPanel;
              protected JButton loadButton;
              public void AddButtonListener(ActionListener a) {
                   loadButton.addActionListener(a);
              public LoadVolPanel(String title) {
                   super();
                   setBorder(new CompoundBorder(new TitledBorder(new EtchedBorder(),
                             title), new EmptyBorder(3, 5, 3, 5)));
                   loadButton = new JButton("Load surfaces");
                   loadButton.setMnemonic('L');
                   buttonPanel = new JPanel();
                   buttonPanel.add(loadButton);
                   setLayout(new BorderLayout());
                   add(buttonPanel, BorderLayout.SOUTH);
         public class LogPanel extends LoadVolPanel {
              public LogPanel() {
                   super("Log");
                   JTextArea ta = new JTextArea();
                   ta.setLineWrap(true);
                   ta.setWrapStyleWord(true);
                   ta.setEditable(false);
                   ta.append("The Load Surfaces button below kicks off\n");
                   ta.append("a shell script on a unix box\n");
                   ta.append("Output from the script appears here.\n");
                   JScrollPane scroll = new JScrollPane();
                   scroll.getViewport().add(ta);
                   add(scroll, BorderLayout.CENTER);
         public class LoadPanel extends LoadVolPanel {
              protected JList securitiesList;
              public final int VISIBLE_ROWS = 12;
              private JTabbedPane tabbedPane;
              private CheckListCell[] volCodes = { new CheckListCell("AMP"),
                        new CheckListCell("ALN"), new CheckListCell("ANN"),
                        new CheckListCell("ANZ"), new CheckListCell("ASX"),
                        new CheckListCell("AXA"), new CheckListCell("BNB"),
                        new CheckListCell("BIL"), new CheckListCell("BSL"),
                        new CheckListCell("CBA"), new CheckListCell("CML"),
                        new CheckListCell("CSR"), new CheckListCell("DJS"),
                        new CheckListCell("FOA"), new CheckListCell("FXJ"),
                        new CheckListCell("GNS"), new CheckListCell("GPT"),
                        new CheckListCell("IAG"), new CheckListCell("JHX"),
                        new CheckListCell("LEI"), new CheckListCell("MAP"),
                        new CheckListCell("MBL"), new CheckListCell("MIG"),
                        new CheckListCell("NAB"), new CheckListCell("NWS"),
                        new CheckListCell("NWSLV"), new CheckListCell("ORG"),
                        new CheckListCell("OST"), new CheckListCell("PBG"),
                        new CheckListCell("PBL"), new CheckListCell("PMN"),
                        new CheckListCell("QAN"), new CheckListCell("RIN"),
                        new CheckListCell("RIO"), new CheckListCell("SEV"),
                        new CheckListCell("SGB"), new CheckListCell("SHL"),
                        new CheckListCell("SSX"), new CheckListCell("STO"),
                        new CheckListCell("TAH"), new CheckListCell("TCL"),
                        new CheckListCell("TLS"), new CheckListCell("VBA"),
                        new CheckListCell("WBC"), new CheckListCell("WDC"),
                        new CheckListCell("WMR"), new CheckListCell("WOW"),
                        new CheckListCell("WPL"), new CheckListCell("WSF"),
                        new CheckListCell("ZFX"), new CheckListCell("CCL"), };
              public LoadPanel() {
                   super("Codes");
                   securitiesList = new JList(volCodes);
                   CheckListCellRenderer renderer = new CheckListCellRenderer();
                   securitiesList.setCellRenderer(renderer);
                   securitiesList
                             .setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                   securitiesList.setLayoutOrientation(JList.VERTICAL_WRAP);
                   securitiesList.setVisibleRowCount(VISIBLE_ROWS);
                   JScrollPane ps = new JScrollPane();
                   ps.getViewport().add(securitiesList);
                   JButton refreshButton = new JButton("Refresh Securities List");
                   buttonPanel.add(refreshButton);
                   add(ps, BorderLayout.CENTER);
         public final class CheckListCell {
              private String name;
              private boolean selected;
              public CheckListCell(String name) {
                   this.name = name;
                   selected = false;
              public String getName() {
                   return this.name;
              public void setSelected(boolean selected) {
                   this.selected = selected;
              public void invertSelected() {
                   selected = !selected;
              public boolean isSelected() {
                   return selected;
              public String toString() {
                   return name;
         public final class CheckListener implements MouseListener, KeyListener {
              private LoadPanel parent;
              private JList securitiesList;
              public CheckListener(LoadPanel parentPanel) {
                   parent = parentPanel;
                   securitiesList = parentPanel.securitiesList;
              public void mouseClicked(MouseEvent e) {
                   int index = securitiesList.locationToIndex(e.getPoint());
                   if (index == securitiesList.getSelectedIndex())
                        doCheck();
              public void mousePressed(MouseEvent e) {
              public void mouseReleased(MouseEvent e) {
              public void mouseEntered(MouseEvent e) {
              public void mouseExited(MouseEvent e) {
              public void keyPressed(KeyEvent e) {
                   if (e.getKeyChar() == ' ')
                        doCheck();
              public void keyTyped(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
              private void doCheck() {
                   int index = securitiesList.getSelectedIndex();
                   if (index >= 0) {
                        CheckListCell cell = (CheckListCell) securitiesList.getModel()
                                  .getElementAt(index);
                        cell.invertSelected();
                        securitiesList.repaint();
         public class CheckListCellRenderer extends JCheckBox implements
                   ListCellRenderer {
              private Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
              public CheckListCellRenderer() {
                   setOpaque(true);
                   setBorder(noFocusBorder);
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus) {
                   if (value != null)
                        setText(value.toString());
                   setBackground(isSelected ? list.getSelectionBackground() : list
                             .getBackground());
                   setForeground(isSelected ? list.getSelectionForeground() : list
                             .getForeground());
                   CheckListCell data = (CheckListCell) value;
                   setSelected(data.isSelected());
                   setFont(list.getFont());
                   setBorder((cellHasFocus) ? UIManager
                             .getBorder("List.focusCellHighlightBorder") : noFocusBorder);
                   return this;
         public static void main(String argv[]) {
              JFrame frame = new JFrame("Load Volatility");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(370, 330);
              TestClass myTest = new TestClass();
              JPanel logPanel = myTest.new LogPanel();
              LoadPanel loadPanel = myTest.new LoadPanel();
              JTabbedPane jtp = new JTabbedPane();
              jtp.addTab("Load Volatility", loadPanel);
              jtp.addTab("Log", logPanel);
              frame.getContentPane().add(jtp);
              frame.pack();
              frame.show();
    }

  • A focus question: button activated by mouse or by ENTE

    In the following program:
    If the program is run as is ? The button can be activated only by the mouse.
    If the part:
    // try {
    // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    // catch(Exception e) {
    // e.printStackTrace();
    is used, the button can be activated also by ENTER and the focus is the default.
    How to get the second option not using SystemLookAndFeel ?
    Which option is better for an application or an applet ?
    Help would be appreciated.
    import javax.swing.*;
    import java.awt.event.*;
    public class Focus extends JPanel {
    JButton b2;
    public Focus() {
    // try {
    // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    // catch(Exception e) {
    // e.printStackTrace();
    b2 = new JButton(("Is it ok?"));
    add(b2);
    b2.addActionListener(buttonListener);
    ActionListener buttonListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("Is it ok?")) {
    System.out.println("It's ok !!!");
    public static void main(String[] args) {
    JFrame fr = new JFrame();
         Focus fc = new Focus();
    fr.getContentPane().add(fc);
         fr.setVisible(true);
    fr.pack();

    dialog.setModal(true);beat you!
    You did provide code though :)

  • Opening HTML file using a Jbutton

    can anybody tell me how can I open an HTML file using a Jbutton.
    I have a help button on my menu of my GUI. I wanna open a html document using the help (jbutton)
    thank you

    call this class in your button action
    import javax.swing.JInternalFrame;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.JOptionPane;
    import javax.swing.BorderFactory;
    import javax.swing.border.*;
    import javax.swing.JDesktopPane;
    public class Taa extends JFrame implements HyperlinkListener{
         public JEditorPane hh;
         public JScrollPane ss;
    *Taa default constructor
    *@param Nothing
    *@return Nothing
    *@thorws nothing
    *@see descon
    public Taa(){
    //set top left image in the gui
    setIconImage(Toolkit.getDefaultToolkit().getImage("buttons/help.jpg"));
    try{
         File f=new File("Here you can put your html"such as"Help.htm");
         String s = f.getAbsolutePath();
         s = "file:"+s;
         URL url = new URL(s);
    hh=new JEditorPane(s);
    hh.setEditable(false);
    hh.addHyperlinkListener(this);
    catch (MalformedURLException e) {
         System.out.println("Malformed URL: " + e);
    catch (IOException e) {
         System.out.println("IOException: " + e);
         ss=new JScrollPane(hh);
         getContentPane().add(ss);
         setBounds(232,0,490,500);
         setResizable(false);
         show();
    *Implementation of HyperlinkEvent
    public void hyperlinkUpdate(HyperlinkEvent e) {
         if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
         linkActivated(e.getURL());
    *this method activate link
    *@param URL the URL
    *@return Nothing
    protected void linkActivated(URL u) {
         Cursor c = hh.getCursor();
         Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
         hh.setCursor(waitCursor);
         SwingUtilities.invokeLater(new PageLoader(u, c));
    *this class load help files
    class PageLoader implements Runnable {
    *Taa default constructor
    *@param Url the url,Cursor c
    *@return Nothing
    *@thorws nothing
    *@see descon
         PageLoader(URL u, Cursor c) {
         url = u;
         cursor = c;
    public void run() {
         if (url == null) {
              // restore the original cursor
              hh.setCursor(cursor);
              Container parent = hh.getParent();
              parent.repaint();
         } else {
              Document doc = hh.getDocument();
              try {
              hh.setPage(url);
              } catch (IOException ioe) {
              hh.setDocument(doc);
              getToolkit().beep();
              } finally {
              // schedule the cursor to revert after
              // the paint has happended.
              url = null;
              SwingUtilities.invokeLater(this);
         URL url;
         Cursor cursor;

  • A JButton, a mnemonic, and a missing action event.

    Does anybody have a clue as to why a JButton, when activated by a mnemonic, would highlight the button onscreen but NOT call the button's actionPerformed() method?
    Specifically, I have a (huge) application that consists of a main JFrame and any number of internal JDialogs launched (mostly) by buttons and menu items. The situation is arising when a dialog is closed without expressly placing focus on a component parented by the main frame. Once the dialog closes you can hit a mnemonic key combination and the button associated will 'depress' (turn grey) but not reset back to it's normal state, nor will the associated actionPerformed be called. A second usage of the mnemonic immediately following the first one WILL activate the button (and reset the visual state). This behaviour can be avoided by clicking on a component (other than a button) on the main frame before trying the mnemonic the first time, but that's not acceptable from a user's standpoint (this job would be sooo much easier without them! ;) )
    I know it's not possible to get specific without code examples (which aren't possible because I can't narrow down were it's happening in the 900+ GUI-side scripts) but I'd really appreciate anyone who could point me in the right direction to start investigating this phenomenon. Thx.

    Hi Yuki,
    Yeah, after I turn on detail JSF debugging as instructed by the book Core JavaServer Faces, I figured out I had a validation error. That solves the mystery.
    Thanks,
    Edmond

Maybe you are looking for