JButton: Using Strings and Icons

I am trying to make a JButton so that when it is ...
1. enabled, an Icon appears without any text
2. selected, a String appears without any Icon
3. disabled, a Icon appears without any text
My Code is as follows...
equation[i] = new JButton(mathSigns);
equation.setDisabledIcon(winImage);
equation[i].setDisabledSelectedIcon(winImage);
equation[5].setSelected(true);
     if(equation[5].isSelected() == true)
                    equation[5].setText("TEXT");
Everything works except that When the button is selected, the Icon and the Text shows up instead of just the text showing up. I want the Icon to dissappear and only the text to show up. How can i do this? Thanks!

Here is a piece of code that might help. I had to use JToogleButtons because I don't really know what a selected regular JButton is.import javax.swing.*;
import java.io.IOException;
import java.net.URL;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
* User: weebib
* Date: 12 janv. 2005
* Time: 03:06:30
public class MultiStateButton extends JToggleButton {
     private static ImageIcon ICON_ENABLED = null;
     private static ImageIcon ICON_DISABLED = null;
     static {
          try {
               ICON_ENABLED = new ImageIcon(new URL("http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/tumble/T1.gif"));
               ICON_DISABLED = new ImageIcon(new URL("http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/tumble/T2.gif"));
          } catch (IOException e) {
               e.printStackTrace();
     public MultiStateButton() {
          super(ICON_ENABLED);
          setModel(new ToggleButtonModel() {
               public void setSelected(boolean b) {
                    super.setSelected(b);
                    if (b) {
                         setText("tutu");
                         setIcon(null);
                    } else {
                         setIcon(ICON_ENABLED);
                         setText(null);
          setDisabledIcon(ICON_DISABLED);
     public static void main(String[] args) {
          final JFrame frame = new JFrame(MultiStateButton.class.getName());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JPanel panel = new JPanel(new GridLayout(1, 2));
          final JToggleButton firstButton = new MultiStateButton();
          final JToggleButton secondButton = new MultiStateButton();
          firstButton.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    secondButton.setEnabled(!secondButton.isEnabled());
          secondButton.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    firstButton.setEnabled(!firstButton.isEnabled());
          panel.add(firstButton);
          panel.add(secondButton);
          frame.setContentPane(panel);
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    frame.pack();
                    frame.show();
}

Similar Messages

  • Using Strings and tokens . . .

    Hello,
    I was wondering if anyone could help me out with this problem(s). I'm designing a java program that (when a statement is typed in by a user) (1) tells you if it's a sentence, question, or exclamation, (2) it gives you the total amount of words in the statement, (3) tells you the longest word in the statement, (4)and also outputs the number of words that contain 1-3 characters. So far, i've been able to figure out how to do (1) and (2), but I'm really stuck on (3) and (4). Could someone please take a look at my program and tell me what I'm doing wrong. Thanks, Ana : )
    // ProgramTwo.java Author: Ana
    // Program Two. Demonstrates the use of strings and tokens.
    import java.util.Scanner;
    import java.io.*;
    import java.util.StringTokenizer;
    public class ProgramTwo
    // Prints a string and various mutations of it.
    public static void main (String[] args)
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter a statement >");
    String myString = scan.nextLine();
    String oneWord;
    if (myString.endsWith("!"))
    System.out.println("Your statement ends with an exclamation.");
    else
    if (myString.endsWith("."))
    System.out.println("Your statement is a sentence.");
    else
    System.out.println("Your statement is a question.");
    StringTokenizer st = new StringTokenizer(myString);
    System.out.println("There are " + st.countTokens() +
                   " word(s) in your statement.");
    st = new StringTokenizer(myString);
    while (st.hasMoreTokens())
    oneWord = st.nextToken();
    if (oneWord.length() <= 3)
    System.out.println(oneWord); //supposed to determine the number of words that contain up to three
    //characters
    String longestWord = "";
    while (st.hasMoreTokens())
    String w = st.nextToken();
    if (w.length() > longestWord.length())
    longestWord = w;
    System.out.print(longestWord); // It's supposed to determine the longest word in the statement
    }

    Hey Guys,
    I just wanted to thank all of you who responded to my message. With your help, I was able to figure out a bunch of other stuff. ChuckBing, I replaced some parts like you said and it worked like a charm! KPSeal, you brought up a good point, I doubled checked with my instructor and he said it was Ok for me to leave that part as is. Lutha, thanks for your input. I was just wondering, is Python similar to Java? I've never heard of it before, then again I've never heard of Java until a couple of months ago : ) Anyways, thanks again!! Ana : )
    By the way, here's how my program came out.
    // ProgramTwo.java Author: Ana
    // Program Two. Demonstrates the use of strings and tokens.
    import java.util.Scanner;
    import java.io.*;
    import java.util.StringTokenizer;
    public class ProgramTwo
    // Prints and groups various word types and amounts.
    public static void main (String[] args)
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter a statement >");
    String myString = scan.nextLine();
    String oneWord;
    if (myString.endsWith("!"))
    System.out.println("Your statement ends with an exclamation.");
    else
    if (myString.endsWith("."))
    System.out.println("Your statement is a sentence.");
    else
    System.out.println("Your statement is a question.");
    StringTokenizer st = new StringTokenizer(myString);
    System.out.println("There are " + st.countTokens() +
                   " word(s) in your statement.");
    int shortWordCount = 0;
    int medWordCount = 0;
    int longWordCount = 0;
    String longestWord = "";
    String shortestWord = "";
    while (st.hasMoreTokens())
    oneWord = st.nextToken();
    if (oneWord.length() <= 3)
    shortWordCount++;
    if (oneWord.length() >= 4 && (oneWord.length() <= 6))
    medWordCount++;
    if (oneWord.length() >= 7)
    longWordCount++;
    if (oneWord.length() > longestWord.length())
    longestWord = oneWord;
    if (oneWord.length() < shortestWord.length())
    shortestWord = oneWord;
    System.out.println("The shortest word is " + shortestWord + ".");
    System.out.println("The longest word is " + longestWord + ".");
    System.out.println("There are " + shortWordCount + " short words.");
    System.out.println("There are " + medWordCount + " medium words.");
    System.out.println("There are " + longWordCount + " long words.");

  • ALV using chekbox and icon

    1)  Needs to create two icons for a row in ALV.
    With One Icon, she should be able to Edit a ROW. Other icon should support save option and should save the changes in the database table.
      How can we do this????
    2)  Needs to create a checkbox by creating a Field in the database table.
    Each row in the table will have a checkbox in ALV.
    If a checkbox is selected , that particular row should be selected in the ALV
    Regards,
    Rajkumar

    Rajkumar,
    Check the following code
    Types: begin of lt_io.
    include structure mara. " Your Structure
    Types: style_table type lvc_t_style.
    Types: end of lt_io.
    data: lt_io type table of lt_io,
    ls_layout type lvc_s_layo,
    lt_fcat type lvc_t_fcat,
    lo_grid type ref to cl_gui_alv_grid.
    field-symbols: <io> type lt_io,
    <fcat> type lvc_s_fcat.
    ... fill your output table ....
    ls_layout-stylefname = 'STYLE_TABLE'.
    loop at lt_io assigning <io>.
    PERFORM set_style USING 'CHECKBOX' "Your Filename
    CHANGING <io>.
    endloop.
    ... Fill Your Field Catalog lt_fcat
    read table lt_fcat assigning <fcat>
    where fieldname = 'CHECKBOX'.
    <fcat>-checkbox = 'X'.
    create grid control lo_grid.
    CALL METHOD lo_grid->set_table_for_first_display
    EXPORTING
    is_layout = ls_layout
    CHANGING
    it_fieldcatalog = lt_fcat
    it_outtab = lt_io[].
    FORM set_button_to_line
    USING iv_fieldname TYPE lvc_fname
    CHANGING cs_io TYPE io.
    DATA: ls_style TYPE lvc_s_styl,
    lt_style TYPE lvc_t_styl.
    ls_style-fieldname = iv_fieldname.
    if cs_io-checkbox = ' '.
    ls_style-style = cl_gui_alv_grid=>mc_style_enabled.
    else.
    ls_style-style = cl_gui_alv_grid=>mc_style_disabled.
    endif.
    ls_style-maxlen = 2.
    INSERT ls_style INTO TABLE io-style_table.
    ENDFORM. "set_icon_to_status_line
    [/code].
    Vinodh

  • Reverse Strings using rercursion and iteration

    Hi,
    I really need some help, am quite new to java and am struggling.
    I want to design 2 methods, both 2 reverse strings.
    1) uses StringBuffer and iteration
    2) uses Strings and recursion
    I would be greatful for any advice or help.
    Thanx xxxxx Nats xxxxxx

