How can I change a JTextField into a JComboBox

I have a desktop GUI application that has a field on a panel, which is usually a JTextField. However, under certain circumstances, this field needs to be restricted to certain known values - and a ComboBox would be great.
Under these circumstances, I would like the Textfield to disapear and the combobox to appear in exactly the same place, but I cannot figure out how to achieve this effect within the GUI.
I am hand crafting this GUI using GroupLayout Layout manager
I am also using Netbeans, so I thought I would try and achieve this effect using its GUI designer, but that wouldn't let me place one field on top of another.
Could anyone help me?
Much thanks in advance.

This should give you the necessary example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwitchExample
    public static final void main(String[] args)
        final JTextField field = new JTextField(20);
        final JComboBox combo = new JComboBox();
            combo.addItem("Item 1");
            combo.addItem("Item 2");
        final JPanel panel = new JPanel();
            panel.add( field );
        JButton button = new JButton("Switch");
            button.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(field.isShowing()) {
                        panel.remove( field ); // remove old component
                        panel.add(combo, 0); // add new component 
                    } else{
                        panel.remove( combo );
                        panel.add( field, 0 );
                    panel.validate(); // recalculate the layout
                    panel.repaint();  // redraw components on screen
        panel.add( button );
        JFrame fp1 = new JFrame("Switch Example");
        fp1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fp1.setContentPane(panel);
        fp1.pack();
        fp1.setLocationRelativeTo(null);
        fp1.setVisible(true);
}ICE

