Getting the label of a JButton in a for loop

hi,
I doing a project for my course at the minute and im in need of a bit of help. I have set up 1-d array of buttons and i have layed them out using a for loop. I have also added an annoymous action listener to each button in the loop. It looks something lke this:
b = new JButton[43];
for (int i=1; i<43; i++)
b[i] = new JButton(" ");
b.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
          System.out.println("..........");
}); // addActionListener
} // for
I want the "System.out.println( ..." line, to print out the "i" number of the button that was pressed but i cannot figure out how to do it. I cannot put "System.out.println(" "+i);" as it wont recognise i as it is not inside the for loop. Does anyone have any suggestions?
Thanks!!

class ButtonExample extends JFrame implements ActionListener{The OP wanted to have anonymous listeners, not a subclassed JFrame
listening to the buttons. I don't know if the following is the best design,
since the poster has revealed so little, but here is how to pass the
loop index to an anonymous class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
    private JButton[] buttons = new JButton[24];
    public JPanel createGUI() {
        JPanel gui = new JPanel(new GridLayout(6,  4));
        for(int i=0; i<buttons.length; i++) {
            final int ii = i; //!! !
            buttons[i] = new JButton("button #" + i);
            buttons.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
System.out.println("number " + ii);
gui.add(buttons[i]);
return gui;
public static void main(String[] args) {
ButtonExample app = new ButtonExample();
JPanel gui = app.createGUI();
JFrame f = new JFrame("ButtonExample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(gui);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);

Similar Messages

  • Good morning a few weeks ago  I send the request for the replacement program of my ipod nano 1st generation and they sent me the shipping box but I did not get the label to go back,  and I can not  return it , i need to you sent me again the box for retu

    Good morning a few weeks ago  I send the request for the replacement program of my ipod nano 1st generation and they sent me the shipping box but I did not get the label to go back,  and I can not  return it , i need to you sent me again the box for return the ipod

    Best thing would be to call Apple up again, and let them what has happened and they'll help you!

  • How to get the label on selectOneMenu selected item??

    Hi,
    I'm not able to get the label of the selected item in a selectOneMenu. The code I use to fill it is:
    <h:form id="formNacion" name="formNacion">
    <h:selectOneMenu value="#{modelRtbBean.nacion}" id="selectNacion" onchange="this.form.submit();">
    <f:selectItems value="#{dataRecoveryBean.naciones}" id="idItemsNacion"/>
    </h:selectOneMenu>
    </h:form>
    The dataRecoveryBean has this method to fill the content of the component (basically it creates an arrayList of selectItems by recovering data from a database):
    public ArrayList<SelectItem> getNaciones() {
    if ((naciones == null ) || (naciones.isEmpty()) ){
    naciones = new ArrayList<SelectItem>();
    HDBGeografico hdbGeo = new HDBGeografico();
    SqlMadd sqlmadd = new SqlMadd();
    try {
    AccessBD sscm = new AccessBD( );
    sscm.table(hdbGeo.getSqlNaci());
    // The AccessBD object has a reference to the resultset:
    ResultSet rs = sscm.getRS();
    while (rs.next()) {
    naciones.add(new SelectItem((String) rs.getString(1), (String) rs.getString(2)));
    sscm.Close();
    } catch (Exception e) {
    System.out.println(e.toString());
    return naciones;
    the modelRtbBean setNacion recovers the value, but I need its label too, because it's a kind of description that I use later.
    In the modelRtbBean setNacion method I'm able to access the UISelectItems object, but I cannot get the selected item itself
    public void setNacion(String nacion) {
    FacesContext fc = FacesContext.getCurrentInstance();
    if (fc != null) {
    UIViewRoot viewRoot= fc.getViewRoot();
    System.out.println(viewRoot.getViewId());
    HtmlSelectOneMenu selNac = (HtmlSelectOneMenu)viewRoot.findComponent("bodySTB:formNacion:selectNacion");
    if (selNac != null) {
    System.out.println("Nacion value-htmlSelectOneMenu :" + selNac.getValue() );
    System.out.println(selNac.getAccesskey() + selNac.getTitle() + selNac.toString());
    UISelectItems uis = (UISelectItems)selNac.findComponent("idItemsNacion");
    if (uis != null) {
    System.out.println("I have the element...");
    this.nacion = nacion;
    How could it be accessed this selected item label ??

    I finally did it as you suggest, but I found another way to access the label (I don't know if it could be useful for anybody but here it is) :
    In the setter method linked to the SelectOneMenu, you can put in this code:
    FacesContext fc = FacesContext.getCurrentInstance();
    if (fc != null) {
    UIViewRoot viewRoot= fc.getViewRoot();
    System.out.println(viewRoot.getViewId());
    HtmlSelectOneMenu sel = (HtmlSelectOneMenu)viewRoot.findComponent("viewName:formName:selectOneName");
    if (sel != null) {
    UISelectItems uis = (UISelectItems)sel.findComponent("idItemsName");
    if (uis != null) {
    ArrayList<SelectItem> listElem = (ArrayList<SelectItem>) uis.getValue();
    You could put in in the value item of each SelectItem it's index position in the list, so in the setter method
    of the bean linked to the selectOneMenu you would get the index of the selected item as the parameter of the method
    int index = 1; // For easyness in this example
    System.out.println("Label: " + listElem.get(index).getLabel() + " Value: "+ listElem.get(index).getValue());
    Thanks !!!

  • Can we get the label name of the particular oracle field using open script

    hi
    can we get the label name of the oracle fields like column name ORDER NUMBER instead of ORDER_ORDER_NUMBER_0 when recording using openscript.

    Good morning
    Do you develop functional or load test scripts?
    I don't think we can in both cases because this is really the name of the field + the index.
    The zero refers to first line normally (then 1 for second line and so on).
    "Order number" is maybe the display label which is not enough to recognize and interact with a field.
    May I ask why you want this, then it could help me (us) to give you a good solution/workaround.
    Cheers
    JB

  • What is the code to get the  Label of  radio button item at runtime?

    Hi All
    I am working on forms 10g(version 10.1.2.0.2 ) with Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 on windows 2000 platform.
    My requirement is to dynamically get the label of the radio button item in a radio group.I am able to get the label of the radio group as shown below
    Item :Radio group
    Label : Gender
    IF m_type = 'RADIO GROUP' THEN
         m_label:=Get_Item_Property(m_Item ,label);
    END IF;
    There two Radio buttons inside this radio group which are
    item     : Radio button
    Label : Male
    item :Radio button
    Label :female
    What is the code to get the label of radio button(i.e) male and female ?
    How will I get the count of radio buttons in a radio group at runtime?
    Regards
    Mohan

    But you have to provide the button name which cannot be get at runtime.
    This is a lack of information that the Dev team would correct !
    Francois

  • How do I get the Label for a Front Panel Control to appear in the Block Diagram but not on the Front Panel?

    How do I get the Label for a Front Panel Control to appear in the Block Diagram but not on the Front Panel? On the Front Panel I am making a complex control that consists of a Slider and a Numerical Input box. Both Controls display the same information and either can be used for Input. When one changs, the other is made to display the same value.
     But I only want the Slider to display the Label on the Front Panel, to avoid confusion. On the Block Diagram however, I want both controls to display their Labels so that I know what they are. How do I display the Label for a Control on the Block diagram, but not display its Label on the Front Panel?

    No.  The Label Visible property is separate for the front panel control label and the block diagram terminal label.
    How did you start out with the block diagram's label not being visible?  Whenever I drop a control or indicator, the label is always visible on both the FP and BD by default.  Maybe there is a LabVIEW option that causes new controls/indicators not to have their labels visible by default, but I have yet to find it.  I don't think an item should ever be dropped without the label visible, good LabVIEW coding practice demands that the labels for control terminals on the block diagram be visible so that you know what control or indicator a wire is going to.
    That being said, I have seen a lot of VI's posted where the label for the terminal on the BD is not shown (against good programming practice.)  I've gone to the BD and right clicked to show the label.  Sometimes, the people have an empty label (which will turn off the visibility for both the FP and BD) and I'm forced to add some text of my own into the label so I can figure out what their code is doing.  When I add some text to the label, at that time, I find both the BD and FP labels become visible.
    Are you dealing with controls that have empty labels to start?
    Good programming practices:
    1.  Always have a name for all of your controls, never use and empty label by deleting the text in the label.
    2.  Make the labels unique.  For example, don't have two controls both called Stop.  How do you know quickly know which terminal relates to which control?
    3.  Always show the labels on the block diagram, so you know the function of a control's terminal.  If you want to hide the label on the FP, that's okay.
    4.  If you want a different label to appear on the FP than whatever you actually called the control, then use the caption.  You can hide the label and show the caption.  This is useful if you need to programmatically change what the "label" is on the front panel such if you are making an application that needs to change its user interface such as for a foreign language.

  • I am trying to update ITunes from 10.4 to 10.5 I have tried from both the program, and from a download on Apple's website. Regardless, I get the following error messages: (1) Installation package for iTunes cannot be found. Try installing to find the inst

    I am trying to update ITunes from 10.4 to 10.5 I have tried from both the program, and from a download on Apple's website. Regardless, I get the following error messages: (1) Installation package for iTunes cannot be found. Try installing to find the installation package 'iTunes.msi' in a folder from which you can install iTunes.  I can't find this folder. I have tried to completely unistall iTunes through the Control Panel, but it wouldn't let me: I tried going directly to the files themselves, but cannot uninstall. Any help would be greatly appreciated. System OS: Win XP SP 3.

    Set the permissions for Everyone in the folder in which CCPackager created, to "Read/Write" enabled. This is strange since there is only an administrator account on the Mac (and that account already has read/write), but it seems to resolve the issue.

  • I cant sign in to i-cloud with my new apple id  i signed out of the old one and when i try to log in i just get the 'thinking about it' logo. this lasts for ages and doesn't sign me in.  help!

    Hi, i have recently purchased an i-phone 4s and had been merrily playing away and set up an i cloud account.  However when i tried to access i cloud from my pc i couldn't verify it.  I had to change my apple id because i no longer had access to my old e-mail.  I managed to sort out my i-phone and change all the  accounts to my new apple i.d (except game centre? don't know how to do that yet.)  but when i signed out of my old i-cloud account on my pc and tried to sign in with my new apple id it just tries to connect (i get the i'm thinking about it wheel) for ages; not allowing me to log on.
    Help!

    Content (apps, music, ibooks, films etc) is tied to the account that originally downloaded it, so if the iBooks app was downloaded using the account that you used to share with your ex then only that account can download updates to it. As it's a free app you could delete it and re-download it under your own account - and then re-download your ibooks into it (or copy the books to your computer's iTunes first via File > Transfer Purchases and then sync them back to the app).

  • I try to export my Imovie and I always get the error code"Unable to prepare project for publishing...File already open with write permission"  it even does it when I am just trying to export to my external hard drive to save the file

    I try to export my Imovie and I always get the error code"Unable to prepare project for publishing...File already open with write permission"  it even does it when I am just trying to export to my external hard drive to save the file

    Thanks!!! I had same error (with -49) and the mac had an external hard drive attached.. and it was doing a backup.  Stopped, disconnected and the project exported!

  • How to get the list of users who has access for list of tcodes.

    How to get the list of users who has access for list of tcodes.

    Go to transaction SUIM, this has a number of reports for users/authorisations
    open the Where used>Autorization Values>In Users
    and double click to execute
    in authorisation object, enter S_TCODE
    then press the "Enter Values" button
    It will offer entry boxes to put the transaction code you are interesed in.
    Then execute and the list of users with access to this transaciton code will be returned.

  • HT201272 My computer was acting up so i had to restore it and i lost everything. how do i get the songs back that i already paid for?

    My computer was acting up so i had to restore it and i lost everything. how do i get the songs back that i already paid for?

    The easiest way to get back missing items?  Restore your whole hard drive with all your irreplaceable things like photos in about 20 minutes from the backup clone you make on a regular basis.
    Downloading (using iOS or computer) past purchases from the App Store, iBookstore, and iTunes Store - http://support.apple.com/kb/ht2519 - enabled with iTunes 10.3 and newer; not all media formats are available in all countries (see: iTunes in the Cloud and iTunes Match Availability by Country - http://support.apple.com/kb/HT5085); apps, books (not audiobooks), music, t.v. shows, and movies (some - not all studios have permitted this).  Downloading previously purchased movies and TV shows requires iTunes 10.6 or later.  Discontinued items not available. For items not included in the iCloud list (e.g., ringtones), or locations or computer systems where iCloud is not (yet?) available, you only get one download per fee paid.  Apple notes it is your responsibility to back up your purchases.
    Select the store on the left side of iTunes.
    Click on Purchased on the right side under Quick Links.
    You can re-download your available previous purchases.

  • I keep getting notified I have an update available but when I try to update I get the following msg ,"You have updates available for other accounts". I only have one account with apple and purchased the software when I got my macbook in Aug 2012.

    I keep getting notified I have an update available but when I try to update I get the following msg ,"You have updates available for other accounts To update this application, sign in to the account you used to purchase it.". I only have one account with apple and the software was preinstalled when I purchased my macbook in Aug 2012 with that account. Has anyone had this problem or know how to find out what account apple needs?

    You log into the App store using the same Apple ID you used to set the computer up, verify that none of your apps are hidden and that they have all be accepted and then download and install the update
    for help contact the App store support - link is on the right ot the App store window
    LN

  • The App Store says I have updates for I-Photo and Garage Band.  When I try to update I get the following message: You have updates available for other accounts  To update this application, sign in to the account you used to purchase it.  I only have 1 acc

    The App Store says I have updates for I-Photo and Garage Band.  When I try to update I get the following message: You have updates available for other accounts  To update this application, sign in to the account you used to purchase it."  Both apps came with my computer and as far as I know I only have one Apple account.  Any thoughts?  Thanks.
    Karen

    Thanks for you reply.  I'm 99% positive that I'm using the user id and password that I used to set up my computer.  That's why I'm stumped.  I read the solution someone else suggested (type your user name without @gmail and create a new password.  When I tried it, I was asked for my birthday.  It didn't recognize it.  I know I got my birthday correct. Oh well...
    Karen

  • I am trying to sync my ipad with my computer and keep getting the following message: iTunes could not check for an update to the carrier settings in your ipad.  an unknown error occurs (1631).  what do I do??

    am trying to sync my ipad with my computer and keep getting the following message: iTunes could not check for an update to the carrier settings in your ipad.  an unknown error occurs (1631).  what do I do??

    The search bar can be very valuable...........
    In using it, I found out other's have had this issue and it likely means you have a 3G iPad?  If you do, go into settings and turn off cellular data, then try to update again and you should be OK........

  • Exporting photos for UHDTV or Native 4K TV, what are the best settings ? (File: Quality File: Color Space, Image Sizing and resolution)   Or in other words; How can I get the smallest files but keep good quality for display on new UHDTV

    Exporting photos for UHDTV or Native 4K TV, what are the best settings ? (File: Quality File: Color Space, Image Sizing and resolution)   Or in other words; How can I get the smallest files but keep good quality for display on new UHDTV

    You're welcome, and thank you for the reply.
    2) Yesterday I made the subclips with the In-Out Points and Command-U, the benefit is that I've seen the clip before naming it. Now I'm using markers, it's benefit is that I can write comment and (the later) clip name at once, the drawback is that I have to view to the next shot's beginning before knowing what the shot contains.
    But now I found out that I can reconnect my clips independently to the format I converted the master clip to. I reconnected the media to the original AVI file and it worked, too! The more I work with, the more I'm sold on it... - although it doesn't seem to be able to read and use the date information within the DV AVI.
    1) Ok, I tried something similar within FCE. Just worked, but the file size still remains. Which codec settings should I use? Is the export to DV in MOV with a quality of 75% acceptable for both file size and quality? Or would be encoding as H.264 with best quality an option for archiving, knowing that I have to convert it back to DV if I (maybe) wan't to use it for editing later? Or anything else?
    Thank's in advance again,
    André

Maybe you are looking for

  • How to create a BAM database in enterprise version

    Hi, I need to configure and create a BAM database for my client in an AL Process Interaction installation. I tried to follow the documentation to create the BAM schema, but was not successful. It threw me a message telling me the Driver was not found

  • Windows fax and scan disconnects prematurely then redials

    windows fax and scan disconnects prematurely then redials to SOME but not all of my contacts SO I have been using the dependable Canon FAX software through my MX860, same MS Contacts address book, same win8.1-64 fickle OS

  • Flex 2 14 Battery Level Dropped from 57 to 7 in seconds

    I've been using my Flex 2 14 for around 3 months. However, recently I've encounter a situation whereby my battery level had dropped from 57% to 7% in split second when I'm not plugged in. I was wondering could it be an manufacturing defect and what s

  • Random Green Frames in Premiere Render and Export Files

    Hello! I just switched a new MacBook Pro and am having a render issue in Premiere CC. Random green frames pop up sporadically throughout my video. This happens both on my rendered timeline and in the exported file. It seems to affect the clips with h

  • Spam with contact requests

    So a while ago like a month ago I stopped talking to this one person.  He started to get kinda strange acting wierd so I blocked him, but ever since then I have been getting contact requests from him.  It is so bad every day it's a diffrent person to