    Oh, you need to do it using both methods.... Sorry, didn't realise it was coursework :)
    Using StringBuffer and iteration
    public StringBuffer reverse(StringBuffer buff) {
        int halfLen = buff.length();
        int len = buff.length();
        for(int i=0; i < halfLen; i++) {
             char c1 = buff.getCharAt(i);
             char c2 = buff.getCharAt((len - i) - 1);
             buff = buff.setCharAt(i, c2);
             buff = buff.setCharAt((len - i) - 1, c1);
        return buff;
    }And for String using recursion
    public String reverse(String str) {
        char[] chars = new char[str.length];
        str.getChars(0, chars, 0, str.length());
        reverseChars(chars, 0, str.length() / 2);
        return new String(chars);  
    private reverseChars(char[] chars, int index, int halfLen) {
        //* end condition
        if(index >= halfLen) return;
        topIndex = (chars.length - 1) - index;
        char tmp = chars[index];
        chars[index] = chars[topIndex];
        chars[topIndex] = tmp;
        reverseChars(chars, ++index, halfLen);
    }I only wrote this code on the fly so things may break but it is a start.

  • Since i have updated my iphone everytime i open an app it comes up with a message 'connect to itunes to use push notifications, may include alerts, sounds and icon badges, i have backed up my phone on itunes and restored phone but its still doing it, :(

    since i have updated my iphone everytime i open an app it comes up with a message 'connect to itunes to use push notifications, may include alerts, sounds and icon badges, i have backed up my phone on itunes and restored phone but its still doing it  can anyone help?
    Em

    Return the iPhone and get your money back. It has been
    hacked/modified/jailbroken and likely cannot be made
    operative.

  • Push Notifications. The Message "Connect to iTunes to Use Push Notifications "BBC History Magazine" notifications may include alerts, sounds and icon badges" keeps coming up in Newstand, also happens with National Geographic Magazine. HELP!

    The Message "Connect to iTunes to Use Push Notifications "BBC History Magazine" notifications may include alerts, sounds and icon badges" keeps coming up in Newstand, also happens with National Geographic Magazine. HELP!
    I have now followed multiple instructions from this and other forums. have turned push notifications off. Turned them on. Have updated to IOS 6. Have signed out and signed back in, have uninstalled all magazines and reinstalled. Have synced, and updated everything in iTunes.
    Nothing works,. Also cannot use youtube.

    Basic troubleshooting from the User's Guide is reset, restart, restore (first from backup then as new).  Try each of these in order until the issue is resolved.
    It might also be a good idea to contact Square for assistance.

  • I cannot shut dow my MacBook Pro using the apple icon (as it was suppose to be), actually I have to press and hold the on/off buttom. I have taken twice for Mac dealer and they did not solve the problem. What must I do?

    I cannot shut dow my MacBook Pro using the apple icon (as it was suppose to be), actually I have to press and hold the on/off buttom. I have taken twice for Mac dealer and they did not solve the problem. What must I do? I would to remark that I have installed 2 antivirus and uninstalled one of them. Since then I have facing this troublesome issue. Thanks

    Uninstall the other AV software. They are not needed. All they do is cause trouble like you are having now.
    If you have been forcing the Mac to shut down with the power switch you may nave corrupted your disk. You should repair it with disk Utilty to remove any corruption the shutdwons may have cased.
    Allan

  • After years of owning all things Mac, I am finally trying to use iChat, and can't get it to work. I see my buddy, but all I can do is send a message--the video and audio chat icons are gray, as is inviting to a video chat under Buddies.

    After years of owning all things Mac, I am finally trying to use iChat, and can't get it to work. I am using gmail, and I see my buddy (no camera icon next to her name), but all I can do is send a message--the video and audio chat icons are gray, as is inviting to a video chat under Buddies. My buddy has the same problem as I.  We are able to do video chat through gmail, but I had hoped to use iChat.  I am using OS 10.6.8, iChat v. 5.0.3.  What am I missing?

    HI,
    iChat will Video chat to another iChat in a Jabber Buddy List (Google run a Jabber server for GoogleTalk)
    However it will not Video to the Web Page login to iGoogle or the Web Mail Page login.  (where people can Google Chat as it were in a  Web Browser).
    Nor does it video to the Google Talk Stand alone app for PCs or any other Jabber apps on any platform.
    iChat uses a connection Process called SIP (Session Initiation Protocol) which is also used by other VoIP devices.
    Jabber/XMPP invited the Jingle Protocol for Jabber Applications.
    Google have included this in their Standalone app and the Plug-in for Web Browsers on both PCs and Mac (you can get this as a Standalone Plug-in or as part of Chrome)
    More on this here  This article has been changed several time in the recent months.  It now claims a greater involvement by Google in writing the Jingle Library (Although now Google's version does not work with the others)
    This tends to mean that using the web Login to Google to Chat also cannot video chat to other Jabber apps that are using Jingle.
    If your Buddy is using iChat then check the Video Menu has two items to Enable Camera/Video chat and Microphone/Audio chats are ticked.
    In the View Menu the Show Status Items should be ticked (Selecting them toggles the tick and the function On or Off)
    It could be Internet speed but at this stage I would doubt this at this stage.
    10:27 PM      Saturday; January 21, 2012
    Please, if posting Logs, do not post any Log info after the line "Binary Images for iChat"
      iMac 2.5Ghz 5i 2011 (Lion 10.7.2)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
    "Limit the Logs to the Bits above Binary Images."  No, Seriously

  • How to read a C structure with string and int with a java server using sock

    I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
    I want to know how can I read strings and int with the same stream because they are sent at the same time:
    C pgm sent structure :
    char* chaine1;
    char* chaine2;
    int nb1;
    int nb2;
    I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
    Any idea would be a good help...
    thanks.
    Nicolas (France)

    Does the server sent the ints in little endian or big endian format?
    The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it.

  • How to Split the string using Substr and instr using loop condition

    Hi every body,
    I have below requirement.
    I need to split the string and append with single quotes('') followed by , (comma) and reassign entire values into another variable. so that i can use it where clause of update statement
    for example I am reciveing value as follows
    ALN varchar2(2000):=(12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434);
    Note: In the above variable i see 8 transactions, where as in real scenario i donot how many transaction i may recive.
    after modification i need above transactions should in below format
    ALTR Varchar2(2000):=('12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434');
    kindly help how to use substr and instr in normal loop or for loop or while loop while modifying the above transactions.
    Please help me to sort out this issue.
    Many Thanks.
    Edited by: user627525 on Dec 15, 2011 11:49 AM

    Try this - may not be the best way but...:
    create or replace type myTableType as table of varchar2(255)
    declare
    v_array mytabletype;
    v_new_str varchar2(4000);
    function str2tbl
             (p_str   in varchar2,
              p_delim in varchar2 default '.')
             return      myTableType
        as
            l_str        long default p_str || p_delim;
             l_n        number;
             l_data     myTableType := myTabletype();
        begin
            loop
                l_n := instr( l_str, p_delim );
                exit when (nvl(l_n,0) = 0);
                l_data.extend;
                l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
                l_str := substr( l_str, l_n+length(p_delim) );
            end loop;
            return l_data;
       end;
    begin
      v_array := str2tbl ('12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434', ',');
          FOR i IN 1 .. v_array.COUNT LOOP
             v_new_str := v_new_str || ''''||v_array(i)||'''' || ',';
          END LOOP;
       dbms_output.put_line(RTRIM(v_new_str, ','));
    end;  
    OUTPUT:
    =======
    '12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434'HTH
    Edited by: user130038 on Dec 15, 2011 12:11 PM

  • Dragging Icons stops working after organizing using drag and drop. Why?

    On the newest MBA (2013)
    While organizing my music I was creating new folders within the artists' folder in order to seperate things into albums. sometimes when im dragging the songs into this newly created folder ( I drag them in  like groups of 10 , really depends on the length of the album) the ability to drag any icon is completely gone. I can still highlight folders and icons but I can no longer move them at all ( using the three finger move on the mouse pad or by holding the click and dragging  )
    It only happens when I select and drag a few songs over to the folder and drop them in without waiting for that folder to open up.
    This forces me to restart in order to be able to use OSX normally again.
    Does anyone have any insight? Do I need to just wait for a new update ?

    I found this by EvB on https://discussions.apple.com/thread/4830916
    "Try this.
    Open a Terminal and type the following commands:
    cd /
    sudo rmdir tmp
    sudo ln -s tmp /private/tmp
    If your tmp directory is not already there then the second command will give an error - just proceed to the third command in this case.
    Once you have done this sequence, reboot the machine and see if your drag and drop is restored."
    Not sure if this fixed the problem or if rebooting temerally fixed it again.
         Nope did not fix it

  • All the script and icons on my iPhone4 have suddenly become enlarged and it´s almost impossible to use them

    After making a call on my iPhone4 all the script and icons suddenly became enlarged and it´s now almost impossible to use the phone.  Everything is slowed up and only partial amounts of the screen can be seen.  Any idea´s on how to restore to normal?

    Thank you. All in order now!

  • Can anyone please help? Every time I start up my imac OSX 10.6 desktop my Aperture 3 programme opens up without being requested. Is it possible to stop this from happening and only open by using the desktop icon? Thank you for any assistance.

    Can anyone please help? Every time I start up my imac OSX 10.6 desktop my Aperture 3 programme opens up without being requested. Is it possible to stop this happening and only allow Aperture to open by using the desktop icon? Thank you for any assistance anyone may be able to give.
    Best regards, John.

    because there is absolutely no mention in my System Preferences of either Users & Groups nor Start Up Items.
    John,
    William's solution was much easier - just for completeness sake: The preferences panes to edit your startup items moved between the Mac OS X updates: I forgot that the "Users&Groups" preference pane used to be called "Users" in Mac OS X 10.6; it is the panel that you use to create new User accounts; and earlier systems had a separate preferences panel "Login" to enable and to disable the applications that are launched at login. Both are now combined in "Users&Groups". Sorry for sending you on a wild goose chase with the wrong Preferences panel.
    Regards
    Léonie

  • HT5137 i tried using the setting icon to reset the prints and icon to a bigger size, thereafter the setting icon lost colore to gray and stopped responding

    i tried using the setting icon to reset the prints and icon to a bigger size, thereafter the setting icon lost color to gray and stopped responding.? most of the pop up boxes will also not respond why?

    Thanks Winston, restarting my router worked for me too. Seems that somehow the DCHP (maybe due to the Mountain Lion upgrade?) had assigned the same IP address to both the AppleTV and my iMac. The AppleTV stopped appearing as an AirPlay device for my iPhone and Mac, but still the AppleTV had Internet access.
    Restarting the router reassigned IPs and without fanfare, the AppleTV is now available to AirPlay.

  • Sort Icon/option in ALV tree repot using classes and methods

    Hi all,
    I have done an alv tree report using the class cl_gui_alv_tree
    and i need to let users re-sort the report by using a sort icon(as visible in a normal alv report).Is there any possibility to create an icon and set the functionality such that the entire tree structure gets resorted depending upon the sort criteria?Please give me an example of doing so if there is an option.

    if u want without classes then i can  give an example of Sort Icon/option.
    example:-
    DATA:   wa_sortinfo TYPE slis_sortinfo_alv.
           i_sortcat TYPE slis_t_sortinfo_alv.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
           EXPORTING
                i_callback_program     = report_id
                i_grid_title           = ws_title
               i_callback_top_of_page = 'TOP-OF-PAGE'
                is_layout              = wa_layout
                it_fieldcat            = i_fieldcat[]
                it_sort                = i_sortcat
                i_save                 = 'A'
                it_events              = i_events
           TABLES
                t_outtab               = i_reportdata1
           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.
      PERFORM sortcat_init CHANGING i_sortcat.
    FORM sortcat_init CHANGING i_sortcat TYPE slis_t_sortinfo_alv.
      CLEAR wa_sortinfo.
      wa_sortinfo-fieldname = 'EBELN'. (sales order)
      wa_sortinfo-tabname = 'I_REPORTDATA1'.
      wa_sortinfo-spos = 1.            " First sort by this field.
      wa_sortinfo-up = 'X'.            "   Ascending
      wa_sortinfo-subtot = 'X'.        " Subtotal at Name1
      APPEND wa_sortinfo TO i_sortcat.
      CLEAR wa_sortinfo.
      wa_sortinfo-fieldname = 'EBELP'.
      wa_sortinfo-tabname = 'I_REPORTDATA1'.
      wa_sortinfo-spos = 2.            " Sec sort by this field.
      wa_sortinfo-up = 'X'.            "   Ascending
      wa_sortinfo-subtot = 'X'.        " Subtotal at Name1
      APPEND wa_sortinfo TO i_sortcat.
    ENDFORM.                    " sortcat_init

Maybe you are looking for

  • "are you sure?" message scares me but think I need automatic update.

    Hello forum Im new here and about 10 of my questions have been answered by searching. However I have not found an answer to this one: I paid for a music video from itunes, but I cant click and drag to my ipod. I saw another question like this and som

  • Billing document form for printout

    Hi, How do I change the smart form attached to the billing document? I have a new template that I want to use. Thanks!

  • How to Disable Nokia Suite v. 3.4.49 from Lurking ...

    Dear all, I have, just an hour back, installed Nokia Suite 3.4.49. which installed fortunately successfully. And i have connected my phone (NOKIA E90) and it got connected successfully and synced all data. The PROBLEM now is the Nokia Suite's Gallery

  • Does Microsoft Wireless Entertainment Desktop work with built-in BT?

    Hi guys, I was wondering if the Microsoft Wireless Entertainment Desktop 7000 (keyboard and mouse bluetooth combo) is working with the built-in bluetooth module (Satellite A300-1QM). Any experience anyone? I'd like to know if I have to use the blueto

  • Fresh Install Help

    I wanted to know if someone could help with step by step instructions on hhow to do a fresh install of 10.6. I know I probably have to boot of the CD but after that I am a little lost. Thank you