How to use JComboBox

I have an array of objects called procedures. These objects have the attribute int code which I'd like for the JComboBox to display. But instead it displays some other information, such as the directory where these objects were imported from. How do I get it to display only a certain part of the objects in the array that I populate the JComboBox with? Thanks in advance to anyone with an answer.
Joe

You should override public String toString() method in the object instances of what you have in an array.
Just add
public String toString() {
    return String.valueOf(intValue);
}and you'll see those intValues in bundled JcomboBox.

Similar Messages

  • How to use JCombobox (using ComboboxModel) in JTable?

    I have a question first, let imagine that i have 2 tables: Location(IDLocation, Place), Employee(ID, Name, Location)
    And I get all data in Location table into ArrayList, then setup a model (that extends ComboboxModel) and use this arraylist.
    After that i get all data in Employee table into Arraylist, then setup a MyTableModel (that extends AbstractTableModel) and use this arraylist.
    I could setup combobox in Location column, but i just wonder that how do i know how many comboboxes i need?. And if i use one model for all of these comboboxed and when i change selected item in one combobox, it will change data in other comboboxes in other rows. :(
    Anybody helps me, please?

    you just need only one combobox as the editor for all cell in location column.
    because, initially, all the cell in location column is "rendered" as non-combobox, the combobox appears only when you edit one cell, so you use only one combobox for every edition of a cell (in location column).
    The way to do this is to setCellEditor of your JTable to (new DefaultCellEditor(editComboBox)), so that every time you click on a cell (in location column), the combobox appears and your selected value will be the new value in that cell, all you have to do is just set the CellEditor as combobox, java 's done the rest for you.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#combobox : perfect in this situation
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    public class TableComboBox extends javax.swing.JFrame {
        public TableComboBox() {
         initComponents();
        private void initComponents() {
            scrollPane = new javax.swing.JScrollPane();
            myTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            // create a table
            myTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {"E01", "John Bolton", "Boston"},
                    {"E02", "Vannessa", "Ohio"},
                    {"E03", "Hellboy", "Alaska"}
                new String [] {
                    "ID", "Name", "Location"
            // create a combobox which model will be created from the database as the editor
            JComboBox locations = new JComboBox(new String[]{"Boston", "Ohio", "Alaska"});
            // create a default cell editor
            DefaultCellEditor editor = new DefaultCellEditor(locations);
            // set that cell editor as the location column cells editor (column number 2 is location column), then use setCellEditor() method
            myTable.getColumnModel().getColumn(2).setCellEditor(editor);
            scrollPane.setViewportView(myTable);
            getContentPane().add(scrollPane);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-380)/2, (screenSize.height-117)/2, 380, 117);
        public static void main(String args[]) {
         java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
              new TableComboBox().setVisible(true);
        private javax.swing.JTable myTable;
        private javax.swing.JScrollPane scrollPane;
    }Edited by: bobbi2004 on Oct 28, 2008 9:59 AM

  • How to use JComboBox as VB DataCombo?

    I wan't to know if it is possible to use a JComboBox as VB6 DataCombo.
    There are 3 main properties of the VB6 DataCombo component: BoundColumn, ListField and RowSource.
    For example I can set the rowsource of this component to be a recordset containing for the first field a country code and the second field the corresponding country name. Therefore the BoundColumn will be the country code and the list field the country name. This component will display the country name and I am able to retrieve the corresponding country name. Also when I set to country code to this component, the corresponding country name is displayed.
    Is it possible to have the same behaviour with a JComboBox or do I have to use another component?
    Thanks for your help.

    Hi, you are probably long gone ...but I would like to set the record straight.
    After coming back and reading this post again I realized I my memory was a bit foggy about what a VB bound column property was doing. In fact, you DON'T need a CellRenderer to do this, because a CellRenderer is used to manipulate the visible aspect of the cell, and that has nothing to do with the VB bound column concept. I went into Access and reminded myself what VB is using the bound value for ...which is to store an additional value for each cell in the combo, apart from the value that will be displayed in each cell. This value is used to 'bind' the combo to a database query where the invisible 'bound column' value is a primary key value that is used to lookup the rest of the row for that selection. Of course in VB this all happens behind the scenes when you choose to fill the combo from a database query.
    In Java, unless you want to build an entire wizard to match the one in VB, you don't really approach the problem that way. You are going to have to do your own JDBC routine to fill the combo ...then listen for selections on that combo ...and query new values from the database each time the selection changes. However, you could give yourself a bit of leverage by considering the following two approaches.
    First off, you could ...as you read in the combo values from the db ...just add your own special data object into the combo that holds TWO values instead of just putting in the single visual object into the combo.
    //Loop through db results getting both the primaryKey
    //column values and the visible column values...
    mycombo.addItem( (Object) new MySpecialDataObject(primaryKey,visibleValue) );Your class for MySpecialDataObject could be something like this:
    public class MySpecialDataObject {
      private String primaryKey;
      private String visibleValue;
      public MySpecialDataObject(String primKey, String visVal) {
        primaryKey = primKey;
        visibleValue = visVal;
      public String getPrimaryKey() { return primaryKey; }
      public String getVisibleValue() { return visibleValue; }
    }And then when you get the selected object just cast it back into your special type, and then you can access both the primaryKey and the visibleValue for the selection. You can then requery the db using the primaryKey instead of having to use only the visible combo cell value.
    //Inside your action event for the combobox...
    MySpecialDataObject dao = (MySpecialDataObject) mycombo.getSelectedItem();
    String sql = "SELECT * FROM a_table WHERE primKey = " + dao.getPrimaryKey();However, this kind of forces the work onto the application developer to make this one (or possibly many of these) little data capsules each time they are using the combo. Another alternative could be to go to the data model for the combo, and create your own custom subclass that adds the characteristics you are looking for to the combobox itself, relieving the app developer of this minor nuisance. It might be a bit more work up front ...but it will streamline your development in the future by providing a customized combo class for your dev's to use.
    Here is an example of doing just that. The comments cover most of what I have done and why ...I did this over the weekend as my penance for giving you bad advice regarding the Cell renderer. As a bonus, I threw in an example of defining a custom cell renderer as well. Cheers ...silly old GumB.
    P.S. I am sure there are other approaches as well, good luck.
    * BoundJComboBoxModel.java
    * Created on May 23, 2003, 10:51 PM
    package com.gumbtech.ui;
    import java.util.ArrayList;
    * @author  gum
    public class BoundJComboBoxModel extends javax.swing.DefaultComboBoxModel {
      private ArrayList boundObjects = new ArrayList();
       * Above, is an ArrayList for storing the bound values for each element.
       * Below, I have overriden all three constructors from DefaultComboBoxModel.
       * Notice how the second two just create default 'bound values' equal to a
       * string representation of the elements array index integer.  This may
       * work as a default if your primary keys in the database agreed (which
       * they quite possibly could).  However, the model is not really intended
       * to be filled this way.  Instead, use the overloaded addElement method
       * (below) and provide each item and corresponding bound value as a pair.
      public BoundJComboBoxModel() {
        super();
      public BoundJComboBoxModel(Object[] items) {
        super(items);
        for(int i=0; i<items.length; i++) {
          boundObjects.add(String.valueOf(i));
      public BoundJComboBoxModel(java.util.Vector v) {
        super(v);
        for(int i=0; i<v.size(); i++) {
          boundObjects.add(String.valueOf(i));
       * This method overloads its counterpart from DefaultComboBoxModel.
       * This provides a way to add a complete element, by providing values
       * for both the display value and the bound value all at once.
      public void addElement(Object item, Object boundValue) {
        boundObjects.add(boundValue);
        super.addElement(item);
       * Here are the new methods that 'decorate' the original DefaultComboBoxModel.
       * They provide ways to set and get the bound value for a specific element.
       * The method setBoundValueAt is called from the gui when we fill the combo.
       * The method getBoundValueAt is called from the BoundJComboBox class that
       * we are going to build next. It could be called directly on the model, but
       * making a special JComboBox class that used this model seemed a little nicer.
       * You will see the JComboBox class that uses this model next in the example.
      public void setBoundValueAt(int index, Object boundValue) {
        boundObjects.set(index, boundValue);
      public Object getBoundValueAt(int index) {
        return boundObjects.get(index);
      public Object getBoundValueForItem(Object item) {
        int index = getIndexOf(item);
        return boundObjects.get(index);
       * These methods override thier counterparts from DefaultComboBoxModel.
       * They are overriden so we can keep the bound value list in sync.
       * For example, consider the original addElement method from the superclass.
       * Used when no bound value is provided, the method will add a bound value
       * equal to a string representation of the elements array index integer.
       * The other two overriden methods are self explanatory.
      public void addElement(Object item) {
        int idNum = boundObjects.size();
        boundObjects.add(String.valueOf(idNum));
        super.addElement(item);
      public void removeElement(Object item) {
        int index = super.getIndexOf(item);
        boundObjects.remove(index);
        super.removeElement(item);
      public void removeAll() {
        boundObjects = new ArrayList();
        super.removeAllElements();
    * BoundJComboBox.java
    * Created on May 23, 2003, 10:00 PM
    package com.gumbtech.ui;
    import java.util.ArrayList;
    import com.gumbtech.ui.BoundJComboBoxModel;
    * @author  gum
    public class BoundJComboBox extends javax.swing.JComboBox {
       * Here, I have overriden all three constructors from JComboBox.
       * We will 'force' our custom JComboBox to use the BoundJComboBoxModel.
      public BoundJComboBox() {
        super(new BoundJComboBoxModel());
      public BoundJComboBox(Object[] items) {
        super(new BoundJComboBoxModel(items));
      public BoundJComboBox(java.util.Vector v) {
        super(new BoundJComboBoxModel(v));
       * These are the new methods that 'decorate' the original JComboBox
       * class.  We have added methods that match the two methods JComboBox
       * provides for finding elements in the models list, except that our
       * new methods access the bound value list instead of the item list.
       * I only use the getSelectedBoundValue method in this example.  I
       * provided the other because together the two make a complete match
       * to the way the original class lets you query the original model.
      public Object getSelectedBoundValue() {
        return ((BoundJComboBoxModel)this.dataModel)
                .getBoundValueAt(getSelectedIndex());
      public Object getBoundValueAt(int index) {
        return ((BoundJComboBoxModel)this.dataModel)
                .getBoundValueAt(index);
    * BoundComboTest.java
    * Created on May 24, 2003, 12:18 PM
    package com;
    import java.awt.Color;
    import com.gumbtech.ui.BoundJComboBox;
    import com.gumbtech.ui.BoundJComboBoxModel;
    import com.gumbtech.ui.MyCustomCellRenderer;
    * This is a test gui that lets us demonstrate the custom
    * BoundJComboBox that we have created.  We are going to
    * emulate the 'bound column' characteristic of a VB bound
    * combo box object.
    * @author  gum
    public class BoundComboTest extends javax.swing.JFrame {
      public final static String T = "    ";
      private BoundJComboBox boundJComboBox;
      private javax.swing.JLabel msgLbl;
       * The constructor just calls methods that
       * build the gui and then fill the combo box.
      public BoundComboTest() {
        initComponents();
        fillCityComboByProvince("Alberta");
       * This method just sets up the gui components for our example.
      private void initComponents() {
      //Create an instance of BoundJComboBox (our customized JComboBox).
        boundJComboBox = new BoundJComboBox();
      //Plug in a custom renderer for the element cells visual appearance.
      //I put this here so you can see what a CellRenderer does, but this
      //actually plays no part in creating our VB like bound column combobox.
      //Out of interest, you can look at the MyCustomCellRenderer class later on.
        boundJComboBox.setRenderer(new MyCustomCellRenderer(new Color(40,100,60)));
      //Listen for change events on the combo box with an action listener.
      //Inside this action (see the comboActionPerformed method below) lies
      //the real reason for needing the bound column value.  The action needs
      //to translate the combo selection into a database query that retrieves
      //the values to be used on the form that this combo box is controlling.
        boundJComboBox.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboActionPerformed(evt);
      //Create other stuff to host our combo box in (irrelevent to our example).
        msgLbl = new javax.swing.JLabel();
        setTitle("Bound Combo Example");
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
          public void windowClosing(java.awt.event.WindowEvent evt) {
            System.exit(0);
        getContentPane().add(boundJComboBox, java.awt.BorderLayout.NORTH);
        getContentPane().add(msgLbl, java.awt.BorderLayout.CENTER);
        pack();
        java.awt.Dimension screenSize =
           java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setSize(new java.awt.Dimension(400, 200));
        setLocation((screenSize.width-400)/2,(screenSize.height-200)/2);
       * So, your 'bound' combo box needs a visual label that will be
       * displayed in the combo box, here we use city names from a db.
       * Your VB like 'bound column' is going to be the city_ID number, which is
       * the primary key we need to use to look up this cities values in other
       * tables.  Being different from the visible text label ...this value needs
       * to be stored in the special 'bound column' area of our combo box model.
      private void fillCityComboByProvince(String province) {
      //We can get the model out of our JComboBox, notice that the model is of
      //type BoundJComboBoxModel ...which is our own customized ComboBoxModel.
        BoundJComboBoxModel model = (BoundJComboBoxModel) boundJComboBox.getModel();
      //Clear out the combo so we can load it fresh  See how the methods we are
      //used to using in a regular ComboBoxModel now seamlessly handle our
      //parallel list of 'bound column' values.  That's because we over-rode
      //them appropriately in our customized BoundJComboBoxModel.
        model.removeAll();
      //Pretend this is the query we would use to get the values...
      //If we were selecting all the rows in the table, we might not need a bound
      //column bacause they may have a linear set of incrementing primary keys.
      //However, we are selecting a filtered set of cities ...only those from Alberta
      //...so the primary keys will not follow any regular pattern.  This is why the
      //'bound column' concept is used ...to hold a non-visible list of primary keys
      //that match each label in the combo box.  Even though we choose the value
      //'Calgary' in the combo ...we need to use '54' to look it up in the database.
        String sql = "SELECT name, city_ID FROM cities WHERE province = "+ province;
      //Pretend this is the results from our query to the db.
        final Object[] cityNames = {"Calgary", "Edmonton", "Lethbridge", "Red Deer"};
        final Object[] primaryKeys = {"54", "89", "101", "193"};
      //Use the overloaded addElement method we created in BoundJComboBoxModel to
      //fill the combo with both the visual text value, and the 'bound' value.
        for(int i=0; i<cityNames.length && i<primaryKeys.length; i++) {
            model.addElement(cityNames, primaryKeys[i]);
    //See, the combo box now has a 'bound column' for each visual element in
    //its list, which we will use to query the db each time the selection changes.
    //This is all your 'bound column' is doing in your VB wizard ...except you
    //never see the code for it. In Java, you just write the code to give your
    //JComboBox this behaviour ...and more if you so choose (which is really
    //the whole the point here!)
    * The next method handles the selection change event for our combo box.
    * This is where you use the 'bound value'. You use it to requery
    * the db so you can fill in your form with new values each time
    * the combobox selection is changed by the user.
    * This method is your action event for the combo ...and it is doing
    * the same thing that your VB program will do with your 'bound column'
    * in your VB combo box. In VB you just can't see the code, that's all.
    private void comboActionPerformed(java.awt.event.ActionEvent evt) {
    //Get the combobox that performed the action event...
    boundJComboBox = (BoundJComboBox) evt.getSource();
    //If we had a database here for real, we would query for our new form
    // values using the 'bound column' value as the primary key in the query.
    //This is what it means to use the 'bound column' of a VB combobox or list.
    //Its just a value for each element in the combo box that is different from
    //the value that will be displayed in the combo list. That's all it means.
    //VB just uses the bound value to query the database, so we can do that too.
    String sql =
    "SELECT * FROM cities WHERE city_ID = " +
    boundJComboBox.getSelectedBoundValue();
    //Since we don't really have a db, I'll just show the values for the element.
    String msg = "<html><font color=#006666>"+
    T +"Index Selected : "+ boundJComboBox.getSelectedIndex() +"<br>"+
    T +"Value Selected : "+ boundJComboBox.getSelectedItem() +"<br>"+
    T +"Bound Column Value: "+ boundJComboBox.getSelectedBoundValue() +"<br>"+
    T +"</font><font color=#dd3366>"+ sql +"</font></html>";
    msgLbl.setText(msg);
    public static void main(String args[]) {
    new BoundComboTest().show();
    * MyCustomCellRenderer.java
    * Created on May 23, 2003, 9:21 PM
    package com.gumbtech.ui;
    import java.awt.Color;
    import javax.swing.JList;
    import javax.swing.DefaultListCellRenderer;
    * usage:
    * String[] data = {"one", "two", "free", "four"};
    * JList dataList = new JList(data);
    * dataList.setCellRenderer(new MyCustomCellRenderer());
    * @author  I think this structure and the comments are a variation of
    *          David Flanagans example from Java Examples 2. (O'Reilly)
    public class MyCustomCellRenderer extends DefaultListCellRenderer {
      private static Color selectedColor = new Color(240,99,99);
      private static Color selectedBG = new Color(163,186,168);
      public MyCustomCellRenderer() {
      public MyCustomCellRenderer(Color selectedColor) {
        this.selectedColor = selectedColor;
       * This is the only method defined by ListCellRenderer.
       * We just reconfigure the Jlabel each time we're called.
      public java.awt.Component getListCellRendererComponent(
             JList list,
             Object value,   // value to display
             int index,      // cell index
             boolean iss,    // is the cell selected
             boolean chf)    // the list and the cell have the focus
         * The DefaultListCellRenderer class will take care of
         * the JLabels text property, it's foreground and background
         * colors, and so on.
        super.getListCellRendererComponent(list, value, index, iss, chf);
         * We additionally set the JLabels color properties here,
         * but only for the cell that is currently selected (highlighted).
        if(iss) {
          setForeground(selectedColor);
          this.setBackground(selectedBG);
        return this;

  • The problem in using JComboBox. Need Help!

    HI,
    I am programming to make an address bar as IE? Now, I am using JComboBox as the address bar. I also read the article of "how to use JComboBox" in sun tutorial.
    The problem is I cann't make the icon and text together in the address bar. As in the tutorial article, I can make it there since the JComboBox is uneditable.
    My case is I still want the icon in the JTextField of JComboBox, but I am still able to input address into this JTextField as well.
    Is it able to add a JLabel into JTextField first, and then be able to input text exactly after this icon, then my problem is solved.
    Thanks!
    Feng

    Hi Feng,
    My suggestion is that you try out the JComboBox methods setEditor() and setRenderer(). They allow you to specify custom components that will be used to show the combo box items. You'll need to do a bit of work, but you'll probably be able to provide a custom component that will display your icon.
    Hope that helps!
    Shannon Hickey (Swing Team)

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • How to use TableModel ???????

    I'm new to java, please help me
    i have this problem. When i choose the item in the combo box for the first time, i get the selected table, but when i choose the other item in combo box, the previous table is still remain in the panel instead of the new one.
    String sList[] =
    "InformationTechnology",
    "Account",
    "Investment"
    combo = new JComboBox();
    combo.setBounds( 220, 35, 260, 25 );
    panel3.add( combo );
    combo.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
    System.out.println("Selected Item = "+(String)combo.getSelectedItem());
    TableDisplay((String)combo.getSelectedItem());=
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    scroller = new JScrollPane(table);
    scroller.setBounds( 220, 70, 260, 100 );
    panel3.add(scroller);
    table.validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    just now got a 'guru' told me to use TableModel, but i search the web already but still stuck in the middle, because i don't know how to use TableModel..............

    liml,
    You code shows table instantiation as:
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    Check that it's in scope, say at class-level, for subsequent manipulations.
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Hello can any body help me to add color to my shape using jcombobox

    please how can i fill color to my shape and change the line color of my shape using jcombobox here is my code
    //package paint;
    * PaintShapesDemo.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PaintShapesDemo extends JFrame implements ActionListener
    final private int RECT =1 ;
    final private int CIRCLE = 2;
    final private int POLY = 3 ;
    final private int ELLI = 4 ;
    final private int TRAN = 5 ;
    private int shape;
    JLabel Lcolor;
    JLabel Fcolor;
    JLabel headlebel,linecolorlabel,fillcolorlabel,labeldisplay;
    JButton recbutton,cirbutton,polygonbutton,ellipsebutton;
    JComboBox linecolor,fillcolor;
    private ButtonGroup grShapes = new ButtonGroup();
    private JPanel shapeSelectionPanel = new JPanel(new FlowLayout());
    public PaintShapesDemo()
    super("HAKIMADE");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBackground(Color.white);
    setSize(800,600);
    setLocationRelativeTo(null);
    recbutton = new JButton("CIRCLE");
    cirbutton = new JButton("ROUNDRECT");
    polygonbutton = new JButton("ELLIPSE");
    ellipsebutton = new JButton("RECTANGLE");
    JPanel TP=new JPanel();
    TP.setLayout(new FlowLayout(FlowLayout.CENTER));
    TP.add(new JLabel("MY PAINT APPLICATION."));
    JPanel panel1=new JPanel();
    panel1.setLayout(new FlowLayout(FlowLayout.CENTER,10,40));
    panel1.add(recbutton);
    panel1.add(cirbutton);
    panel1.add(polygonbutton);
    panel1.add(ellipsebutton);
    JPanel TP1=new JPanel();
    TP1.setLayout(new BorderLayout());
    TP1.add(TP,BorderLayout.NORTH);
    TP1.add(panel1,BorderLayout.CENTER);
    JPanel panel2=new JPanel();
    panel2.setLayout(new FlowLayout(FlowLayout.CENTER,30,2));
    Lcolor = new JLabel("SELECT LINE COLOR");
    Fcolor = new JLabel("SELECT FILL COLOR");
    panel2.add(Lcolor);
    panel2.add(Fcolor);
    JPanel panel3=new JPanel();
    panel3.setLayout(new FlowLayout(FlowLayout.CENTER,30,2));
    linecolor = new JComboBox();
    linecolor.addItem("Choose the color");
    linecolor.addItem("Gray");
    linecolor.addItem("Orange");
    linecolor.addItem("Magenta");
    linecolor.addItem("Dark Gray");
    fillcolor = new JComboBox();
    fillcolor.addItem("Choose the color");
    fillcolor.addItem("RED");
    fillcolor.addItem("BLUE");
    fillcolor.addItem("BLACK");
    fillcolor.addItem("YELLOW");
    panel3.add(linecolor);
    panel3.add(fillcolor);
    JPanel panel4=new JPanel();
    panel4.setLayout(new BorderLayout());
    panel4.add(panel2,BorderLayout.NORTH);
    panel4.add(panel3,BorderLayout.CENTER);
    shapeSelectionPanel.add(TP1);
    shapeSelectionPanel.add(panel4);
    shapeSelectionPanel.setBackground(Color.green);
    shapeSelectionPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    shapeSelectionPanel.setPreferredSize(new Dimension(110, 100));
    add(shapeSelectionPanel, BorderLayout.NORTH);
    add(new DrawingPanel());
    recbutton.addActionListener(this);
    cirbutton.addActionListener(this);
    polygonbutton.addActionListener(this);
    ellipsebutton.addActionListener(this);
    public static void main(final String args[])
    new PaintShapesDemo().setVisible(true);
    public void actionPerformed(final ActionEvent e)
    shape = CIRCLE;
    if(e.getSource() == cirbutton)
    shape = RECT;
    if(e.getSource() == recbutton)
    shape = POLY;
    if(e.getSource() == polygonbutton)
    shape = ELLI;
    if(e.getSource() == ellipsebutton)
    shape = TRAN;
    class DrawingPanel extends JPanel
    private Image img;
    private Graphics2D g2;
    public DrawingPanel()
    addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){drawShape(e.getX(), e.getY());}});
    public void paintComponent(final Graphics g)
    if(img == null)
    img = createImage(getWidth(), getHeight());
    g2 = (Graphics2D)img.getGraphics();
    g.drawImage(img,0,0,null);
    private void drawShape(final int x, final int y)
    switch (shape)
    case POLY: g2.drawOval(x,y,100,100);break;
    case ELLI: g2.drawOval(x,y,100,50);break;
    case RECT: g2.drawRoundRect(x,y,100, 70, 20, 20);break;
    case CIRCLE: g2.drawRect(x,y,100,80);break;
    case TRAN: g2.drawRect(x,y,100,80);
    repaint();
    }

    use CODE tags to post source code
    read selected color from combobox and set colors Or declare two Strings lineColor and fillColor and set these variables on change of combo by adding ItemListener to the combo. and use that varables to set colors ..
    Refer:
    http://www.java2s.com/Code/Java/2D-Graphics-GUI/Arcdemonstrationscalemoverotatesheer.htm

  • Using JComboBox(Object[] )

    Hi,
    Im using JComboBox(Object[] ) constructor , but the problem is how to retrieve the object selected , the solution
    i use is to define the toString() method in the class of this object to select an the
    attribute returned by this method will be the label displayed in the combo this solution
    is good .
    My question is : there is any other solution to do this without defining the toString() method.
    Thanks for all the replys

    What kind of data are you passing into the ComboBox?
    If the objects are just Strings then you should you a String[ ] instead of an object array.
    If the objects are complex, then you could define your own cellrenderer to display the values of the objects just how you want them, that way you don't have override the toString() method of all the objects in the array. The renderer can parse the objects and then convert the values to their necessary string representation and then display them.
    ICE

  • How to use one email adress for multiple recipients

    Hello,
    I'd like to know how to use one email adress for multiple recipients. 
    this would be very useful or projects. for example;
    if i send one mail to [email protected], all people in this project get an email.
    I will add the people in this project myself. 
    I know it is possible, but I don't know how to do it ;-)
    please help me! 

    Hope this help.
    _http://technet.microsoft.com/en-us/library/cc164331(v=exchg.65) .aspx

  • Can't figure out how to use home sharing

    Since the latest couple iTunes updates, my family and I can not figure out how to use home sharing. Everyone in our household has their own iTunes, and for a long time we would just share our music through home sharing. But with the updates, so much has changed that we can no longer figure out how to use it.
    I have a lot of purchased albums on another laptop in the house, that im trying to move it all over to my own iTunes, and I have spent a long time searching the internet, and everything. And I just can't figure out how to do it. So.... how does it work now? I would really like to get these albums from my moms iTunes, onto mine. I would hate to have to buy them all over again.
    If anyone is able to help me out here, that would be great! Thanks!

    The problem im having is that after I am in another library through home sharing, I can't figure out how to select an album and import it to my library. They used to have it set up so that you just highlight all of the songs you want, and then all you had to do was click import. Now I don't even see an import button, or anything else like it. So im lost... I don't know if it's something im doing wrong, or if our home sharing system just isn't working properly.
    Thanks for the help.

  • How to use the same POWL query for multiple users

    Hello,
    I have defined a POWL query which executes properly. But if I map the same POWL query to 2 portal users and the 2 portal users try to access the same page simultaneously then it gives an error message to one of the users that
    "Query 'ABC' is already open in another session."
    where 'ABC' is the query name.
    Can you please tell me how to use the same POWL query for multiple users ?
    A fast reply would be highly appreciated.
    Thanks and Regards,
    Sandhya

    Batch processing usually involves using actions you have recorded.  In Action you can insert Path that can be used during processing documents.  Path have some size so you may want to only process document that have the same size.  Look in the Actions Palette fly-out menu for insert path.  It inserts|records the current document work path into the action being worked on and when the action is played it inserts the path into the document as the current work path..

  • How to use airport time capsule with multiple computers?

    I'm sure there are some thread about this but i couldn't find it... so sorry for that but hear me out! =)
    I bought the AirPort Time Capsule to back up my MBP
    And so i did.
    then i thought "let give this one a fresh start" so i erased all of it with the disk utility and re-installed the MBP from the recovery disk.
    I dont want all of the stuff i backed up just a few files and some pictures so i brought that back.. so far so good.
    Now i want to do a new back up of my MBP so i open time machine settings, pick the drive on the time capsule and then "Choose" i wait for the beck up to begin, and then it fails.  It says (sorry for my bad english, im swedish haha) "the mount /Volume/Data-1/StiflersMBP.sparsebundle is already in use for back up.
    this is what i want:
    i want the "StiflersMBP.sparsebundle" to just be so i can get some stuf when i need them. it's never to be erased.
    i want to make a new back up of my MBP as if it's a second computer...
    so guys and girls, what is the easiest and best solution?
    Best regards!

    TM does not work like that.
    If you want files to use later.. do not use TM.
    Or do not use TM to the same location. Plug a USB drive into the computer and use that as the target for the permanent backup.
    Read some details of how TM works so you understand what it will do.
    http://pondini.org/TM/Works.html
    Use a clone or different software for a permanent backup.
    http://pondini.org/TM/Clones.html
    How to use TC
    http://pondini.org/TM/Time_Capsule.html
    This is helpful.. particularly Q3.
    Why you don't want to use TM.
    Q20 here. http://pondini.org/TM/FAQ.html

  • How to use multiple ipods on one account

    I have an Ipod classic and just bought my sons two nano's how do I use these on the same account without changing my account info?

    Take a look here:
    How to use multiple iPods with one computer
    Forum Tip: Since you're new here, you've probably not discovered the Search feature available on every Discussions page, but next time, it might save you time (and everyone else from having to answer the same question multiple times) if you search a couple of ways for a topic, both in the relevant forums, in the User Tips Library and in the Apple Knowledge Base before you post a question.
    Regards.

  • How to use a Table View in AppleScriptObjC

    How can I use a table view and add data to it? And how can I display a button cell and image cell in the table? Thanks.

    Hi all,
    Actually i need some more clarification. How to use the same select statement, if i've to use the tabname in the where clause too?
    for ex : select * from (tab_name) where....?
    Can we do inner join on such select statements? If so how?
    Thanks & Regards,
    Mallik.

  • How to use '|' delimited as seprator in GUI_DOWNLOAD ? Plz suggest me ,,

    how to use '|' delimited as seprator in GUI_DOWNLOAD ? Plz suggest me ,,
    i want the output should be seprated by '|' delimited when i download the file.

    Hi,
    We will pass the seperator to the WRITE_FIELD_SEPARATOR parameter as
    CALL FUNCTION 'GUI_DOWNLOAD'
    EXPORTING
    filename = v_file
    write_field_separator = '|'
    TABLES
    data_tab = itab[] . "Our internal talbe filled with data
    Re: Why Function GUI_DOWNLOAD can create XML file but not a flat file?
    Award points if useful
    Thanks,
    Ravee...

Maybe you are looking for