Blank values for editable JComboBox

Hello,
I have a editable JComboBox that the user can erase its current value and if they simple change focus (like click on a text field on the same panel) the combo box is left blank. i would like to have it so that if the user leaves focus of the box and its blank that current value goes back to what it was before they erased it.
Many thanks,
Jonathan

import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class NonBlankCombo {
   JComboBox comboBox;
   Object previousContent;
   void makeUI() {
      Object[] data = {"One", "Two", "Three", "Four", "Five"};
      previousContent = data[0];
      comboBox = new JComboBox(data);
      comboBox.setEditable(true);
      comboBox.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED
                  && !((String) comboBox.getSelectedItem()).trim().isEmpty()) {
               previousContent = comboBox.getSelectedItem();
      comboBox.getEditor().getEditorComponent().addFocusListener(new FocusListener() {
         public void focusGained(FocusEvent e) {
            previousContent = comboBox.getSelectedItem();
         public void focusLost(FocusEvent e) {
            if (((String)comboBox.getSelectedItem()).trim().isEmpty()) {
               comboBox.setSelectedItem(previousContent);
      JFrame frame = new JFrame("Non-blank Combo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(200, 100);
      frame.setLayout(new FlowLayout());
      frame.add(comboBox);
      frame.add(new JButton("Click"));
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            new NonBlankCombo().makeUI();
}db

Similar Messages

  • How to return blank value for a column

    Hi All
    We would like to create a short version of the BI report for the scorecards that has the same number and order of the columns, but far less rows. This will improve the size and performance of the Overhead, Services scorecard.
    For some columns, we need blank values , which means the content should be blank , but the column should appear in the report.
    I have tried checking some options in "column format" tab under column properties and played with "column header interaction" and "value interaction" , however i couldnt get the desired results.
    Can we achieve this?
    Please suggest me on the same.
    Regds
    Mano

    Mano wrote:
    For some columns, we need blank values , which means the content should be blank , but the column should appear in the report.Can you not just add any colulmn from the subject area and change its formula to '' ? You can rename the column name, and it will show blank values for all the records.
    Assign points if helpful.
    Regards,
    -Amith.

  • Preventing blank values for dDocAccount

    We are using Oracle Services using RIDC. I have few questions regarding dDocAccount:
    1. How do you make dDocAccount a required parameter using the UCM configuration manager?
    2. During document checkin, the dropdown for account displays a blank value along with some custom accounts. How do I prevent the blank value from appearing?

    1) You can achieve this by removing the ability of users to checkin 'documents without accounts'
    You can access this setting from User Admin Applet >Users tab > Edit > Accounts tab > documents without accounts ()
    you can leave them with documents without accounts (R) if you like.
    This does mean everything must be checked in a named account byt this user.
    You will notice the Account field goes red on the checkin page to symbolise that it is mandatory
    2) Without a customization I am not sure you can do this...it would be very easy to est a default value via profiles/rules however.
    Tim
    Edited by: Tim Snell on 15-Feb-2011 06:14

  • Setting default value for a jcombobox based on the value not the index

    I am trying to set the default value for my combobox to the current year. One way I thought of doing it was to get the index of the value representing the current year and then use setSelectedInex to make it the default. Any ideas?
    The relevent section of code is below.
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    int year = gregorianCalendar.get(Calendar.YEAR);
    String currentyear = year + "";
    int startyears = 2000;
    int numyears = 25;
    JComboBox endyearcombobox = new JComboBox();
    endyearcombobox.setBorder( BorderFactory.createLineBorder(Color.DARK_GRAY));
    endyearcombobox.setFont(standardfont);
    endyearcombobox.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent event ) {
    endyearcombobox = ( JComboBox )event.getSource();
    endyear = endyearcombobox.getSelectedItem();
    boolean same = endyear.equals(oldItem);
    oldItem = endyear;
    String[] endyearlist = new String[numyears];
    for(int i = startyears; i < startyears+numyears; i++){
    String item = new Integer(i).toString();
    endyearcombobox.addItem(item);
    Thanks
    Ged

    Thanks mate,
    That was what I was looking for. I still had a little more manipulation to do, but sent me on the right track and have got it working now. I don't know why I didn't think of it in the first place.
    Ged

  • Default the blank value for MessageChoice

    Hi,
    I have created a Message Choice Bean and I require to have a blank value as the first value followed by the original values. How to achieve this ?
    I have also tried setting through personalization 'Add Blank Value' to 'true' and also tried with the function 'setAllowBlankValue(true)' for the messagechoice bean. But its not working.
    Please help me by giving the valuable suggestions to achieve the above.
    With Thanks,
    Thiyagarajan

    The only possible case of this happening, is you might have made required property as true, which removes blank value because if value is required in messagechoiceebean, then blank alue can not be included.
    --Mukul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Set init values for Edit Form

    Hi!
    I'm using JDev 10.1.3+ADF+Struts
    I have some attributes in viewObject, and have related bindings in PageDef. I whant to set init values for that attributes in 2 cases:
    1. Edit Form doesn't contain fields for entring attribute value.
    For example:
    Current_User
    Creation_Date
    etc.
    2. Edit Form contain fields for entring attribute value. And i want that input fields display my init values.
    The purpose is to perform it in onCreate event in PageController.
    But i don't know where to put my values.
    Any help will be appriciated!

    Thank you very much!
    Maybe my question is not so clear.
    I mean, when we call event=Create i need to set values, but before Submit/Commit the Row in viewObject is not exist.
    So I founded solution for this issue - to set my values in method 'create' of Entity Object.
    I have another big problem i confused with. Would you help me, please?
    Description is here:
    Database Constraint Error Handling on create/edit (Struts ADF)

  • Update the testfield when setSelectedItem() for editable JComboBox

    Hi,
    I am having problem with setSelectedItem() and setSelectedIndex() methods of editable JComboBox.
    I extended JComboBox with default dataModel. When I enter some string in the textfield of the combobox, I call insertItemAt() method to dynamically grow the list. The application requires to clear the textfield everytime I enter something and press "return" key. To make it work, I insert an empty string to the list at the very beginning and call the setSelectedItem("") method in the actionPerformed().
    Now the problem is that I know the setSelectedItem("") is called since the getActionCommand() returns "comboBoxChanged" everytime I enter something in the textfield, but the testfield is not cleared. And if I select one item from the list and press "enter" key, the textfield is cleared. To make things more interesting, after I enter the first string and press "enter", the textfield really get cleared, but not for all other later input. Is this a bug? Can anyone please help me? Thanks a lot. Below is my code snippet.
    public class MyComboBox extends JComboBox implements ActionListener
    public GsISCommComboBox()
    jbInit();
    private void jbInit() throws Exception
    this.setEditable(true);
    this.addActionListener(this);
    insertItemAt("",0);
    public void actionPerformed(ActionEvent e)
    String str=null;
    String strrr=e.getActionCommand();
    System.out.println("getActionCommand: "+strrr);
    if(strrr.equalsIgnoreCase("comboBoxChanged"))
    str=(String)this.getSelectedItem();
    return;
    else
    str=strrr;
    // other stuff to process the string and do things
    setSelectedItem("");
    repaint();
    hidePopup();
    insertItemAt(str,0);

    Try inserting your string first and then, try clearing the combobox's textfield.
    insertItemAt(str,0);
    setSelectedItem("");
    hidePopup();
    repaint();
    Since you add the "" string at the begining, it will have the index 0. Perhaps, you want to insert your string this way:
    // insert string at the end
    insertItemAt(str, this.getItemCount());
    //Then use the
    setSelectedIndex(0);
    But you need to remember that if you add an item at the begining, index 0 may not be your '' '' string after that.
    I hope that it helps.

  • Displaying blank value for the Rounding Value field in MM03 transaction

    Hello All,
    We are using BDC to create a material master record.Some users are not loading the rouding value in the MRP1 screen. The rounding value is stored in the MARC table which has the data type as QUAN. Thus when there is no value being passed it implicitly converts the blank value to 0.00. The users do not want the rounding value to be displayed as 0 when they view the material record using mm03. Kindly let me know if there is any way to display the rounding value as blank if no value is present.
    Thanks in Advance.
    Regards,
    Avinash Sai N S

    Hai siddharth,
    I have enabled the BADi HRPBSIN_ADDITIONAL_CHECKS to do validations for loans. Can u pls explain is there any FM or wat can be used to set default value for the field in portal.
    Pls give some suggestions,
    thnaks,
    Nalla B.

  • How to create a default value for a JComboBox through his model

    Hi,
    I have created a "myComboBox" component.
    This component extend the standard Java JComboBox and simply add some helper features.
    The values that "myComboBox" display are coming from his bound model. (In fact, "myComboBox" has been designed to allow JComboBox to be implemented accordingly to the MVC design pattern: The model contains the data, the view the GUI and the controller handle the GUI events).
    My question is how can I add a default "none" item to the content displayed by an instance of "myComboBox" without doing any refactoring of the existing code implementing "myComboBox" ?
    Thank you very much for your help.

    It sounds like what you really want is to display "None" when the selected index = -1. Simple, write a custom list cell renderer that display's something instead of nothing when the index is -1.

  • Saving "blank" page for editing

    I have tried to recreate my blogger blog in my new iWeb design with no success
    Is there anyway I can recreate an "Empty" page template (say with nav and header only) to then place the blog underneath.
    I have a complicated blog with years worth of entries (http://trunkguy.com/blog) and really want to move the articles and menu on the right into the iWeb template but it's proving very difficult.
    Help!

    Hi,
    Are you able to login to SAP Netweaver Administrator screen ?
    Thanks
    Sunny

  • Removing # sign in the Report for Blank Value

    Guys,
    I was trying to use the below code VB, but i am getting error like Expected: End of statement.
    I am new to VB, do anyone have step by step guide to implement the below macro for Excel and remove the # from BEx analyzer.
    Do i need write this macro for each query? I totally dont understand the link.
    Kindly guide to run the macro and avoid # in reporting.
    Do I need to implement this macro on each end user client server ?
    Removing '#' in Analyzer (Report)
    In ODS, there are records having a value BLANK/EMPTY for some of the fields. EX: Field: `Creation Date' and there is no value for some of the records.
    For the same, when I execute the query in Analyzer, the value `#' is displaying in place of `BLANK' value for DATE and other Characteristic fields. Here, I want to show it as `BLANK/SPACE' instead of `#'. How to do this?
    I had a similar problem and our client didn't want to see # signs in the report. And this is what I did. I created a marco in Workbook as SAPBEXonRefresh and run my code in Visual Basic editor. You can run same code in query also as when you will refresh query this # sign will be taken care. You can see similar code in SAP market place.
    I will still suggest not to take out # sign as this represent no value in DataMart. And this is SAP standard. I did convince my client for this and later they were OK with it.
    The codes are below:
    Sub SAPBEXonRefresh(queryID As String, resultArea As Range)
    If queryID = "SAPBEXq0001" Then
    resultArea.Select
    'Remove '#'
    Selection.Cells.Replace What:="#", Replacement:="", LookAt:=xlWhole, _ SearchOrder:=xlByRows, MatchCase:=False, MatchByte:=True
    'Remove 'Not assigned'
    Selection.Cells.Replace What:="Not assigned", Replacement:="", LookAt:=xlWhole, _ SearchOrder:=xlByRows, MatchCase:=False, MatchByte:=True
    End If
    ' Set focus back to top of results
    resultArea(1, 1).Select
    End Sub
    Regards,
    Anand
    Edited by: araj123 on Oct 19, 2010 4:51 PM
    Edited by: araj123 on Oct 19, 2010 4:58 PM

    Anand,
    This is what I have used in the past and works just fine
    Sub HashRemoval()
        Application.ScreenUpdating = False
        Cells.Replace What:="#", Replacement:="", LookAt:=xlWhole, SearchOrder:= _
            xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
        Application.ScreenUpdating = True
    End Sub
    But I have this as a separate macro that can be called any time.
    Cheers
    Craig

  • ODS Key Fields allows blank values in Transformation

    Dear Experts,
    I have two layers:
    1. Datawarehouse layer (purpose is to represent exactly data at the backend)
    2. Consolidation Layer
    Scenario 1:
    In Datawarehouse layer, the fiscal variant is a key field in ODS and I have two other key fields i.e. combine to form a composite key.
    When I load the data from PSA to this ODS, I have a record which contains blank value for the fiscal variant. It successfully loads into the Datawarehouse ODS.
    Sceanrio 2:
    In the consolidation layer, i have 4 key fields out of which fiscal variant is one of them. Now when I load the data from the datawarehouse ods to consolidated ods, it throws an error saying:
    Diagnosis
         An exception fiscvarnt_missing was raised while executin
         module RST_TOBJ_TO_DERIVED_TOBJ .
    System Response
         Processing the corresponding record has been terminated.
    The transformation mapping for the fiscal varaint in both sceanarios is 1:1 mapping with the rule type 'Time Characteristic'.
    My questions is:
    1. Why different behaviour during scenario 1 and sceanario 2
    2. Solution to the above issue
    Thanks
    Jain

    Thanks J.S.
    Yes the format selected in the field for the datasource is 'Internal'.
    When loading the data from R3>PSA>ODSX(Datawarehouse Layer), I have no problems even when the field is blank.
    When loading from ODSX-->ODSY(Consolidated Layer) the empty (blank) field for that records throws error.
    Any ideas?
    Jain

  • Urgent :CHECK BLANK VALUES

    Hi
    I am fetching some data into a date IO but the problem is that some records contain a blank value for that fild.
    So i am using a routine to assign some value to that field based on some logic.
    i have used
    if DATEIO is intial...
    then codn..
    but the code doesnt seems to work.
    Is this the right way to check. or shud i use if DATEIO = '00000000'.

    Hi,
    What you put is correct, but let me review your code:
    Assumptions: You are using the code in update/field routine.
    if comm_structure-date is initial.
    logic......
    endif.
    Cheers,
    Rewards accepted

  • Capturing blank and non blank values in parameter

    In one of the report there is only one parameter “BU VP Name”, now the business has added one more field “Director” to the application and they want this to be as a parameter. Now all the new records will have Director name
     and old records will be blank for Director. How can I create a multi parameter with blank and relevant values for my report. Please note I am using sharepoint list to create the report.
    SFH

    Hi Syedfpl,
    According to your description, you want to add a parameter which include a blank value.
    In Reporting Service, we are allowed to use blank value for a multivalue parameter, but we are not allowed to use null values. So in this scenario, you should insert some blank values(‘’) into column “Director” so that we don’t need convert null values into
    string at query level. Besides, in order to be allowed to use blank values in a parameter, we should choose the option "Allow blank value ("")". Also “Allow multiple values” option should be checked. As we tested in our environment, the
    final result looks like below:
    If you have any question, please feel free to ask.
    Best regards,
    Qiuyun Yu

  • Restore default value for SharePoint Store

    Hi,
    I followed this TechNet article to set up SharePoint App Store! 
    https://technet.microsoft.com/en-us/library/fp161236.aspx
    At the end of the article it stands: 
    In some cases, for example, when you have an on-premises SharePoint 2013 farm where updates are installed infrequently, you will need to run a cmdlet to update the URL used to point to the SharePoint Store:Set-SPAppStoreConfiguration -Url http://office.microsoft.com -Enable $true
    When I changed this value the users couldn't access the store anymore. I tried to change this value by using a blank value for -Url, but it didn't change the value. Now I have a value that doesn't work and I can't change it back to original value which is
    empty! 
    My question is how can I reset this value and remove http://office.microsoft.com from my farm?
    Regards
    Henrik A. Halmstrand
    sharepointrevealed.com
    getspconfig.codeplex.com
    Please click Mark As Answer; if a post solves your problem or
    Vote As Helpful; if a post has been useful to you.

    Hi,
    Refer to the following to turn off the SharePoint Store.
    Set-SPAppStoreConfiguration -Enable $false
    Refer to the following article about Set-SPAppStoreConfiguration:
    https://technet.microsoft.com/en-us/library/jj730451.aspx
    Best Regards,
    Lisa Chen
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

Maybe you are looking for

  • Sharing Photos in Photoshop Elements 9

    I want to use Photoshop Elements 9 to send photos via e-mail (it reduces the photo size). I updated 'preference>shared using two methods:-  1)Windows Live and 2) Adobe e-mail services (tried both ways). Using Windows Live method a message came back i

  • Connecting Iphone to computers

    I have my iphone synced with my mac powerbook, no probs. But there are some songs on another computer (my eMac) which I want to move to my iphone. However, when I connect the iphone to the eMac a message comes up saying (something like) "iTunes could

  • SAP Suucontract process in India scenerio

    Dear SAP gurus 1. We implement subcontract process. For this process, make challan which create thru J1IF01, in this T code we wish to put some data like Truck No, Transporter Name, Nature of Processing thru Text Tab like Shipping instructions, Natur

  • HT201210 Restore mode

    problem while trying to update my iphone 4 said would go to restore mode does that mean i loose all my music, texts and photos?

  • How do i disassembl​e the printer hpofficeje​t 6210 all in one ( paperjam with glue paper - gluein)

    HP officejet 6210 all in one Paper jam with selff-stick paper. I can not remove it. I tore it apart while trying to remove it, and now I can no teven see the left over self-stick paper. I need to disaasemble the unit to remove this glue paper. Wher c