Gui - making an array of JButtons to make a grid

how do i declare an array of JButtons to make a 16x16 grid? here is an example:
JPanel grid = new JPanel();
grid.setLayout (new GridLayout(16,16));
Container content = frame.getContentPane();
ImageIcon icon = new ImageIcon("picture.gif");
JButton[][] element = new JButton[16][16];
for ( i = 0; i < 16; i++ )
for ( j = 0; j < 16; j++)
grid.add(element[i][j].setIcon(icon));
content.add(grid);
is that correct at all? it returns this error:
'void' type not allowed here
grid.add(elem[i][j].setIcon(icon));
the caret points to the open parenthesis in setIcon(icon).
if an array of JButtons doesnt work at all, is there an alternative? my program allows the user to arrange various bricks, etc. to create a maze.

A 2-dimensional array of JButtons is perfectly possible, provided you write valid Java code. That's all the compiler is complaining about. And also, you forgot to create any button objects to go in the array. Try something like this:for ( i = 0; i < 16; i++ ) {
  for ( j = 0; j < 16; j++) {
    element[i][j] = new JButton();
    element[i][j].setIcon(icon);
    grid.add(element[i][j]);
content.add(grid);That will get you started. Of course those buttons won't do anything until you add listeners to them, but that's your next challenge, I suppose.
(By the way, there's a bug in the code that runs this forum. Wherever you see "<i>" in the code, alter it to use the correct rectangular brackets.)

Similar Messages

  • Is it possible to make an array of JButtons?

    is it possible to make an array of JButtons?

    Note that this doesn't create any JButtons, just the array!

  • How to create an array of JButtons and How to implment it ...

    This is what i want to do - I want to create an array of JButtons that has 8 rows of 8 buttons, could someone help me with this (im creating a checkers board) all i need is the array of buttons and them in 8 rows of 8 buttons .... im pretty confident in the way of making them do what i want but need help getting it up and running .... please note it is to be done in the swing environment and not in a applet or anything - ie in a JPanel and a JFrame .... any help would be GREATLY appreciated.

    U can try this
            JButton b[][] = new Button[8][8];
         setLayout(new YourLayout());
         for(int i =0; i<8; i++)
              for(int j =0; j<8; j++)
                   b[i][j] = new Button("Test");
                   b[i][j].addActionListener(new YourAction());
                   add(b[i][j]);
         }               

  • Using NetBeans Matisse to build a form with an array of JButtons

    With Matisse I can build a form with a lot of buttons on it, but i want to use a 2-dim array of JButtons so that I can easily access the buttons. How should I do this?

    Code it by hand. It's not that hard.
    JButton [][]buttons = new JButton[NUM_ROWS][NUM_COLUMNS];
    for (int row = 0; row < NUM_ROWS; row++) {
       for (int row = 0; row < NUM_ROWS; row++) {
          buttons[row][col] = new JButton();
          // set other properties of buttons[row][col]
    }If there is a lot of stuff, you could even make a separate method for creating a single button:
    private JButton createButton()
       JButton button = new JButton();
       // whatever else
       return button;
    }Then, in the "for" loops:
    buttons[row][col] = createButton();

  • Return an array of JButtons - Is this possible?

    Is it possible to return an array of JButtons? I have madean array of JButtons and assigned them anonymous listeners as they each do the same thing so i only had to do one in the for loop creation
    the idea is that i want to ship this code out to a method called createButtons and call it in the make frame method, but i cant seem to find a solution that actually works
    thanks

    JustSomeGuy wrote:
    If you went to your teacher and asked them how they felt about [the java forums], and under what circumstances it may be considered cheating, I think you will be suprised by the answer. Most teachers actually want you to learn, big shocker I know.
    JSGJSG.kudos++;
    compSciUndergrad wrote:
    if you want to tell me your opinions i am all ears, i hope they are not to harsh :SI'm of the opinion that at least 90% of students who are concerned about being seen as cheating are only concerned because they feel that they are cheating. Furthermore atleast 90% of students who "feel" that they are cheating have perfectly valid concerns, because they are in fact cheating.
    In my humble opinion it would be better for all concerned if cheaters did get caught, and sooner rather than later... because when they hit the real-world, where there really is no-one to cheat off, cheaters allways seem to come-a-cropper, big-time... because they also lie about there total lack of progress, in a shortsighted attempt to cover up there total imcompetence... too often taking those who entrusted them to actually do the friggin job down with them.
    Lots of good people getting skinned-alive by a pack of feral know-nothing friggin lawers, all because some moron kid tells a pack of lies, and thinks he's gonna get away with it come crunch time. Ummm... No thanks. Ta.
    So, much better to delineate between the competent and the not-competent programmer at the paedogogical stage. Eh what?
    I wouldn't class posting a bit of code on a forum as lay-down-mazaire proof positive that "He's a cheat". My concern is that you are actively concerned (paranoid even), which is indicative that you have actually cheated in the past; and plan to do so in the future. That's all.
    Cheers. Keith.

  • Making an Array of Textblocks and displying on the screen when the app is running

    Hello everyone
    I am new to this UI development. I am making a reverse game model and I want show my
    character array contents on text-blocks. I want to make an array of these text-blocks  and show them on screen
    if there is another simple method please suggest me.

    Hello Madhusoodan,
    I'm not sure if you mean WPF application since I haven't saw anything related to WPF. A UI develop can related to so many UI technologies, for example, WPF, WinForm...
    Anyway, if you mean WPF application, you need to know how WPF can add controls at runtime.
    For example, if you have a Grid and want to add textbox, see here:
    https://msdn.microsoft.com/en-us/library/System.Windows.Controls.Grid(v=vs.110).aspx 
    // Add the TextBlock elements to the Grid Children collection
    myGrid.Children.Add(txt1);
    myGrid.Children.Add(txt2);
    myGrid.Children.Add(txt3);
    Just create a loop and put your array of textbox in to the grid:
    textarray[i] = new TextBox();
    textarray[i].Height = 30;
    textarray[i].Width = 50;
    textarray[i].MouseDoubleClick += this.OnMouseDoubleClick;
    uniformGrid1.Children.Add(textarray[i]);
    Regards
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • C++ making an array of zeros?

    Hi, Im trying to make an array that will be filled with data later, but I keep getting the following error when compiling:
    error: incompatible types in assignment of of 'int*' to 'int[10]'
    Im using the following line:
    int counter[10]={0}
    What needs to be changed? I read everywhere online and this is how they recommend doing it.

    Hey guys, I tried all the suggestions provided and they all give me different kind of errors =/
    Heres my code, "counter" is the array im trying to make that has a size of "height". can anyone see a reason why Id be getting errors trying to do this?
    #include <stdio.h>
    #include "CImg.h"
    #include <vector>
    using namespace cimg_library;
    //main program
    int main()
    CImg<unsigned char> img("xray.jpg");
    const unsigned int width = img.dimx();
    const unsigned int height = img.dimy();
    //converts the image to black and white
    img.RGBtoYCbCr().channel(0).resize(-100,-100,1,3).RGBtoLUT(CImg<>(2,1,1,3).fill(0.0f,255.0f),false);
    //displays image
    CImgDisplay display(img,"Black and White");
    while (!display.is_closed)
    display.wait();
    printf("The height of the image is %d\n",height);
    printf("The width of the image is %d\n",width);
    //counter array
    int counter[10];
    std:fill( counter, counter+10, 0);
    for (int i=0;i<width;i++)
    for (int j=0;j<height;j++)
    for (int k=0;k<3;k++)
    if (img(i,j,0,k)=0) {
    counter=counter+1;
    printf("%d",counter);
    return 0;

  • Make a grid menu using an array

    Hi,
    I was wondering if there is a way to make a menu of buttons from an array arrange themselves in a 3x3 grid.
    I have used code i have gotten from this forum to place them next to each other onto the stage (which was quit awesome) and i have found code to place them in a rotating cell from an array but is it possible to do it as a grid?
    Any help would be great

    use Math.floor and the modulo operator to construct grids:
    var xSpace:int = 100;
    var ySpace:int=100;
    var rowNum:int=3;
    var colNum:int=3;
    for(var i:int=0;i<yourarray.length;i++){
    yourarray[i].x=xSpace*i%rowNum;
    yourarray[i].y=ySpace*Math.floor(i/colNum);

  • How do i create a GUI which links to other GUI's by pressing a JButton

    hi;
    i am trying to write a small program which reads a text file and which can update and save to the
    file as well as just view it. This i can do, but, i intend to create a main GUI from which you can
    select JButtons which will bring up different GUI's depending on which JButton has been pressed.
    i.e. one GUI for viewing certain data, another for updating the file etc....
    is this possible? and if so, how?
    cheers
    IK

    I did something similar. I had a Dialog which used the BorderLayout, the North was a title/section info, the Center part was to be changed on a button click to a different panel, the South was navigation like Next, Back, and Cancel/Finish. I got everything to work, but when I clicked the button and the method updated the center panel, it would not change to the new panel. I never figured out why it didnt do it.

  • Make a grid only appear on top another of another object

    hi everyone
    having trouble with trying to make a grid only appear  when its over another object. Basically i'm trying to lay 45 degree  lines over a circle, but i only want the grid lines to appear over the  circle and not outside.
    any suggestions without scissor tooling the lines outside the circle and it not looking good.
    very new user to illustrator so sorry if this is a dumb question

    You could use the polar grid tool
    You could use pathfinder's divide function, but that will also cut the circle into 45 degree sections.
    You could turn your lines and shape into a Live Paint Group and then use the Live paint Selection tool to just select the overhanging segments and delete them

  • How to make a grid column a linked column?

    Is there any way to make a grid column a linked column?
    I have a cardcode column in a grid, which I want to link with BP master link object.  If I try to do it the same way I do for matrix, it gives me 'specific cast not valid' error; whereas the same property works fine with matrix.
    help will be appreciated...
    Binita

    You need to do the following:
    string colUid = "yourUid";
    oGrid.Columns.Item(colUid).Type = BoGridColumnType.gct_EditText;
    EditTextColumn col = (EditTextColumn)oGrid.Columns.Item(colUid)
    col.LinkedObjectType = "2"; //2 = Buisness Partner (The id behind the BoLinkeObjectType as a string)

  • I want to make a grid. Apple said Pages will do the job. I need to change the grid to 1 in. x 1 1/2 in. squares. What tutorial can I use to show me how to do this?

    I want to make a grid. Apple said Pages will do the job. I need to change the grid to 1 in. x 1 1/2 in. squares. What tutorial can I use to show me how to do this?

    A calendar is not difficult nor does it take long once you know where the dates fall.
    Start with a basic month template table.
    1. Click on the table icon on the Toolbar to create a basic table for one month
    2. Click on the resultant table > Inspector > Table > Headers & Footers > 2nd button > 1
    3. Inspector > Table > Body Rows: 6 > Body Columns: 7
    4. Inspector > Metrics > Size > Width: 7 cm/in > Height: 7 cm/in
    You can drag resize the whole month to your liking afterwards
    5. Select the entire header row > Inspector > Table > Edit Rows & Columns > Merge Cells > Type in a month
    6. Type Mon in first cell & Tue in 2nd cell of of 2nd row > Select both cells and drag the white dot in the bottom right corner sideways to fill the cells with the days
    7. Do the same with the dates in the cells below
    8. You can fill the spare dates at the beginning and end of the month if you like and maybe change them to a paler grey.
    9. Style and position the text as you like it.
    10. If you don't want to see the grid or want different strokes, colors etc:
    Inspector > Table > Cell Borders/Cell Backgrounds etc
    When you have the first month looking the way you want, option drag out copies sideways to make the rest of the months.
    Peter

  • Mapping KeyStrokes to an array of JButtons

    Hi. I'm working on a calculator program. It has a scrollPanel with an uneditable JTextPane at the top and a 10x4 gridJPanel of buttons at the bottom. All the buttons are generated at once, as part of a 40 button JButton array.
    Here's the code where I generate the buttons...
    String[] buttonNames =
                        "ans", "rand", "back", "clear",
                        "abs", "e", "pi", "inv",
                        "sin", "cos", "tan","rad",
                        "csc", "sec", "cot", "mod",
                        "E", "log", "ln", "^",
                        "sqrt", "(", ")", "/",
                        "1", "2", "3", "*",
                        "4", "5", "6", "-",
                        "7", "8", "9", "+",
                        "0", ".", "+/-", "enter"
    for (int i=0; i<40; i++)
                        buttons[i] = new JButton(buttonNames);
                        buttons[i].setPreferredSize( new Dimension(30, 35));
                        buttons[i].addActionListener(this);
                        add(buttons[i]);
    The buttons all have the same action assigned to them, as you can see. In the code for the action, what to do is determined by if statements. Here's a block of code from there...
    public void actionPerformed(ActionEvent e)
                   JButton whichClicked = (JButton)e.getSource();
                   else if (whichClicked.getText() == "/")
                        try
                             doc.insertString(doc.getLength(), "/", null);
                        catch(Exception ble) {}
                        expression = expression + "/";
                        lastEntered = "operator";
                   else if (whichClicked.getText() == "1")
                        try
                             doc.insertString(doc.getLength(), "1", null);
                        catch(Exception ble) {}
                        expression = expression + "1";
                        lastEntered = "number";
                   else if (whichClicked.getText() == "2")
                        try
                             doc.insertString(doc.getLength(), "2", null);
                        catch(Exception ble) {}
                        expression = expression + "2";
                        lastEntered = "number";
                   else if (whichClicked.getText() == "3")
                        try
                             doc.insertString(doc.getLength(), "3", null);
                        catch(Exception ble) {}
                        expression = expression + "3";
                        lastEntered = "number";
                   else if (whichClicked.getText() == "*")
                        try
                             doc.insertString(doc.getLength(), "*", null);
                        catch(Exception ble) {}
                        expression = expression + "*";
                        lastEntered = "operator";
    //AND SO ON AND SO FORTH...You get the idea. Anyway, what I want to do is somehow make it so that I can assign KeyStrokes to certain buttons (for instance, pressing 3 on the NumPad of the keyboard will go to the action for the "3" JButton and add 3 to the text pane), to expedite the process of entering numbers into the JTextPane. However, the JTextPane is uneditable, so that can't be done directly.
    Will simple InputMaps and ActionMaps work? Does anybody have any ideas?
    I appreciate the help - thanks in advance
    Nick

    Never mind. I figured it out myself. For anyone who's interested / for everyone's future reference, I used arrays and for loops to map specific keys to specific buttons.
    Here's what I finally ended up with.
         class ButtonsPanel extends JPanel
              ButtonsPanel()
                   setLayout(new GridLayout(10,4));
                   setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
                   String[] buttonNames =
                        "ans", "rand", "back", "clear",
                        "abs", "e", "pi", ">deg",
                        "sin", "cos", "tan",">rad",
                        "csc", "sec", "cot", "mod",
                        "E", "log", "ln", "^",
                        "sqrt", "(", ")", "/",
                        "1", "2", "3", "*",
                        "4", "5", "6", "-",
                        "7", "8", "9", "+",
                        "0", ".", "+/-", "enter"
                   Action buttonClicked = new buttonClickedAction();
                   for (int i=0; i<40; i++)
                        buttons[i] = new JButton();
                        buttons.setPreferredSize( new Dimension(30, 30));
                        buttons[i].setAction(buttonClicked);
                        buttons[i].setText(buttonNames[i]);
                        add(buttons[i]);
                   int[] buttonsWithKeyBindings = {2,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39};
                   String[] keyBindings =
                        "BACK_SPACE", "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", "DIVIDE", "NUMPAD1",
                        "NUMPAD2", "NUMPAD3", "MULTIPLY", "NUMPAD4", "NUMPAD5", "NUMPAD6", "SUBTRACT",
                        "NUMPAD7", "NUMPAD8", "NUMPAD9", "ADD", "NUMPAD0", "DECIMAL", "SUBTRACT", "ENTER"
                   for (int i=0; i<20; i++)
                        buttons[buttonsWithKeyBindings[i]].getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyBindings[i]), "typed");
                        buttons[buttonsWithKeyBindings[i]].getActionMap().put("typed", buttonClicked);
         class buttonClickedAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JButton whichClicked = (JButton)e.getSource();
                   if (whichClicked.getText() == "ans")
                        try
                             doc.insertString(doc.getLength(), "ans", null);
                        catch(Exception ble) {}
                        expression.append("ans");
                        lastEntered = "operator";
                        lengthOfLast = 3;
                   else if (whichClicked.getText() == "rand")
                        long randomNumber = Math.round(Math.floor(Math.random() * 10));
                        try
                             doc.insertString(doc.getLength(), String.valueOf(randomNumber), null);
                        catch(Exception ble) {}
                        expression.append(randomNumber);
                        lastEntered = "number";
                        lengthOfLast = 1;
    // etc. etc. etc.
    Nick

  • An array of jButtons

    Hi!
    I have an array loaded with my jButtons (100 count).
    I programmatically call for this array to change the button's color ... this works well.
    button.setBackground(new Color(a,b,c));now ... what I want to do now , is when I mouse click on any of these buttons ... to have it report its jButton number as a new var.. (they range from 1 to 100)
    Can this be done?
    Thanks!

    Have you looked at my code above? It solves the problem for you.
    If you don't want to use a subclass then store the buttons in a List and use indexOf() to determine its index, calling getSource() on the event to determine the button which produced it. Or use a Map for the same effect - it means creating some Integer objects but the lookup is quicker.
    what I need to do is to make every jButton (100 of them)fire an event.
    They all fire events anyway when clicked. What you need to do is listen to them.
    then have one listener class
    Do you mean class or object? Yes, you could use a single listener object - eg with my example IndexedButton above, you could detect an event from any button, then getSource(), cast to an IndexedButton and the query the index field. However it's much, much neater to simply have your buttons call a method directly, passing their value as a parameter. It also allows for that method to be called programatically, which means your object will can be used even without a UI, or if you change the UI (eg you use a text field to input the number) then there's no change to the main object itself: the change is just in the UI class, as it should be.
    I can't even imagine doing all of this without a form builder.
    You break it down hierarchically into manageable chunks. If you've designed your code properly then this should happen anyway: it's very rare that a cohesive component should have a massively-populated - or rather, over-complex - UI.
    Sounds like you've just stuffed everything in one place and let it be managed by one object, which isn't a good way to go about it.

  • How can I generate an array of JButton in Eclipse 3.2 ?

    I know something like this shud work ::
    JButton[] barray = new JButton(5); // To create an array of 5 Buttons
    But the problem is that in the JButton class, there is no constructor that takes an integer argument.
    Any ideas ... ?
    Ajay Garg

    Please don't cross post - http://forum.java.sun.com/thread.jspa?threadID=5249328&tstart=0

Maybe you are looking for

  • DMS SEARCH THROUGH PORTAL

    Dear SAP Gurus,     I'm using SAP NW 2004s ,i have connected my portal with DMS and when i search documents from DMS through dms search iview it is giving wrong result,please help me in solving this issue. regards, sathya.

  • My mac mini unexpectedly died!

    Hello all, I bought a mac mini 10 days ago. It was all so nice when today I looked at the mac (I was abandoned it for about 10 minutes) and I found a strange screen, saying to restart the machine. Late I found this screen is an analog to the Windows

  • Audio (PPC) File Size

    Hello. We have been working with Adobe Presenter to create presentations/lectures which we ultimately upload to our University Adobe Connect server. We have been seeing some very annoying problems with the size of the audio (PPC) file. On one system,

  • Malware and/or Phishing Incident???

    In a moment of "not thinking clearly," yesterday on my iPad I was reading an email from "my bank" that indicated a possible fraudulent charge. I clicked on the embedded html link within the body of the email message and it launched Safari which then

  • Not getting last character

    I wrote a method that decrypts encoded text. I have used it before (in another class) so I know that it works. Perhaps I may have just copied it wrong...though I did a copy/paste...or maybe its my coding itself. Either wasy its driving my bonkers. He