Creating array of buttons

I'm trying to create an array of buttons, but I keep getting a npe
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl<Container.java:1031>
at java.awt.Container.add<container.Java:352>
at ButtonArray.main<ButtonArray.java:26>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonArray{
static JLabel jl;
public static void main(String[] args){
JFrame jf = new JFrame();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
jl = new JLabel();
int count = 30;
JButton[] jbh;
jbh = new JButton[count];
//JButton[] jbh = new JButton[]{new JButton("1"), new JButton("2")};
for(int x=1; x<count; x++) {
     jbh[x] = new JButton(Integer.toString(x));
Container c = jf.getContentPane();
for(int i = 0; i < jbh.length; ++i){
p1.add(jbh);
for(int i = 0; i < jbh.length; ++i){
jbh[i].addActionListener(new ButtonListener());
c.add(p1, BorderLayout.NORTH);
p2.add(jl);
c.add(p2, BorderLayout.SOUTH);
jf.setSize(400,300);
jf.setVisible(true);
jf.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
System.exit(0);
static class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
jl.setText("Button" + evt.getActionCommand() + " was pressed");

Just spotted the error.
Your for loop adding buttons to the array begins at 1. Therefore there is a null still in position 0 of your array which you attempt to access in your next for loop.
[shakes fist at Enc]
Edited by: flounder on Aug 7, 2009 11:08 AM

Similar Messages

  • Creating an array of buttons in a jframe

    hi, i need help im trying to create a simple button game where there are 5x3 buttons in a jframe where the user can click on one to find the button with the prize on it, i know how to create the jframe but im trying to approch this in a object orientated way, with classes not a procedural way, and having no luck, any suggestions?

    Ok, here what you want, but don't forget dukes:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class MyGame extends JPanel{
        private Random rand ;
        private int rows;
        private int cols;
        private int prizeX;
        private int prizeY;
        public MyGame(int rows, int cols){
            //super(new GridLayout(rows, cols));
            super(new BorderLayout());
            this.rows = rows;
            this.cols = cols;
            JPanel p = new JPanel(new GridLayout(rows, cols));
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    JButton b =  new JButton(" Button [x="+i+", y="+j+"]");
                    b.addActionListener(new MyActionListener(i, j));
                    p.add(b);
            this.add(p, BorderLayout.CENTER);
            this.add(new MyReStartButton(), BorderLayout.SOUTH);
            rand = new Random(System.currentTimeMillis());
            prizeX = rand.nextInt(rows);
            prizeY = rand.nextInt(cols);
            System.out.println(prizeX+", "+prizeY);
        class MyActionListener implements ActionListener{
            private int x;
            private int y;
            public MyActionListener(int x, int y){
                this.x=x;
                this.y=y;
            public void actionPerformed(ActionEvent e) {
                if(x==prizeX&&y==prizeY){
                    JOptionPane.showMessageDialog(MyGame.this, " Winner !! ");
                }else{
                    JOptionPane.showMessageDialog(MyGame.this, " Try again ");
        class MyReStartButton extends JButton{
            public MyReStartButton(){
                super("Start new Game");
                addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent e) {
                        MyGame.this.prizeX = rand.nextInt(rows);
                        MyGame.this.prizeY = rand.nextInt(cols);
                        System.out.println(prizeX+", "+prizeY);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("MyGame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new MyGame(3, 5);
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

  • Connecting kurzweil sp88 to GB I want to connect my Kurzweil sp88 to GB. The Kurzweil has a baffling array of buttons and possible MIDI channels. It also has the old style MIDI plug ins. I've got the MIDI out connected to my MacBook Pro via USB adapter.

    I have my Kurzweil connected to my MacBook Pro via an adapter (old style MIDI from Kurzweil to USB adapter connecting to Mac). The Kurzweil has a baffling array of buttons and possible MIDI channels. Can anyone please tell me which of the channels I should use? Also, should I leave the MIDI In cable out of the Kurzweil? Thanks for as detailed an answer as possible. If you like you can respond directly to me at [email protected]

    First of all I do not own this keyboard. But a quick look at the manual (found on the internet) says that when first powered up the SP88 is in Internal Sounds mode. Meaning you hear the sounds selected when playing the keyboard. It also stated that the default Midi Transmit Channel is Midi Channel #1.
    Looks like you would need to go to the SP88 Keyboard's MIDI SETUP and simply select LOCAL OFF. Now the keyboard should be ready to transmit Midi Out only and no internal sounds should be heard.
    Next you may or may not need to do this but you might need to go into the Utilities Folder found in your Applications Folder on your Mac and double click AUDIO MIDI SETUP the keyboard Icon. Figure #1 below.
    Next you need to make a physical connection from the Midi Out of the SP88 to the Midi In on your Midi Interface. Figure #3 below. You may need to Click on Add Device first. Figure #2 below.
    In the examples shown below I have a Yamaha Electronic Drum Kit that is Midi Out only... not USB out. I had to plug a Midi cable from the Midi Out Port on the back of my Drum Module to the Midi In Port on the back of my Motu 828 Audio Inferface which is connected to my Mac. Next I created the Audio Interface and Drum Module "Devices" as mentioned above.
    I then double clicked on the Drum Module and made my Midi Out Selections. Figure #4 Below. And once it was setup and the icons closed I used my mouse to draw a virtual cable connection from the Drum Module Out to the Audio Interface In. Figure #3 below. This is how I got my Midi Devices to talk to one another.
    Once you have made your setup as I have outlined create a MIDI Instrument Track in Garageband, select an instrument for example a Piano then Record Enable that track in Garageband and see if you now hear what you are playing. In this example the SP88 is a Midi Controller only and you will only hear sounds selected in Garageband which is what you want.
    Keep in midi your setup may be different than mine. You can keep your SP88 Keyboard on the default Midi Channel #1. That would be a good place to start. Garageband receives Midi on all channels.

  • 9x9 array of buttons and not a single button worked

    im trying to build a 9 x 9 block composed of buttons. I used array of buttons.
    here's my code with my explanation and poor logic thinking details.
    public class ButtonArrayDemo extends JFrame implements ActionListener
    private JButton[] sButton;
    private int[] x;//manipulation purposes only
    public ButtonArrayDemo()
         JPanel buttonPanel = new JPanel();
         buttonPanel.setLayout( new GridLayout(9, 9) );
         sButton = new JButton[81];
         x = new int[81];
    // creates the buttons,action listeners, syntax is correct but
    // i doubt the logic
         for (int i = 0; i < sButton.length ; i++)
              JButton button = new JButton();
              button.setText(" ");
              button.addActionListener(this);
              sButton[i] = button;
              buttonPanel.add(sButton);
              x[i] = 0;
         getContentPane().add(buttonPanel,BorderLayout.SOUTH);
         setResizable(false);
    // what i want for this is that, when a button is clicked, it displays the
    //number 1 then increments by 1 if clicked again. Like,when i click a
    //blank button, it displays the number "1", if i clicked it again, it displays
    //the number 2. This goes on until number 9. When the button is clicked
    //on the 10th time, it leaves the button's text blank. Syntax is fine but
    //i doubt the logic.
    public void actionPerformed(ActionEvent e)
         int y;
         for(y = 0; y < sButton.length; y++)
              if(e.getActionCommand().equals(sButton[y]))
                   sButton[y].setText(Integer.toString(++x[y]));
                   if(x[y] == 10)
                   sButton[y].setText(" ");
                   x[y] = 0;
    Now, i created the main and compiled the program. The frames appeared complete with 81 buttons. But, when I click on any button,
    it does nothing. The button's text which is supposedly to change is not displaying anything. this is a vital thinking process for me and any help from someone would be very much appreciated.
    thanks for reading and i hope someone will respond to my problem.
    lots of thanks.

    I believe the problem is that you are using the actionCommand but you did not set the actioncommand for the buttons. I suggest you either set the action command for each button to a unique item or use getSource instead.
    Also, you might want to break out of your for loop once you find the correct button.
    Also, if the future use the code formatting tags and this probably should have been in the Swing forum.

  • Array of buttons and Event Structure

    I have a the same problem... I was wondering if you were able to find a soln.
    I have literally thousands of buttons and each button as a unique key code and unique name.
    For Example :  
    Button Name    – Key code #
    PUSH              - 1
    POP                 - 2
    PULL               - 3
    The way I program this simple algorithm is deadly painful. 
    1)      I create 1000 buttons by going to control->buttons.
    2)      Then I have to go through one by one to change the Boolean text to “PUSH,POP,PULL…”  
    3)      Then used the Event Structure, adding in all the controls names “PUSH, POP, PULL..” In side each event, I placed the key codes “1,2,3..”
    I have search and tried for weeks to find a better way, and still nothing comes to mind.  
    Please help.

    Hi Ben,
    Thank you for your reply, I have attached my try_code and a picture of the code I currently have.  I  am new in Labview, but I am confident that, there must be a easier way to make an array of buttons with different button name and an associated number to that button.  
    The 1st file, is to show you want I am currently doing, (painful)
    The 2nd file attached is some of the things i tried, I had great hope with my try_code, array_jan25.  But I couldn't get it.  I think I am very close.
    Thanks again,
    Attachments:
    ThePainfulWay.doc ‏63 KB
    Array_jan25.vi ‏42 KB

  • Pass a variable number into an Action method from an array of buttons

    Hello,
    I have created an array of buttons like so:
                       private javax.swing.JButton[] barray = new JButton[8];
    javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(K8055_Card_Control.JavaElectrodeSwitches1App.class).getContext().getActionMap(JavaElectrodeSwitches1View.class, this);
                 for (int i=0;i<8;i++)    // Create Output Check Boxes
              barray[i] = new JButton();
                            barray.setAction(actionMap.get("ButtonPressed"));
              barray[i].setName("Outbox"+ String.valueOf(i+1));
              barray[i].setText("Electrode " + String.valueOf(i+1));
    BoxLayout layout = new BoxLayout(jPanel1,BoxLayout.PAGE_AXIS);
    barray[i].setAlignmentX(JCheckBox.CENTER_ALIGNMENT) ;
    jPanel1.setLayout(layout);
    jPanel1.add(barray[i]);
    When a button is pressed it calls the method ButtonPressed()@Action
    public void ButtonPressed()
    // button pressed code here
    My problem is that once the button has been pressed I don't know how to find out which button called the method. Each button operates a different switch.
    I tried testing barray.isSelected(); however the ButtonPressed() method is only called once the button has released and is no longer selected.
    Any ideas?
    Thanks,

    Actually the answer to both of these questions is ActionEvent
    do for instance:
    JButton b = new JButton("test");
    JButon b2 = new JButton("test2");
    ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
      Object src = ae.getSource();
      String cmd = ae.getActionCommand();
      if (src == b) { //won't work unless you make b final
      //or
      if ("test".equals(cmd)) {
    b.addActionListener(al);
    b2.addActionListener(al);

  • How to create a rollover button effect in Captivate 7?

    Hi,
    I recently upgraded from Captivate 6 to Captivate 7 and am curious to know how I can create a rollover state for a SmartShape button. Basically, let's say I have a SmartShape being used as a button. What I want is to have the button have a glow effect and a shadow effect each time the mouse is hovered over it. Is there an easier way than having two objects on the slide -- one as the normal state and one the mouse hoever image. What I'm thinking is that the mouse hovered state image will have it's 'Visible in Output' set as unchecked and I can use an Advanced Action to show the object on mouse hover. Perhaps I can have the mouse hovered state image as a rollover SmartShape too?
    Nonetheless, this looks like too much work. If I have 10 clickables on the page for which I want rollover effects, I would need to have 10 additional objects with their rollover states -- just seems like too much, but perhaps that's the Captivate way. Or I am I missing the obvious?
    Any help would be appreciated.
    Thanks,
    Sean

    Most people would say the easiest way to achieve what you are talking about would be to just create your own custom image button in a graphics editor and give the Over state image having the glow effect that you want.
    If you decide to go that route, this tutorial describes the process of creating an image button:
    http://www.infosemantics.com.au/adobe-captivate/create-custom-image-buttons
    Another possibility is that you can use the Infosemantics Event Handler widget to trigger an Apply Effect action and use the Glow filter as the effect. 
    However, this may require some tweaking since it's not that easy to time effects that are applied via an advanced action.

  • Difference b/w create and createInsert button

    hi,
    what is the difference b/w create and createInsert button in ADF data control.

    first go through
    https://forums.oracle.com/forums/ann.jspa?annID=56
    next look
    http://jjzheng.blogspot.in/2010/04/create-or-createinsert.html
    ADF Faces & BC: Difference between Create and CreateInsert.

  • How to create user defined button in alv report

    how to create user defined button in alv report
    thnks in advance.

    Hi,
    U can define it the the PF-STATUS ( Menu for ALV ).
    For that u have to define it in the EVENTCAT.
    form z_eventcat  using    p_i_eventcat type slis_t_event.
      data: i_event type slis_alv_event.
      call function 'REUSE_ALV_EVENTS_GET'
        exporting
          i_list_type     = 0
        importing
          et_events       = p_i_eventcat
        exceptions
          list_type_wrong = 1
          others          = 2.
      if sy-subrc <> 0.
        message id sy-msgid type sy-msgty number sy-msgno
                with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      endif.
      clear i_event.
      read table p_i_eventcat with key name = slis_ev_top_of_page into
      i_event.
      if sy-subrc = 0.
        move 'TOP_OF_PAGE' to i_event-form.
        append i_event to p_i_eventcat.
      endif.
      read table p_i_eventcat with key name = slis_ev_pf_status_set into i_event.
      if sy-subrc = 0.
        move 'SET_PF_STATUS' to i_event-form.
        append i_event to p_i_eventcat.
      endif.
      clear i_event.
      read table p_i_eventcat into i_event with key name = slis_ev_user_command .
      if sy-subrc = 0.
        move 'USER_COMMAND' to i_event-form.
        append i_event to p_i_eventcat.
      endif.
    And in the DISPLAY
    call function 'REUSE_ALV_GRID_DISPLAY'
       exporting
         i_callback_program                = v_progname
         i_callback_pf_status_set          = 'SET_PF_STATUS'
         i_callback_user_command           = 'USER_COMMAND'
         i_callback_top_of_page            = 'TOP_OF_PAGE'
         i_grid_title                      = v_gridtitle
         i_save                            = 'A'
         is_layout                         = i_layout
         it_fieldcat                       = i_fieldcat[]
         it_sort                           = i_sortinfo
         it_events                         = i_eventcat
    IMPORTING
      E_EXIT_CAUSED_BY_CALLER           =
      ES_EXIT_CAUSED_BY_USER            =
        tables
          t_outtab                          = it_final
       exceptions
         program_error                     = 1
         others                            = 2
      if sy-subrc <> 0.
        message id sy-msgid type sy-msgty number sy-msgno
                with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      endif.
    *MENU SETTINGS.
    form set_pf_status using rt_extab type slis_t_extab.
      set pf-status 'ALV_MENU'.
    endform.                    "SET_PF_STATUS
    endform.                    " Z_EVENTCAT
    Now double click on ALV MENU nad u can create a button in the application bar.
    Regards,
    Pritha.

  • How Can I Create a Print Button on a PDF Using Acrobat Pro That Will Also Work on iOS?

    I created a Print Button on a PDF document using Adobe Acrobat Pro on my Mac.  The Print button works perfectly on different browsers on my Mac and on Windows (running under Parallels Desktop) as well.
    When I open the document on my iPad the Print button doesn't even appear.  I am guessing that this is a Flash issue but it may be more related to the fact the the action for the button is to access the Print menu item, which doesn't exist under iOS.
    Is there any way to create a Print button using Acrobat Pro that will work on a Mac and Windows but also on iOS?

    In order to initiate printing by clicking a button, the button has to have either an "execute menu item" type action or use the "print" JavaScript method. As you guessed, the former won't work since there are no menu items to execute, and the latter can only work if the particular PDF viewer you're using supports it. I'm not aware of any that do on iOS.
    The button doesn't appear because you're probably opening it in the default PDF viewer, which doesn't support forms at all. If you were to open the form in Adobe Reader, you'd see the button but it wouldn't work.

  • How To Create On Submit Button For Master_detail Page ?

    I have adf page that is master And detail view.
    i want to have one submit button for master and detail block

    Duplicate of  How To Create On Submit Button For Master_detail Page ?
    Please don'r post your question multiple times.
    Timo

  • To disable the horizontal scrollbar and to create a next button to navigate

    To disable the horizontal scrollbar and to create a next button to navigate through the records. At present I create a JSF page and drag and drop my table view and then using the Tuning property I have limited the number of records to be shown. But I need to add a button and then code it to display the next few records. Can someone kindly suggest a suitable mechanism to get this accomplished.
    Edited by: 888970 on Oct 2, 2011 10:15 PM

    Hi Erp,
    At present these are the entries that I have in my JSPX page.
    I have a Table, Iterator and a Input List of Values. As per the scenario, I want a few rows to appear on the table for which I wanted to disable the horizontal scroll bar and then once I click on the list of values it must prompt me with the remaining page numbers.
    Earlier there are about 150 records in the table. I want to show them as 15 per page.
    For which I have added the Iterator and a LOV component code in my JSPX page.
    <af:iterator id="i1"
    value="#{bindings.NsEventDetailsView1.collectionModel}"
    var="row"
    binding="#{pageFlowScope.testPageBean.myIterator}"/>
    <af:inputListOfValues label="Label 1"
    popupTitle="Search and Result Dialog" id="ilov1"/>
    Then I created the bean class as per the example.
    Below is the bean class:
    import javax.faces.event.ValueChangeEvent;
    import oracle.adf.view.rich.context.AdfFacesContext;
    import org.apache.myfaces.trinidad.component.UIXIterator;
    import org.apache.myfaces.trinidad.event.AttributeChangeEvent;
    public class TestPagebean {
    public TestPagebean() {
    public void i1ov1_valueChangeListener(ValueChangeEvent valueChangeEvent) {
    // Add event code here...
    private UIXIterator myiter;
    public void setI1(UIXIterator myiter) {
    this.myiter=myiter;
    public UIXIterator getmyiter() {
    this.myiter=myiter;
    public UIXIterator setmyiter() {
    return myiter;
    UIXIterator valueIterator = getmyiter();
    if (!valueChangeEvent.getNewValue().equals(valueChangeEvent.getOldValue())) {
    int newPage =
    Integer.parseInt(valueChangeEvent.getNewValue().toString());
    int pageStart = (newPage) * valueIterator.getRows();
    valueIterator.setFirst(pageStart);
    AdfFacesContext.getCurrentInstance().addPartialTarget(valueIterator);
    But i am getting errors in the bean class.
    1. Block expecting }
    2. public UIXIterator getmyiter() {
    this.myiter=myiter;
    Return Statement missing
    3. Block expecting {
    4. Type or variable 'valueChangeEvent' not found
    5. Method 'getNewValue' not found
    6. Method 'getOldValue' not found
    7. Method 'toString' not found
    Can you suggest a possible solution?

  • How to create a radio button on OA Page using Personalization

    I am trying to create a radio button on OA Page using Personalization. The item style , I can see is Message Radio Group.
    How to create Message Radio Button and bring them under one group.
    Thanks

    You should use jdev to define a radiogroup and radio buttons under that, wrap that definition inside a stackLayout in jdev, use personalization to add a stackLayout and extend the region which you had created earlier in jdev.

  • Is there a way to create an export button on a pdf form that will send form info into ongoing excel spreadsheet?

    I'm trying to see if there is a way to create a submit button on my pdf form that will export the form data into a saved (ongoing) excel spreadsheet. The end result i'm hoping for would be a spreadsheet that lists all the information i receive from each form.
    Any help would be greatly appreciated.
    Thank you,

    Not really. But you can combine the data from multiple forms into a single (new) spreadsheet via Tools - Forms - More Form Options - Merge Data Files into Spreadsheet...

  • How to create a "next" button out of image

    Hi all.
    I'm new to Dreamweaver and have no idea what I'm doing!  I'm a designer and not familiar with code.
    I've managed to get this far: I've created a teamplate and am using it successfully on subsequent pages.  My snag is that I want to create a "next" button out of an image.
    One forum poster suggested taking page_1.html and page_2.html and inserting a link between them. I get this, but in order to do so, it seems I have to detach my individual pages from the template in order to directly edit them.  Can I then somehow reattach them to the template so that I can continue to make other changes on one page that will update throughout?
    Any suggestions to a VERY green newbie that does not include copying and pasting code?  Is there a way to do this in design mode?
    thanks
    B.

    UPDATE:
    Nancy and Jon - and all future searchers with this question, I have found the answers!!!
    Here goes:
    MAKING A SIMPLE NEXT/PREVIOUS BUTTON OUT OF AN IMAGE IN DREAMWEAVER FOR THE CODE-RETARED DESIGNER:
    - Create a template which includes buttons for NEXT/PREVIOUS. The buttons should be sliced from a Photoshop file, or created using Div tags in Dreamweaver (see Tutvid.com for these tutorials - very good). The buttons should also be in their own separate Divs.
    - Select the individual Divs containing the buttons (one at a time), not the images themselves.
    - Go to Insert>Template Objects>Editable Region.
    - Give one Editable region the name of NEXT and the other editable region the name of PREVIOUS.
    - Save template file.
    - Go to page_1.html and now those buttons are selectable.  Choose the NEXT button and go to the properties panel and grab the little pick whip icon which is right beside the Link box. Drag and hold the pick whip onto your files panel and select page_2.html.  Do the same for each page.  From page_2.html onward, you also do this for the PREVIOUS button, only you select the page that comes before it, not the one after it.
    Viola!
    I really hope this helps out all you code-challenged designers like me!  I've searched everywhere and lo and behold, it was as simple as this.
    Thanks to you, Nancy, for twigging me into selecting the Div and not the graphic itself.
    BellyBuckle.

Maybe you are looking for

  • Because a USB device was drawing too much power from your computer, one or more of your USB devices has been disabled- in to 2days bought Macbook Air

    It has beeing used only an i phone 3GS for sync !!!

  • Ipod and itunes with windows

    I have connected by ipod to itunes before that it has updated my songs perfectly. I just tried to undate again, once i manually chose which songs i want on my ipod, and it says that it has updated it when really, nothing changed. All the songs on my

  • Some LCD panel info

    Hello all, Like quite a few people on this forum, I recently purchased a new MB 13" aluminum and have been very disappointed in the quality of the LCD panel. In particular, I feel like the viewing angle on this display is significantly worse than my

  • Series not defined for journal entry

    Hello Sir I have defined two series namely "SCPL"  and "New1"                 Start No    Last No SCPL        10001       3000 New1         3001        30000   Now i have made "SCPL" series as default for A/R Invoices and "New1" series as default for

  • Re: What is free and what do you pay for?

    Hello I have received an email from paypal confirming that a three month subscription for Skype at GBP39 has been debited to my account from [email protected] What's going on? I have not authoriosed this. I have a skype account, buit I havnt used it