JComboBox and JFormattedTextField

Hi ppl.
I'm trying to set up an input mask in my editable combo.
I tried this:
JTextField editorComponent = (JTextField) combo.getEditor().getEditorComponent();
DefaultFormatterFactory factory = new DefaultFormatterFactory(fmtData);
((JFormattedTextField) (JTextField) editorComponent).setFormatterFactory(factory);
and got on runtime
javax.swing.plaf.metal.MetalComboBoxEditor$1 cannot be cast to javax.swing.JFormattedTextField
I tried that and got the same problem:
JFormattedTextField ftf = new JFormattedTextField(fmtData);
combo.setEditor((ComboBoxEditor) ftf);
javax.swing.JFormattedTextField cannot be cast to javax.swing.ComboBoxEditor
How to handle this errors or how to set up an input mask for combo editor by another way?
Thanks in advance.

maybe with this one you can..., but you have to implements change ItemValue
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.RoundingMode;
import java.text.Format;
import java.text.NumberFormat;
public class NumberJComboBox implements ComboBoxEditor {
    private JFormattedTextField field;
    private NumberFormat format;
    private JComboBox cb;
    private JFrame frm;
    public NumberJComboBox(Format f) {
        field = new JFormattedTextField(f);
    @Override
    public void addActionListener(ActionListener l) {
    @Override
    public void removeActionListener(ActionListener l) {
    @Override
    public Component getEditorComponent() {
        return field;
    @Override
    public void selectAll() {
    @Override
    public void setItem(Object value) {
        field.setValue(value);
    @Override
    public Object getItem() {
        return field.getValue();
    public NumberJComboBox() {
        format = NumberFormat.getNumberInstance();
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        format.setRoundingMode(RoundingMode.HALF_UP);
        NumberJComboBox ncb = new NumberJComboBox(format);
        Double dbl[] = {1002.22, 154.22, 15.4578, 1000.0, 100.00, 0.12};
        cb = new JComboBox(dbl);
        cb.setEditable(true);
        cb.setEditor(ncb);
        frm = new JFrame();
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.getContentPane().add(cb);
        frm.pack();
        frm.setVisible(true);
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                NumberJComboBox calc = new NumberJComboBox();
}

Similar Messages

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • Using KeyMap in Editable JComboBoxes and JTable

    I am using Keymapping for JTextFields. It works fine ! I am interested in extending the keymap feature to JComboBoxes and JTable.

    if you want to do the keymapping inside the editable component of the combobox or the table, make sure you apply it on the editor component.e.g. comboBox.getEditor().getEditorComponent() and table.getCellEditor().getTableCellEditorComponent().

  • Help with JComboBox and Model creation

    hi,
    I'm trying to figure out the best way to set up the data behind the JComboBox and copy part of that data to be shown by the JComboBox. Here is what I would like it to do.
    My data:
    itemID, dbaseID, name
    1, 2, test1
    2, 2, test2
    3, 2, test3
    The JCombo will only display the name in this case "test1", "test2", or "test3". However when the user selects the name, I want to easily retrieve the hidden itemID or dbaseID. I've got the combobox working with just the "test1" but it doesn't tell me which dbase it is from. I have to search all of them and worry about identical names.
    What is the best way to set this up? I was thinking about an multiDimensional model but not sure how that would look. It is just not clicking how set up the data and then add parts of to the combo box.
    Any guidance or examples would be appreciated.

    From what I can tell both getSelectedItem() and getSelectedValue() return the string value of the GUI component. Read the API, that is not what they return. They return the "selected" Object.
    The renderer, by default, displays the toString() value of the Object.
    I'm casting the string into Item No you aren't, because that is not possible.
    My understanding was casting was just converting one thing to another.Casting does not "convert" anything. Time to get out your Java textbook and read up on casting.
    However this looks like it is actually grabbing the memory point to an item.Exactly. The getSelected... methods simply return a reference to the Object that was selected. Thats all any get... method does.

  • Error in JComboBox and JMenu with JDK 1.6

    We have a Desktop application that uses JMenuBar, JMenu, and JMenuItem and JComboBox. As we use the application, is the disappearance of the menu items, ie, they are not painted and does not drop down.
    We tested with jdk1.6.0 update 17.
    We tested with jdk1.6.0 update 22.
    We tried to force the paint component among other ways to make it work, but without success!
    We would like to know if it's a bug in Swing because we know other applications that use implementations Desktop also the same problem occurs.
    We look back!
    Edited by: Rubens on May 13, 2012 10:16 PM

    Works for me. The updates you tried are rather old too. But I would first suspect your code. Adding menu items fom the wrong thread for example.

  • Problems with MaskFormatter and JFormattedTextfield

    Hi,
    I'm new to the forum and Java programming so if anyone is willing to answer this query with a small degree of patience I would be immensely, humbly grateful!
    I'll say firstly that I wrote the program in jdk1.4.2 then recompiled it in 1.6.0 in the vain hope that the problem would go a way, but no such luck.
    Right, I'm using one Formatted textfield with a MaskFormatter on which I change the mask according to what information I want from the user:
    class myFormatter extends MaskFormatter {
              String key;
              public void setMask(String k){
                   key = k;     
                   if (key.equals("text")) {
                        try{
                             super.setMask("*************"); // for text, eg star names
                             super.setValidCharacters("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("num")) {
                        try{
                        super.setMask("****#"); // for numbers 1-10000 eg frame num
                                    super.setValidCharacters("0123456789\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("epoch")) try{
                        super.setMask("####.#"); // for epoch
                        super.setValueContainsLiteralCharacters(true);
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("yna")) try{
                        super.setMask("L"); // for single lower case characters eg y/n/a
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("coord")) try{
                        super.setMask("*## ## ##"); // for RA/Dec
                        super.setValueContainsLiteralCharacters(true);
                        super.setValidCharacters("0123456789+-\u0020");
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else if (key.equals("reset")) try{
                        super.setMask("*********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
                   else  try{
                        super.setMask("********************"); // accept anything
                        }catch (java.text.ParseException e) {
                        System.err.println("Problem with formatting: " + e.getMessage());
                        System.exit(-1);
    -----------------------------------------------------------------------------------------------------Ok, now I've only gotten as far as checking the implementation of the "epoch", "text", "yna" and "coord" keys. I've discovered two main problems:
    1. The A, ? and H masks in MaskFormatter just simply did not work; the textfield would not let me enter anything, even when setting the valid the characters, hence having to use * for implementing the "text" key.     
    But most importantly:
    2. The "coord" mask will not let me enter anything (example coordinates -32 44 55) and when I try (in particular press the backspace to start entering at the beginning of the ttextfield instead of the middle, where the cursor is put) I presented with this horrendous complaint from the compiler:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.text.MaskFormatter.isLiteral(MaskFormatter.java:566)
    at javax.swing.text.MaskFormatter.canReplace(MaskFormatter.java:711)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:560)
    at javax.swing.text.DefaultFormatter.replace(DefaultFormatter.java:533)
    at javax.swing.text.DefaultFormatter$DefaultDocumentFilter.remove(DefaultFormatter.java:711)
    at javax.swing.text.AbstractDocument.remove(AbstractDocument.java:573)
    at javax.swing.text.DefaultEditorKit$DeletePrevCharAction.actionPerformed(DefaultEditorKit.java:1045)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2844)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2879)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2807)
    at java.awt.Component.processEvent(Component.java:5815)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:693)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:958)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:830)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:657)
    at java.awt.Component.dispatchEventImpl(Component.java:4282)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    A NullPointerException??? I even tried priming the textfield by setting the value using formatTxt.setValue(format.stringToValue("+00 00 00")).
    Does anyone have any ideas on this error (or how I can get around this without delving to much into other filtering classes)? Has anyone had similar problems with the MaskFormatter masks not accepting what they claim they do (I looked through the posts on the subject).
    Thanking you in advance for you patience........

    Hi,
    Thank you very much for your prompt reply.
    I've done as you said - written a smaller program to test each mask. They don't work quite as I expected but you're right, each mask works fine, its changing the masks that's the problem. I wrote this to test it out:
    public class testMask {
    //Note:      main() won't let u access object/variable methods if declared here
    // GUI items to be globally accsessed:
         JFrame MainWin;
         JPanel panel, panel1;
         JLabel question, answer;
         JButton send, askQues, change;
         JFormattedTextField formatTxt;
         myFormatter format;
    // I/O to be globally accessed:
         String usrinput = null;
         public static void main( String[] args ) {
              testMask GUI = new testMask();
         public testMask(){
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public synchronized void run() {
                              create();
                 });                              //     thread safe code to make sure that UI painting is not interrupted by events, possibly causing the UI to hang
         public synchronized void create(){
              //set look and feel of GUI
              try {
              } catch (Exception e) {
                             System.out.println("Error - Problem displaying window");
              //initialise main window and set layout manager
              MainWin = new JFrame("Test Masks");     
              MainWin.getContentPane().setLayout(new BorderLayout());     
              // initialise containers to go on MainWin
              panel = createPanel();
              MainWin.getContentPane().add(panel, BorderLayout.CENTER);
              MainWin.pack();
              MainWin.setSize(300,150);
              MainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              MainWin.setLocation(150, 150);
              MainWin.setVisible(true);
         public synchronized JPanel createPanel() {
              JPanel panel1 = new JPanel();
              panel1.setLayout(new GridLayout(3,1));
              Border border = BorderFactory.createEtchedBorder();
              panel1.setBorder(BorderFactory.createTitledBorder(border, " Test Panel "));
              question = new JLabel("Please enter drive");
              answer = new JLabel();
              answer.setBorder(border);
              panel1.add(question);
              JPanel pane1 = new JPanel(new FlowLayout());
    //------Set up formatted textfield for user input to be verified--------
              format = createFormatter();
              format.setMask("drive");
              formatTxt = new JFormattedTextField(format);
              formatTxt.setColumns(10);
              send = new JButton(" Send ");
              send.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              send.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        try{
                             formatTxt.commitEdit();
                        } catch (java.text.ParseException exc) {
                             answer.setText("Problem with formatting: " + exc.getMessage());
                             return;
                        SwingUtilities.invokeLater(new Runnable() {
                             public synchronized void run() {                         
                                  if (formatTxt.isEditValid()) {
                                       usrinput = formatTxt.getText();
                                       answer.setText(usrinput);
                                  } else { answer.setText("Input not of valid format"); }
              change = new JButton("Change mask");
              change.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              change.addActionListener(new ActionListener(){
                   public synchronized void actionPerformed(ActionEvent e) {
                        question.setText("Please enter coord in format ## ## ##");
                        format.setMask("coord");
              pane1.add(formatTxt);
              pane1.add(send);
              pane1.add(change);
              panel1.add(pane1);
              panel1.add(answer);
              return panel1;
         protected myFormatter createFormatter() {
              myFormatter formatter = new myFormatter();
              return formatter;
    class myFormatter extends MaskFormatter {
         String key;
         public void setMask(String k){
              key = k;     
              if (key.equals("coord")) {
                   try{
                        super.setMask("*## ## ##"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else if (key.equals("drive")) {
                   try{
                        super.setMask("L:"); // for disk drive
                        super.setValueContainsLiteralCharacters(true);
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
              } else  {
                   try{
                        super.setMask("********************"); // accept anything
                   }catch (java.text.ParseException e) {
                        answer.setText("Problem with formatting: " + e.getMessage());
                        return;
    }When I click on the "change" button, the textfield won't let me enter anything in, no matter what I change the mask from or to.
    Does anyone have any idea how I can implement the mask change dynamically? The only thing I could think of was to somehow re-initalise the textfield then do a repaint, but I don't know how or if that would even work.
    Thanking you again in anticipation,
    Mellony

  • How can I fire a change event from a JComboBox and JTextField?

    Is it possible to fire a ChangeEvent from JComboBox?
    Is it possible to fire a ChangeEvent from JTextField?
    If so how can I do that? Thanks.

    You can use an ItemStateListener with the combobox
    As for the textfield, it depends when you want to catch events (every keystroke, or when the user hits enter) but either way, you can do this too. Check keylistener and actionlistener

  • PlainDocument and JFormattedTextField don't work together

    Hello everyone,
    I wrote a PlainDocument only allowing a certain amount of numeric chars to be inserted. This works smoothly with a JTextField.
    The problem is, I need to get it running with a JFormattefTextField, where I added an InternationalFormatter. What happens is, that with each character stringToValue (in InternationalFormatter) is called, insertString (in PlainDocument) is only called on a commitEdit.
    Does anyone know how to change this behaviour?
    Thanks,
    Marc Johnen

    Once again from the java docs
    Warning: As the AbstractFormatter will typically install a DocumentFilter on the Document, and a NavigationFilter on the JFormattedTextField you should not install your own. If you do, you are likely to see odd behavior in that the editing policy of the AbstractFormatter will not be enforced.
    Rereading your post, I thing your international formatter is your conflict point.
    My advice is to use the JFormattedText field as is or don't use it.
    FYI: I tried using JFormattedTextField on my current project and the qa team pretty much hated the fell of it from the get go. I ended up pulling it and writing custome InputVerifier / DocumentFilters where I needed to limit input.
    Hope this helps,
    Todd

  • JComboBox and Tooltips

    Hi,
    I'm creating a project for school in which they want me to populate a JComboBox with a movie list that I created in a text file.
    I was thinking that I want to set a tooltip for each item (movie) and then modify it so that people can see a picture of the movie and a little summary.
    What's the easiest way to do that?
    Or maybe instead of a tooltip I could use different forms? Please, give me some ideas with some code too
    Thanks
    PS: This is the code I'm using to populate the JComboBox.
    private void populateMovies()
    String fileName = "src
    Movies.txt",
    movieList;
    try
    //File Reader
    FileReader content = new FileReader(fileName);
    BufferedReader inputFile = new BufferedReader(content);
    movieList = inputFile.readLine();
    while (movieList !=null)
    movieSelectionJComboBox.addItem(movieList);
    movieList = inputFile.readLine();
    catch(FileNotFoundException exp)
    exp.printStackTrace();
    catch(IOException exp)
    exp.printStackTrace();
    Click to see GUI
    http://i153.photobucket.com/albums/s224/andresmdiaz/AMDGUI.png

    You can set images in tooltips using HTML
    String imageName = "file:image.jpg";
    component.setToolTipText("<html>Here is an image <img src="+imageName+"></html>");
    or for more flexibly but much more complexity, you can make your own tooltip class, here is an example of that:
    http://www.java2s.com/Code/Java/Swing-JFC/ShowinganImageinaToolTip.htm
    btw "image in tooltip java" came up with these results in the top 3. I suggest in the future you have a go, and post your failed attempt, if you fail that is.

  • JComboBox and Vectors

    Hi.
    I am developing an application in netbeans 5.0 using java 6. I would like to place a JComboBox on my GUI using the palette but am not sure how to set the items in the list as coming from a vector, without defining the JComboBox constructor from scratch, as I am able to place the JComboBox where I want it in netbeans using the palette.
    Any ideas on how I can do this through the netbeans IDE? Please let me know if u need more info.
    Thanks
    Message was edited by:
    andy_wood

    I dont actively used netbeans but from looking into what you are asking, I think you could try this.
    1. Open up the properties of the combo box
    2. Open up the combox model editor dialog
    3. use the advanced tab and then try create a post-initialisation procedure using your vector
    ICE

  • JComboBox and textfields

    When you select a row in a ComboBox how do you pass that value of the row to a textfield.
    Any help on this would be greatly appreciated.

    See if this helps. Let us know if it works.
    //All imports here
    public class Trial extends JFrame implements ActionListener
    TextField fid = new TextField ();
    public String[] station = {"Elephant and Castle", "Kennington", "Oval",
    "Stockwell", "Clapham North", "Clapham Common",
    "Clapham South", "Balham", "Tooting Bec", "Tooting Broadway",
    "Colliers Wood", "South Wimbledon", "Morden"};
    JComboBox cb = new JComboBox (station);
    cb.addActionListener (this);
    public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String name = (String)cb.getSelectedItem();
    fid.setText(name);
    }//end method
    } //end class

  • Jcomboboxes and user controlled iteration

    Hello everyone, I'm new both to Java and the forums so I apologize if my questions are a little stupid despite the saying. Well here it is; I'm trying to make a GUI for my latest program. It requires seven JComboboxes with each combo box holding ten options. I tried following the example for combo boxes on the java tutorial site as well as my textbook but I never could seem to get it right. The program is for miniature wargaming statistic simulation. Here is part of my code, in which I want the user to be able to pick a weapon skill from a JCombobox
    public class GUI extends JFrame implements ActionListener
    //JLabel picture;
    // instance variables - replace the example below with your own
    private Container contents;
    * Constructor for objects of class GUI
    public GUI()
    // call JFrame constructor with title bar text
    super("A Shell GUI Application");
    //get container for components
    //set original size of window
    setSize(1650, 1280);
    // setDefaultCloseOperation(JFrame.EXIT_ON_ClOSE);
    //make window visible
    setVisible(true);
    contents = getContentPane();
    Container ca = getContentPane();
    ca.setBackground(Color.lightGray);
    String [] weaponSkill = new String[10]; //Weapon Skill 1-10
    weaponSkill[0] = "1";
    weaponSkill[1] = "2";
    weaponSkill[2] = "3";
    weaponSkill[3] = "4";
    weaponSkill[4] = "5";
    weaponSkill[5] = "6";
    weaponSkill[6] = "7";
    weaponSkill[7] = "8";
    weaponSkill[8] = "9";
    weaponSkill[9] = "10";
    JComboBox weaponSkillList = new JComboBox(weaponSkill);
    weaponSkillList.setSelectedIndex(9);
    weaponSkillList.addActionListener(this) ;
    // JLabel picture;
    // picture = new JLabel();
    // picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
    // picture.setHorizontalAlignment(JLabel.CENTER);
    //updateLabel(weaponSkill[weaponSkillList.getSelectedIndex()]);
    // picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
    //The preferred size is hard-coded to be the width of the
    //widest image and the height of the tallest image + the border.
    //A real program would compute this.
    // picture.setPreferredSize(new Dimension(177, 122+10));
    //Lay out the demo.
    // add(weaponSkillList, BorderLayout.PAGE_START);
    //add(picture, BorderLayout.PAGE_END);
    //setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    public void actionPerformed(ActionEvent e)
    JComboBox cb = (JComboBox)e.getSource();
    String weaponSkill = (String)cb.getSelectedItem();
    The code that is commented out is stuff that I'm not sure quite what to make out of it. But all this code gives me is an empty gui box.
    I was also wondering how user control iteration works, or in other words, how the user could set how many times the code loops by simply typing in a number.
    Thanks for any help!

    Use code tags. I've added some comments to your code:
    public class GUI extends JFrame implements ActionListener //why extend JFrame if you don't override its functionality?
         private Container contents; //this is before the class opening bracket??
          * Constructor for objects of class GUI
         public  GUI()
                 // call JFrame constructor with title bar text
                 super("A Shell GUI Application");
                 //get container for components   
                 //set original size of window
                 setSize(1650, 1280);
    //             setDefaultCloseOperation(JFrame.EXIT_ON_ClOSE); //this should have a capital L in cLose
                 //make window visible
                 setVisible(true);  //you should do this last, after adding all components
                 contents = getContentPane();         //why do you need two references to the same Object?
                 Container ca = getContentPane();  //why do you need two references to the same Object?
                 ca.setBackground(Color.lightGray);
                 String [] weaponSkill = new String[10]; //Weapon Skill 1-10
                 weaponSkill[0] = "1";
                 weaponSkill[1] = "2";
                 weaponSkill[2] = "3";
                 weaponSkill[3] = "4";
                 weaponSkill[4] = "5";
                 weaponSkill[5] = "6";
                 weaponSkill[6] = "7";
                 weaponSkill[7] = "8";
                 weaponSkill[8] = "9";
                 weaponSkill[9] = "10";
                 JComboBox weaponSkillList = new JComboBox(weaponSkill);
                 weaponSkillList.setSelectedIndex(9);
                 weaponSkillList.addActionListener(this) ;    
             //the rest might work if you call it before setting visibility to true
            // JLabel picture;
            // picture = new JLabel();
            // picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
            // picture.setHorizontalAlignment(JLabel.CENTER);
             //updateLabel(weaponSkill[weaponSkillList.getSelectedIndex()]);
           //  picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
             //The preferred size is hard-coded to be the width of the
             //widest image and the height of the tallest image + the border.
             //A real program would compute this.
            // picture.setPreferredSize(new Dimension(177, 122+10));
             //Lay out the demo.
           //  add(weaponSkillList, BorderLayout.PAGE_START);
             //add(picture, BorderLayout.PAGE_END);
            //setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
           //since you are making GUI changes to an already visible window, call revalidate() here
           //or just call setVisible(true) last
         public void actionPerformed(ActionEvent e)
             JComboBox cb = (JComboBox)e.getSource();
             String weaponSkill = (String)cb.getSelectedItem();  
    //no closing bracket for the class?
    I was also wondering how user control iteration works, or in other words, how the user could set how many times the code loops by simply typing in a number.Just set a variable equal to that number and loop that many times?
    for(int i = 0; i < inputFromUser; i++)

  • JComboBox and JList

    hey, i've got a JList - flightsList - and 2 JComboBoxes - from, to. I want to have the list of the flights to appear in each of the 2 combo boxes, but i dnt know how. Please help!! Thanks!!
    JPanel topPanel = new JPanel();
    topPanel.add( new JLabel( "From:" ) );
    from = new JComboBox();
    topPanel.add( from );
    topPanel.add( new JLabel( "To:" ) );
    to = new JComboBox();
    topPanel.add( to );
    topPanel.add( new JLabel( "Date:" ) );
    date = new JTextField( 10 );
    topPanel.add( date);
    JButton button = new JButton( "Query" );
    topPanel.add( button );
    contents.add( topPanel, BorderLayout.NORTH);
    flightsList = new JList();
    contents.add( new JScrollPane( flightsList) , BorderLayout.CENTER );
    JPanel buttons = new JPanel();
    I have defined the following at the top:
    private JComboBox from;
    private JComboBox to;
    private JTextField date;
    private JList flightsList;

    Read the Swing tutorial like I suggested in your other posting.
    You don't add a JList to a combo box.
    You add items to the combo box model and add the model to the combo box.
    The tutorial shows you how to add items to the comboBox add creation time. If you need to update the comboxBox dynamically then read the JComboBox API for the appropriate method.

  • JCombobox and internal component sizes

    Hello,
    I am using a JCombobox in a table header. I would like to change the event handling in that way, that the combobox will be opened only if the arrow button has been selected or the arrow key has been pressed.
    The problem I have is that I do not know the size or lokation of the button inside the JCombobox.
    I created a new HeaderUI where I check the mousePressed event.
    With the function getDeepestComponentAt I get a MetalComboboxButton, but the width seems to be the width of the column size.
    Doese anybody knows how to get the size of the arrow button?
    Claudia

    The API documentation for that method says:
    "Invoked when an item has been selected or deselected. The code written for this method performs the operations that need to occur when an item is selected (or deselected)."
    So, when you change the selection from 4-5-6 to 1-2-3, you deselect 4-5-6 and then select 1-2-3. Two calls result. Fortunately, the ItemEvent parameter has a method getStateChange() that returns either ItemEvent.SELECTED or ItemEvent.DESELECTED, so you can program accordingly.

  • JComboBox and border

    Hi all:
    I have been reading messages about combos and borders, but did not found an answer, so, here it is the question:
    I want a JComboBox that, when not active, does not show any border.
    For the moment, thanks to uiDefaults.put( "Button.border", lineBorder) I have just removed the border in the arrow button. But the selected item label, displayed by a javax.swing.CellRendererPane, still paints a compound border.
    Any help?

    Yes, that's right.
    Following your suggestions I have reached the simplest, I hope, solution. I do not like it very much, because it requires overriding a UI class so future improvements to that class, OK just the method overridden, will not be noticed. But for the moment, it is the only thing I have.
    The solution:
    1.- Register a new ComboBoxUI
    UIDefaults uiDefaults = UIManager.getDefaults();
    uiDefaults.put( "ComboBoxUI"     , "es.shin.plaf.metal.LightMetalComboBoxUI");2.- class LightMetalComboBoxUI
    package es.shin.plaf.metal;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.metal.MetalComboBoxUI;
    import javax.swing.plaf.metal.MetalLookAndFeel;
    * @author jroman
    public class LightMetalComboBoxUI extends MetalComboBoxUI
       public static ComponentUI createUI( JComponent c)
          return new LightMetalComboBoxUI();
       @Override
       public void paintCurrentValueBackground
       ( Graphics g, Rectangle bounds, boolean hasFocus)
          if ( g == null || bounds == null )
             throw new NullPointerException(
                 "Must supply a non-null Graphics and Rectangle");
          g.setColor( Color.LIGHT_GRAY);
          g.drawRect( bounds.x, bounds.y, bounds.width, bounds.height - 1);
          // This is the inner rectangle that makes the border of the label of size 2.
          // I do not paint it, since I want a lighter label.
    //      g.setColor( MetalLookAndFeel.getControlShadow());
    //      g.drawRect( bounds.x + 1, bounds.y + 1, bounds.width - 2, bounds.height - 3);
          if ( hasFocus && !isPopupVisible( comboBox) && arrowButton != null)
              g.setColor( listBox.getSelectionBackground());
              Insets buttonInsets= arrowButton.getInsets();
              if ( buttonInsets.top > 2 )
                 g.fillRect( bounds.x + 2, bounds.y + 2, bounds.width - 3, buttonInsets.top - 2);
              if ( buttonInsets.bottom > 2 )
                 g.fillRect( bounds.x + 2, bounds.y + bounds.height - buttonInsets.bottom, bounds.width - 3,
                             buttonInsets.bottom - 2);
    }I hope this serves to someone...
    Cheers.

Maybe you are looking for

  • AMD RADEON GRAPICHS HD 8750M PROBLEM

    Hey, last week i just bought a new laptop , Lenovo G510. I installed windows 7 (32 bit) and everything works fine , excepts my graphic cip (AMD RADEON GRAPHICS 8750M). In DXDIAG menu it says my graphic cip is Intel(R) HD Graphics 4600. And when i try

  • WAP-WML IDE

    Hi all, I dont know whether its a right palce to post this question or not. Sorry,if its not I m developing a site which can be viewed on any mobile so. I need it to develop it using WML with JSP.. As netbeans doesnt provide WML simulator i need a go

  • Issue of NWDS on PC

    hai ALL, I have installed  EP and nwds on my PC . when i try to configure the J2EE engine in the 'preferences'  window it is not accepting or taking any changes done by me .  Please help me with complete docs on NWDS Thanks, Raghavendra Ach

  • Converting .m2t files to .mov

    How can I convert .m2t files to .mov without loosing any quality?

  • OS X 10.8.5: no sound from DisplayPort after Wake up

    Hi, I have problem with my macbook pro 13" mid 2012 with Mountain Lion 10.8.5. When I turn laptop on everything works just fine but after sleep and wake upthere is no sound coming from displayport. I'm using HP ZR2440W as my desktop display and class