Similar Messages

  • How can I change my apps into .ipa

    Hi.
    I am beginner(and also Korean. So my English will bad.)... And I have some question.
    How can I change my apps into .ipa that I made...
    Well, you know what...
    If we want to put apps in our iPad or iPhone or iPod, we need .ipa file..
    So if I want to put my apps in to iPod,
    what should I do?
    T.T (Crying)
    Tell me the way to solve this.
    "HOW CAN I PUT MY APPS INTO MY IPOD?"

    You need a certificate to be able to install ipa.
    Ipa is accesibles via Product / archive in the menu. You must be in compiler iOS Device for it.
    Otherwise you can directly compile on your device. (with run if your device is connected to your Mac)

  • How can I change my JApplet into a JApplication?

    I am working with a JApplet and am finding that some of my code only works in applications.
    So being new to this, I am clueless as to how to change my Applet into an Application. I understand the difference in definition between the two, but when it comes to looking at Applet Code and Application Code, I am not able to see a difference. (Other than an Applet stating "Applet")
    So, that being said how can I change my code so that it runs as an application and not an applet? Here is my current layout code
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
         // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         }

    baftos wrote:
    Here is one of the sites that explains the procedure:
    [http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
    But maybe you should try to fix the code that does not work as applet?
    Which one is it?
    >Here is one of the sites that explains the procedure:
    [http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
    But maybe you should try to fix the code that does not work as applet?
    Which one is it?
    The code that doesn't work in my applet is the exit button code
    else if (source == exitButton)
                        System.exit(1);
                   }I also can't get my program to properly validate input. When invalid input is entered and the user presses calculate, an error window should pop up. Unfortunately it isn't. I compile and run my applications/applets through TextPad. So when I try to test the error window by entering in invalid info, the applet itself shows nothing but the command prompt window pops up and lists errors from Java. Anyhow, here is the method I was told to use to fix it.
    private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;
         }My Instructor told me to try the following, but I still can't get it to work.String content = textField.getText();
    if (content.length() != 0) {       
    try {          Integer.parseInt(content);  
    } catch (NumberFormatException nfe) {}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How can i change analog waves into digital waves?

    we had labview lab last week.. were doing fine if we have instructions unfortunately the professor will give us an exercise regarding baseband signals spectra.. were trying to download a trial software but we dont have any luck. the question asks for us to change analog waves into digital waves, measure the amplitude of the 5-th harmonic using spectrum analyzer.. i hope you can help me thnx..

    After you are successful getting LabVIEW on your computer, put together something to at least show us you're up for learning.  Then we can guide you to a solution that you've developed (mostly) on your own. 
    Bill
    (Mid-Level minion.)
    My support system ensures that I don't look totally incompetent.
    Proud to say that I've progressed beyond knowing just enough to be dangerous. I now know enough to know that I have no clue about anything at all.

  • Firefox is in German, how can I change the language into Japanese?

    I remember I installed it in Japanese, but recently I have downloaded some program which is to be updated following warnings informed by UpdatStar Gmbh, suddenly the language has changed into German. And all of guidance to daownload other programs are in German. So that I can do nothing....because I cannot understand any of German.
    I am Japanese, so that Japanese is most convieniet for me, but I can undestand English, so change German into English is acceptable.

    If you have the Firefox user interface (menu bar) in the wrong language or want to change the current language then you can get Firefox in the language of your choice here:
    * http://www.mozilla.com/firefox/all.html
    Uninstall the current Firefox version, but make sure that you do not remove your personal data.<br />
    Install the new Firefox version of the wanted language.
    You may need to (re)set the pref "general.useragent.locale" to the preferred language (e.g. "en-US" or "en-GB" or "ja") on the about:config page.<br />
    You can open the about:config page via the location bar, like you open a web site.<br />
    Use the Filter bar at the top of that page to quickly locate the pref.

  • How can I change I tune into English from another language?

    My itune is set in Korean.  I want to change that to Enlish.  How do I do that?

    Take a look here:
    iTunes: Changing the display language
    Regards.

  • How can I change a contact into a vcard

    I need to change a contact in my addres-book as a vcard in front of importing the data as a contact on Strato. Creating a csv file doesn`t work. When asking the technical support of Strato , they told me, that this file couldn`t found. They gave me the advice to change it to a vcard, first. Can you help me in solving my problem?

    Try this add-on: https://nic-nac-project.org/~kaosmos/morecols-en.html

  • I visit the app store to refresh my CAD WS. However, when i click the button below the brand to refresh, the ID certification turns up and it doesn't show my ID but other's. How can I change this ID into mine?

    I have passed the ID certification in app store in the settings though . I just can't download the programme as the ID certification doesn't show my ID.

    Nothing can be better if you can read Chinese below.
    Ipad一代登入app store的“更新”页面,想要下载程序更新。但是按下“更新”键后弹出的ID登录框都是之前一位用户的ID(例如[email protected]),不能改成现在ID(例如[email protected])。尽管已经尝试在“设置”的“Store”里用[email protected]登录成功了,但是按下“更新”键后弹出的ID登录框总是之前一位用户的ID(例如[email protected]),就是改不过来,请问怎么办?

  • How can I change/add keywords into the TB routine, when asking for missing attachments? e.g. German vs. English

    Heja
    I'm using the German TB version (well you can blame me but its now as it is :O)
    Nice thing is that TB asks when keywords appear to make me not to forget the attachment. But can I add here kewords? I use the German version but half of my day I write english mails. I'd like TB to search not only for the German expression but also the english term(s) for attachment etc.
    Is this possible?
    Thanks!
    cheers
    Marten

    You could try adding an English word like 'Attach'
    Tools > Options > Composition > General tab
    or
    Menu icon > Options > Options > Composition > General tab
    click on 'keywords' button.
    You can also get to same Options window from a new Write window.
    Type eg: 'attach' or what ever it is in german to get Write to think an attchment needs to be added.
    at the bottom on the left side, it will say 'Found an attachment keyword' - probably in german.
    click on those words to open the same Options Keywords window
    Then you can add words in English eg: 'attach', 'attachment', 'attaching'

  • [SOLVED]How can i change the orientation of a jcombobox

    hi friends,
    in a frame i put a jcombobox and i want that data it it becomes from the right to the left.
    i tried the famous SetComponentOrientation() but really it didn't give me the solution because only the combobox changes direction howerer the data in the combo still from the left to the right.
    i wish that you help me
    Message was edited by:
    7rouz

    the solution is :
    jComboBox1.setRenderer(new DefaultListCellRenderer() {
    /** {@ineheritDoc}
    @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    setHorizontalAlignment(RIGHT); //voir commentaires plus bas.
    return this;
    });

  • Now that i have installed the software how do i change a pdf into a word doc

    now that i have installed the software how can i change a pdf into a word doc

    Hi patm23422687,
    I hope by saying 'installed the software', you mean that Acrobat XI is now installed on your computer.
    Now, open the PDF in Adobe Acrobat and choose "File> Save as Other> Microsoft Word"
    This is all you need to do
    Please try and let me know if you need further assistance.
    Regards,
    Anubha

  • After the latest update, all my apple products reverted to an old icloud account.  As it no longer exists, I cannot get into it to delete it and add the correct id.  How can I change this, especially on my Macbook pro?

    After the latest update, all my apple products reverted to an old icloud account.  As it no longer exists, I cannot get into it to delete it and add the correct id.  How can I change this, especially on my Macbook pro?  There is no p/w related to it and even though I tried to reset "password" it won't allow as the id does not exist, neither does the email associated with the old id.  How do I switch it to a newer id?

    It's all rather odd because the old account cannot 'no longer exist' - if you don't have the correct password you won't be able to get into it, but you can't actually delete an iCloud account from the server.
    I'm afraid you will need the services of iCloud Support. If you currently happen to have AppleCare, either because you recently bought Apple hardware or have paid to extend the inititial period, you can contact them here:
    http://www.apple.com/support/icloud/contact/
    You will need the serial number of the covered hardware.
    If you are not covered by AppleCare, then - in common with other free email services - there is no free support and you may be asked to pay a fee.

  • How can i change my old master card account into my new master card account in app store?

    HOw can i change my old master card account into my new master card account?

    Howdy Aldringwapo,
    Thanks for using the Apple Support Communities.
    To change the payment information associated with your Apple ID, follow the directions in the article below.
    Change or remove your payment information from your iTunes Store account (Apple ID) - Apple Support
    Have a good one,
    Alex H.

  • Seen this question before but no answer, how can I change my email address from all caps into a more proper upper-lower style.

    Seen this question before but no answer, how can I change my email address from all caps into a more proper upper-lower style.

    You should be able to change your e-mail address from your provider ... then edit it to meet the Apple requirements.   Unfortunately you've given us no profile details so we can't tell what device you have.

  • MY APPLE ID EMAIL ACCOUNT WAS STOLEN BY SOMEONE, AND I NOW I CAN NOT FIX THAT. SO I OPEN A NEW GAMIL HOW CAN I CHANGE MY APPLE ID INTO A NEW EMAIL ADRESS? THANKS.

    MY APPLE ID EMAIL ACCOUNT WAS STOLEN BY SOMEONE, AND I NOW I CAN NOT FIX THAT. SO I OPEN A NEW GAMIL HOW CAN I CHANGE MY APPLE ID INTO A NEW EMAIL ADRESS? THANKS.

    If you are going to change your AppleID login you will need to log out and back in on all your devices. Turn off 'Find My iPhone/iMac/iPod' first or you will find yourself unable to sign out and be stuck.

Maybe you are looking for

  • Is there any way to prevent a wifi network from becoming known?

    Hi, I'm on mid 2010 Macbook Pro running OS X 10.9.4 and I can't figure out a way to prevent a certain wifi network from becoming known. My college's network requires an in browser sign up every time and once the network becomes known it gives me an S

  • Saving data in database from jsp form

    I have a very huge table in my jsp...600 entries. my form table is like this. the number of rows depends upon the number of days in a month. there is one colum which specifies the time frame in 1 hr frame and withing each column is two coulmn represe

  • Scroll bar in pivot view.

    Hi, I am hemant, i have report developed on pivot view which has some where 100 records. I am using this report in dashboard. where users will scroll to seee the recorords which are available below, when they scroll they are not able to see the colum

  • Need help in PO Approval Group Query

    Hi, I need a Query which will list of users that has the Approval Group "BUYER" and "BUYER_DEMO" assigned to them. It will be needful if anyone provides me the Query Thanks and Regards

  • Transfer posting from Sloc to Sloc

    Hi, We do TF from storage location to storgae location with in the palnt using 311 mov. type against Reservation.It is taking 3days for the stock to receive physically in the receiving storage location. Now the client wants the stock to be" in transi