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

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.

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

  • Java Mapping with an xml array as input

    Hi Gurus,
    I have to perform a java mapping to map some input xml contained in an array with a target message type. I have found a good java mapping example here:
    Re: Please provide Java Mapping example
    but my mapping input is not a single XML, but an XML array, thus I have a doubt...
    How can I map multiple XML contained in an array with a target XML? I have to solve this problem into a Java mapping prospective.
    Thanks to all!
    Message was edited by:
            Gabriele Morgante

    Hey Stefan, I think he is refering to a n:1 multimapping.
    If that is indeed the case, Gabriele, you will have to consider the initial tags inserted by mapping runtime to treat multimappings.
    Suppose your XML message is like
    <myMT xmlns="urn:mynamespace">
      <value>xpto</value>
    </myMT>
    Then, if your source message interface occurrence is defined as unbounded in your interface mapping, your mapping program (message mapping, xslt, java mapping, whatever) will receive, from mapping runtime, a message like this:
    <Messages xmlns="http://sap.com/xi/XI/SplitAndMerge">
      <Message1>
        <myMT xmlns="urn:mynamespace">
          <value>xpto1</value>
        </myMT>
        <myMT xmlns="urn:mynamespace">
          <value>xpto2</value>
        </myMT>
        <myMT xmlns="urn:mynamespace">
          <value>xpto3</value>
        </myMT>
      </Message1>
    </Messages>
    Also, if you have more than 1 message type as source of your interface mapping, your mapping program will receive the other message types in <Message2>, <Message3>... tags.
    The <Messages> and <MessageX> tags will always be automatically generated by mapping runtime when dealing with multimappings, which are mappings from m XML messages to n XML messages, with either m, n or both different of 1 (note that this definition includes mappings from 1 type to 1 type, when either source, target or both message types have max occurrence = ubounded).
    Finally, remember that the output that your mapping program generates will also have to include these <Messages> and <MessageX> tags (with proper namespace), since mapping runtime will be expecting them. Message mappings treat those by default, but your xslt and java multimappings will have to explicitely include these tags in the output.
    Regards,
    Henrique.

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

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

  • Mapping array of URIs

    HI,
    I need to map an object containing array of java.net.URI objects. Mapping must fulfill following requirements:
    - values need to be visible in database (not serialized)
    - ordering of elements is important
    I have little control over mapped object (it's part of the interface), but I can freely manipulate database design. What would be the best way to handle this mapping?
    I'm using Toplink 9.0.4.5
    Regards,
    Pawe&#322;

    Hi,
    The class is a relatively simple simple DTO, containing mostly primitive type fields (Strings, int),
    public class DTO {
    private String f1;
    private String f2;
    private java.net.URI[] addresses;
    /* getters, setters, constructor &etc. */
    Instances of the class are received from system's clients.There is no logical ordering rule for the elements of addresses array, but the initial ordering is significant for processing and needs to be preserved.
    Regards,
    Pawe&#322;

  • Soap encoded array of complex type, impossible to map?

    Hello,
    can anyone please tell me if the XI has problems (or is unable) to read from soap-encoded arrays of a complex type.
    As far as I know this is conform to SOAP 1.1
    We developed this webservice for a client, who says, he cannot map this kind of array in his XI.
    Would it be better to do it this way ?
    <complexType name="ActivityList">
      <sequence>
        <element name="ActivityEl" maxOccurs="unbounded" type="Activity"/>
      </sequence>
    </complexType>
    Excerpt of the WSDL:
        <wsdl:message name="getDataForPbnrResponse">
            <wsdl:part name="getDataForPbnrReturn" type="impl:ArrayOf_tns1_Activity"/>
        </wsdl:message>
            <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://ipslsv01vm02:9080/axis/services/QEC-Service">
                <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
                <complexType name="ArrayOf_tns1_Activity">
                    <complexContent>
                        <restriction base="soapenc:Array">
                            <attribute ref="soapenc:arrayType" wsdl:arrayType="tns1:Activity[]"/>
                        </restriction>
                    </complexContent>
                </complexType>
                <complexType name="ArrayOf_tns1_ActivityFeedback">
                    <complexContent>
                        <restriction base="soapenc:Array">
                            <attribute ref="soapenc:arrayType" wsdl:arrayType="tns1:ActivityFeedback[]"/>
                        </restriction>
                    </complexContent>
                </complexType>
            </schema>
    Part ot the response:
    <?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
      <ns1:getDataForPbnrResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://ipslsv01vm02:9080/axis/services/QEC-Service">
       <getDataForPbnrReturn xsi:type="soapenc:Array" soapenc:arrayType="ns3:Activity[7]" xmlns:ns2="http://www.w3.org/2002/12/soap-encoding" xmlns:ns3="urn:BeanService" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
        <item href="#id0"/>
        <item href="#id1"/>
        <item href="#id2"/>
        <item href="#id3"/>
        <item href="#id4"/>
        <item href="#id5"/>
        <item href="#id6"/>
       </getDataForPbnrReturn>
      </ns1:getDataForPbnrResponse>
      <multiRef id="id5" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns4:Activity" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns4="urn:BeanService">
       <FIN xsi:type="xsd:string">---</FIN>
       <VIN xsi:type="xsd:string"></VIN>
    cut -
       <ursache xsi:type="xsd:string"></ursache>
      </multiRef>
    </soapenv:Body>
    </soapenv:Envelope>
    Thanks in advance!

    I am having this issue as well.
    From:
    http://help.sap.com/saphelp_nw04/helpdata/en/43/ce993b45cb0a85e10000000a1553f6/frameset.htm
    I see that:
    The WSDL document in rpc-style format must also not use any soapenc:Array types; these are often used in SOAP code in documents with this format. soapenc:Array uses the tag <xsd:any>, which the Integration Builder editors or proxy generation either ignore or do not support.
    You can replace soapenc:Array types with an equivalent <sequence>; see the WS-I  example under http://www.ws-i.org/Profiles/BasicProfile-1.0-2004-04-16.html#refinement16556272.
    They give an example of what to use instead.
    Of course I have been given a WSDL that has a message I need to map to that uses the enc:Array.
    Has anyone else had this issue?  I need to map to a SOAP message to send to an external party.  I don't know what they are willing to change to support what I can do.  I changed the WSDL to use a sequence as below just to pull it in for now.
    Thanks,
    Eric

  • Map (Hashmap) to Array

    Hello Java Friends,
    Please, I have a map (Mappings = new HashMap<String, Integer>) which contains both String and Integer elements. I wanted to store the string elements of the Map in a String Array and Integer elements in Integer Array but end up with error messages. How can I implement it?
    See part of my code below:
    public class Tryit{
    private  Map<String, Integer> Mappings;
    String[]StringElem;
    int [] IntegerElem;
    public Tryit(){
    Mappings  = new HashMap<String, Integer>()
    StringElem = new String [100];
    IntegerElem = new int [100];
    for (String index : Mappings.KeySet()){
    StringElem = index;
    for (int i : Mappings.values(){
    IntegerElem = i;
    }

    Hello friends,
    The idea you gave me worked but still I am having a small problem: I have two classes, class A and B. In Class A, I implemented a set and get method which I will use in Class B to retrieve the keys and Values. But when I call the get method in Class B, I always get null. The arrays in both classes are all declared globally.
    Get and Set Method in Class A :
    public void setKeyValues() {
              int i = 0;
              for(Map.Entry<String, Integer> e: map.entrySet()) {
                   ElementName= e.getKey();
              i++;
    public String []getKeyValues(){
         return ElementName;
    Call the Get Method in Class B
    import package X.A
    public class B{
    private String [] names;
    public B(){
    A bix = new A();
    int length = bix.getKeyValues().length;
    names = new String[length];
    System.out.printf ("%d", gettingKeys(bix.getKeyValues());
    public String[] gettingKeys(String []naming) {
              names = new int[bix.getKeyValues().length];
              int size = naming.length;
              for (int p = 0; p < size; p++) {
                   names[p]=naming[p];
                   p++;
              return names;
         }Please where is the problem ?? I am unable to read and print the map values and keys from another friend class.
    Jona_T

Maybe you are looking for

  • X120e does not sleep when lid closed

    I found another similar post, however it was resolved by the individual reinstalling the operating system. My issue is more complicated. I have made sure everything is up to date, all the settings that tell the system to sleep when the lid is closed

  • QT Player on Vista gives error # -2048

    Hi everyone, I keep getting the above error while opening some of the QT movies I have on my PC. Sometimes Windows even crashes. The only thing I can read from that is a hexadecimal code 0x00000602. Does the error number or the hex number mean anythi

  • Is 5508 controller version 7.1.91.0 compatible with wcs 7.0.220/230?

    just need a straight answer, best if someone has had a similar configuration working, sorry pals I really need to be shure

  • Mass transport of Model Orders

    Hi, I have a question. I need to transport multiple objects via one transport u2013 Model Orders. The standard transaction allows me only include Model Orders one by one;( This is how it looks like in a transport when you transport it standard way: C

  • DDL Related Changes

    We have an application published. We had to increase the size of a varchar field in one of the tables, so we also changed the "create table" statement for the snapshot. We forced full resyncs for all of our users. (Note: this is a win32 offline app t