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.

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

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

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

  • 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

  • Array of JButtons

    I have 10 JButtons in a JFrame and they shall open a new JFrame when you click on them (different Frames for different buttons).
    I guess that the easiest way is to put the buttons in an array. How can I do that?

    Oki.
    I thought that an array would be good. Easier to control the buttons then.
    After I clicked one of the buttons i get a new frame with new buttons and so forth and so on.
    If I don't have arrays I have to write almost the same thing for all the buttons...
    Do you have a better idea, I'm more than glad to hear!

  • 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

  • Changing A JButton's Icon In an Array of JButtons

    I am making a battleship game and I have an array of buttons set up on the playing board.
    When the user clicks a button, if it is a hit I would like the icon of the button to change.
    This is what I have so far...
    playerOcean = m1.getplayerOcean();
         compOcean = m1.getpcOcean();
              for (int x=0; x < 10; x++)
                   for (int y=0; y < 10; y++)
                        if (playerOcean[x][y] == 2)
                             playButtons [x] [y].setIcon(hit);
    Where hit = private Icon hit = new ImageIcon("boom.jpg");
    And playerOcean is the array in which the locations of the ships are stored, where 2 is a hit.

    Hi, mygrymm-
    There are lots of inefficient ways to do this having to do with traversing arrays, etc., but probably the best thing for you to do is to create a two dimensional associative array, or an Object of Objects, in JavaScript parlance.  That way, you can look up the X in the parent object and the Y in that object to see if it exists.  Here's a really brief sample that I haven't tested, but should get you going in the right direction.
    Let's say my boundary is 4, 5:
    var xArray = new Object();
    xArray["4"] = new Object();
    xArray["4"]["5"] = true;
    Then, when I test....
    var currX = somehow.get.the.object.x.value;
    var currY = somehow.get.the.object.y.value;
    if (xArray[currX.toString()][currY.toString()] == true) {
       console.log("boundary hit!");
    Hope that helps,
    -Elaine

  • How can I listen an array of JButtons?

    JButton button[] = new JButton[10];
    for(int i=0; i<10; i++){
    button= new JButton(""+i);

    krasun.net wrote:
    JButton button[] = new JButton[10];
    for(int i=0; i<10; i++){
    button= new JButton(""+i);
    for(int i=0; i<10; i++){
        button= new JButton(""+i);
    button[i].addMouseListener(myMouseListener); //don't add a new--they need the same instance.

  • Getting values from JLabel[] with JButton[] help!

    Hello everyone!
    My problem is:
    I have created JPanel, i have an array of JButtons and array of JLabels, they are all placed on JPanel depending from record count in *.mdb table - JLabels have its own value selected from Access table.mdb! I need- each time i press some button,say 3rd button i get value showing from 3rd JLabel in some elsewere created textfield, if i have some 60 records and 60 buttons and 60 labels its very annoying to add for each button actionlistener and for each button ask for example jButton[1].addActionListener() ...{ jLabel[1].getText()......} and so on!
    Any suggestion will be appreciated! Thank you!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final int ROWS = 10;
        JPanel[] rows = new JPanel[ROWS];
        final JLabel[] labels = new JLabel[ROWS];
        JButton[] buttons = new JButton[ROWS];
        JPanel p = new JPanel(new GridLayout(ROWS,1));
        final JTextField tf = new JTextField(10);
        ActionListener listener = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setText(labels[Integer.parseInt(((JButton)ae.getSource()).getName())].getText());
        for(int x = 0; x < ROWS; x++)
          labels[x] = new JLabel(""+(int)(Math.random()*10000));
          buttons[x] = new JButton("Button "+x);
          buttons[x].setName(""+x);
          buttons[x].addActionListener(listener);
          rows[x] = new JPanel(new GridLayout(1,2));
          rows[x].add(labels[x]);
          rows[x].add(buttons[x]);
          p.add(rows[x]);
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(tf,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Mouse over JButton

    I have an 10 x 10 array of JButtons in my project. I was just wondering how do i find out which button the mouse cursor is over at any given time?
    I was trying to get x y mouse coordinates but how do i know over which JButton I am?
    Thanks for any advice
    Regards

    Could anybody help me with answer: How could I execute below method:
    public void mouseMoved(MouseEvent e) {
              System.out.println("Mouse over Button");
         }without clicking on the button. I have MouseListener on each button. I can exetue this method only when i'm clicking on button. What's wrong with my code? I wanna execute this method when my mouse is over the button :-(. Could help me with my example?
    thanks in advance.
    regards.
    package gui;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.ArrayList;
    import java.util.EventObject;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.event.ChangeEvent;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    public class TreeSample {
         JTree tree = null;
         CheckBoxNodeRenderer renderer;
         public void showTree() {
              JFrame frame = new JFrame("Tree");
              ArrayList<Object> ipDevice = new ArrayList<Object>();
            ipDevice.add("IP Device");
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CheckBoxNode("IP Device", false));
            rootNode.add(node);
            tree = new JTree(rootNode);
            renderer = new CheckBoxNodeRenderer();
            tree.setCellRenderer(renderer);
            tree.setCellEditor(new CheckBoxNodeEditor(tree));
            tree.setEditable(true);
            frame.setSize(400,400);
            frame.add(tree);
            frame.setVisible(true);
         public static void main(String args[]) {
              System.out.println("Test");
              TreeSample ts = new TreeSample();
              ts.showTree();
    class CheckBoxNodeRenderer implements TreeCellRenderer {
        private JButton leafRenderer = new ButtonCreator("TEST");
        protected JButton getLeafRenderer(){
            return leafRenderer;
        public CheckBoxNodeRenderer() {
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean selected, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {
            Component returnValue;
            returnValue = leafRenderer;
            return returnValue;
    class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor, MouseMotionListener {
        CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
        ChangeEvent changeEvent = null;
        JTree tree1;
        DefaultMutableTreeNode editedNode;
        public CheckBoxNodeEditor(JTree tree) {
            this.tree1 = tree;
        public Object getCellEditorValue() {
            JButton checkbox = renderer.getLeafRenderer();
            return checkbox;
        public boolean isCellEditable(EventObject event) {
            return true;
        public boolean shouldSelectCell(EventObject ev) {
             return true;
        public Component getTreeCellEditorComponent(final JTree tree, Object value,
                boolean selected, boolean expanded, boolean leaf, int row) {
            System.out.println("GetTree");
            Component editor = renderer.getTreeCellRendererComponent(tree, value,
                    true, expanded, true, row, true);
            return editor;
         public void mouseDragged(MouseEvent e) {
         public void mouseMoved(MouseEvent arg0) {
    class CheckBoxNode {
        String text;
        boolean selected;
        public CheckBoxNode(String text, boolean selected) {
            this.text = text;
            this.selected = selected;
        public boolean isSelected() {
            return selected;
        public void setSelected(boolean newValue) {
            selected = newValue;
        public String getText() {
            return text;
        public void setText(String newValue) {
            text = newValue;
    class ButtonCreator extends JButton implements MouseMotionListener {
         public ButtonCreator() {
              this.addMouseMotionListener(this);
         public ButtonCreator(String p_name) {
              this.setText(p_name);
              this.addMouseMotionListener(this);
         public void mouseDragged(MouseEvent e) {
         public void mouseMoved(MouseEvent e) {
              System.out.println("Mouse over Button");
    }

  • Help with JButtons please

    Hi, I have a 2D array of JButton's in a gridLayout. This stores the buttons row/col and if it has an image:
    for(int i = 0; i < 7; i++) {
    for(int j = 0; j < 7; j++) {
    button[i][j] = new JButton(peg); //Populates grid with ImageIcons
    button[i][j].putClientProperty("column", i); //Stores all column properties
    button[i][j].putClientProperty("row", j); //Stores all row properties
    button[i][j].putClientProperty("ImageIcon" yes); //Sets each JButton to have an image
    button[i][j].addActionListener(new MyActionListener()); //Add actionListener
    add(button[i][j]); //Adds all buttons into gridLayout
    When I click one of my buttons the action listener is implemented and I can get all of the information about this button using the e.getSource() method:
    public class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    if(isFirstClick){
    JButton btn = (JButton) e.getSource(); //Get information on each button
    My question is, when I click on one button, how can I get the information from the button directly to its left without clicking on that button?
    I can get the button to the lefts row/col, but not the actually JButton's information like e.getSource()
    Thanks very much, I hope this makes sense

    Store these buttons in an 2D array and use the clientProperty to fetch any other button relative from this button's position.

  • Find index in an array of components

    I have an array of JButtons. Each JButton has an associated ActionListener. My problem is that when one of the buttons are clicked I need the index of the JButton that is clicked to do work inside the Actionlistener.
    How do I get the index of the JButton being pressed?
    JButton[ ] button = new JButton[300];
    for(int i = 0 ; i < 300 ; i++)
    button[i] = new JButton(("Test " + i));
    button.addActionListener(new ActionListener()
    public actionPerformed(ActionEvent evt)
    /** I need to know what the value of i is when this button is pressed **/

    I would think that you could just use the variable i from the loop, like this:
    JButton buttonArray = new JButton[300];
    JButton button;
    for(int i = 0; i < 300; i++)
      button = new JButton("Test"+i);
      button.addActionListener(new ActionListener() {
        public actionPerformed(ActionEvent e)
          int index = i; // here index is the index of the JButton chosen
    hope this helps!
      buttonArray[i] = button;

Maybe you are looking for

  • How do I find out what HD upgrade options are compatible with my MBP?

    I'd like to upgrade the 250GB hard drive in my Macbook Pro to a 500GB or larger size. A copy of the Hardware Overview is pasted below to illustrate the specifications of what I have right now. How do I find out what drives are compatible with my mach

  • [JS][CS3] Getting Page Number

    Hi. I need to find the page number of the page containing a frame. Normally I would use "myFrame.parent.name" to find the page number. However, I cannot use this method on an inline graphic.  What I get returned is the story, which has no page number

  • Problem using icommand in UNIX

    Hi, I'm trying to use icommand in UNIX. I navigate to the middleware home on the server and in the .../BAM/Bin directory I can see an icommand.bat file and the standard icommand file. However, I can't see an icommand.sh file. I've tried some commands

  • Problem related with User Defined search

    Hi all, In service type marketing doc.i added three UDF at row level. 1)Item code 2)Item Desc. 3)Quantity i need to design a formatted search which will multiply Quantity with unit price and will update result in Total field in row level. please sugg

  • Spool Script for XML file

    Question : I do not want <ROW num="1"> in xml file I need just <row> </row>. Because I want to change it to <TRANSACTIONS> <TRANSACTION> using Replace. Please can any one help me to remove num = "1" and num ="2" from xml file ? --MY SPOOL SCRIPT STAR