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

Similar Messages

  • 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;

  • 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();
    }

  • 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 add rows using DefaultTableModel?

    I'm trying to figure out the ins-and-outs of creating a dynamic table.
    I looked for a tutorial, but none of the example programs I found dealt with my particular issue, nor did they explain anything.
    For instance, most of the examples looked like this:
            table = new JTable();
            defaultModel = new DefaultTableModel(10,5);
            setModel(defaultModel);But that doesn't work for me -- I'm creating a class that EXTENDS DefaultTableModel, and so if I want to send in parameters, I have a problem.
              public MyTableModel() {
                            super(data, columnNames);
                    ...The above code complains that "you can't access data or columnNames until you call super()!"
    But I've seen plenty of example code that DOES send in parameters to super(). How do they get away with that? Is it because they are parameters to the constructor, whereas private/public members of the class are somehow different?
    I thought a variable is a variable -- why is one allowed but not the other?
    Lastly, I'm trying to figure out, practically speaking, how to load a database with X items, and be able to add rows later. Does that mean I need to use a vector for my data instead of Object[][]?
    I've seen BOTH AbstractDataModel and DefaultTableModel used with dynamic tables -- is there any difference between them as far as dynamic tables are concerned?
    I was under the impression that I needed to "switch" from ADM to DTM if I wanted to be able to add rows to my table at runtime.
    Here are some references to previous discussions I found/participated in on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5224966
    http://forum.java.sun.com/thread.jspa?threadID=439141&start=0&tstart=0
    Thanks in advance for any help,
    Matthew

    -> I'm creating a class that EXTENDS DefaultTableModel, and so if I want to send in parameters, I have a problem
    Well, you would pass in the data and columnNames as parameter when you create your table model.
    -> Lastly, I'm trying to figure out, practically speaking, how to load a
    -> database with X items, and be able to add rows later. Does that
    -> mean I need to use a vector for my data instead of Object[][]?
    You just said you extended DefaultTableModel. Well you don't need to do anything it already manages the data for you. You just use the methods provided to update and change the data.
    -> I've seen BOTH AbstractDataModel and DefaultTableModel used with dynamic tables
    No you haven't. You really don't understand what an AbstractDataModel is do you? Its nothing. You can't use it. It doesn't have any storage for the data, and since there is no data storage you can't access the data or change it. You can't even create an AbstractTableModel. Read your Java text on what an Abstract class it.
    The DefaultTableModel extends the AbstractTableModel to provide data storage and ways to get the data and change the data. It notifies the table when any change is made to the data so the table can repaint itself.
    -> How to add rows using DefaultTableModel?
    Finally, the DTM provides methods that make the model dynamic. Methods for adding and removing rows or adding and removing columns. Read the API for more information.
    If you still don't understand how how the methods work then search the forum for examples that use the methods you don't understand. I've posted an example the uses the methods required to add rows or columns.

  • 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 can 2 people use itunes in the same household? we both have iphone 4 and separate id but the same itunes? pleasehelp

           how can two people use itunes in the same household? i had a iphone before so alreday had an itunes account now me and my husband have upgraded and we now both have them. he has set up a username and i have mine yet when he logs in he seems to just get my account? please help

    Decide which iPhone will be keeping the current iCloud account.  On the one that will be changing accounts, if you have any photos in photo stream that are not in your camera roll or backed up somewhere else save these to your camera roll by opening the photo stream album in the thumbnail view, tapping Edit, then tap all the photos you want to save, tap Share and tap Save to Camera Roll.  If you are syncing Notes with iCloud, you'll also have to email your notes to yourself so they can be recreated in the new account as they cannot be migrated.
    Once this is done, go to Settings>iCloud, scroll to the bottom and tap Delete Account.  (This will only delete the account from this phone, not from iCloud.  The phone that will be keeping the account will not be effected by this.)  When prompted about what to do with the iCloud data, be sure to select Keep On My iPhone.  Next, set up a new iCloud account using a different Apple ID (if you don't have one, tap Get a Free Apple ID at the bottom).  Then turn iCloud data syncing for contacts, etc. back to On, and when prompted about merging with iCloud, choose Merge.  This will upload the data to the new account.
    Finally, to un-merge the data you will then have to go to icloud.com on your computer and sign into each iCloud account separately and manually delete the data you don't want (such as deleting your wife's data from your account, and vice versa).

  • How can I stop using my primary Apple ID (Gmail) but leave my secondary Apple ID (icloud) as primary ond only ONE?

    Good afternoon friends.
    Please help me and tell how can I stop using my primary Apple ID (Gmail) but leave my secondary Apple ID (icloud) as primary ond only ONE?
    I started using Apple ID in 2011 when iCloud was not exist and was forced to use non-apple e-mail adress as primary ID.
    So I used GMail mailbox.
    When iCloud was started I created my account but unfortunatelly can't remove this Gmail address from my Apple ID and replace it with icloud mail address.
    I was VERY dissapointed because I don't want to use "outside" mailbox to get letters from Apple and ny ID.
    In fact I see the Apple old users and fans discrimination.
    When creating new user accounts are free to create a box on the iCloud mail and use it as a primary ID, and the only ONE.
    At the same time the old user is obliged to keep third-party mail box like Gmail etc. as the primary and can not get such an opportunity, as a new user
    This is extremely inconvenient and a VERY strange logical.
    For example, now I want to stop using this mailbox on Gmail but I can not do that because in this case I lose access to my ID, or run the risk that someone in the future will create a box with the same name on Gmail (when name will be free and available) and will automatically get access to my accounts on Apple and to my Apple ID.
    Now, to avoid this, your team, I offer the only way out: ID, create anew.
    Of course it's possible, but then:
    - I lose all my purchases for 3 years and will be forced to make them again and pay money for the second time for my purchases
    - Lose access to the familiar iCloud e-mail address who now serves as secondary ID because this e-mail address is almost no longer available and will never be released in future.
    And now answer me for ONLY TWO questions:
    - WHERE IS LOGIC?
    - WHAT ABOUT TO BE FRIENDLY FOR YOUR USERS AND FANS?
    Thank you!
    Hopefully for your GOOD answers.

    You cannot make your @icloud.com address the login address for the ID. However you can change your ID, currently a Gmail one, to any other functioning non-Apple email address. The Gmail address would then no longer access your account, and so even if someone were to obtain posession of it (is that even possible) it wouldn't allow them to get into your account.
    If you want to change your ID to another email address please follow the procedure outlined below, particularly noting the first step.
    Firstly, if you have 'Find My iPhone/iPad/iMac' enabled on any of your devices, turn it off.
    Create a new email address, for example  at Yahoo or Gmail, or anywhere convenient (or you can use an existing address as long as it has never been associated with an Apple ID).
    Go to http://appleid.apple.com and click 'Manage your Apple ID'. Sign in with the current ID.
    Where it says 'Apple ID and primary email address' and gives your current ID email address, click 'edit'.
    Enter your new address and click 'Save changes'.
    Now you will need to go to each of your devices and sign out in System Preferences (or Settings)>iCloud - 'Sign out' on a Mac, 'Delete this account' on an iOS device (this will not delete the account from the server).
    Then sign back in with your new ID. Your iCloud data will disappear from your devices when you sign out, but reappear when you sign back in.
    I re-iterate: before you start, turn off 'Find My Mac' (or whatever) or you will need the services of Support.

  • How to round numbers using javascript in Adobe Acrobat Pro?

    How to round numbers using java script in Adobe Acrobat Pro?
    For example:
    1.2 becomes 1.0
    1.7 becomes 2.0
    Thank you.

    Assuming you've already set the field to a Number format category and limited it to one digit to the right of the decimal, you can use the following custom Validate script:
    // Custom Validate script
    event.value = Math.round(event.value);
    More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/roun d

  • I use to use a windows computer for iTunes ,now I do not own one ,I only have my iPad mini and my iPod ,how do I sync iTunes ,

    How to sync iTunes when I do not have computer I once use to use iTunes with ,I only have iPod touch ,an when I goto sync it says plug in to old computer I use to use

    Have a read of this thread:
    https://discussions.apple.com/message/19649111#19649111

  • HT203658 How to sign in using the Apple ID that I initially used to set up the computer?

    How to sign in using the Apple ID that I initially used to set up the computer? I cant update my iPhoto and download pictures from Iphone :((
    I updated ios on my MacBook Air to Yosemite, since then I had to update also iPhoto, as it was not compatible with Yosemite. When trying to update it I received this alert "These apps cannot be accepted by your Apple ID. These have already been assigned to another Apple ID." And the solution wud be to sign in using my initial Apple ID, but Im not aware of having one or changing it. I have many Mac devices so I at one point sing in to my Air with another ID not even noticing it and have it since the moment I found out the alert. Can anyone help me with this, please? And also, where are my pictures stored in my Air? Is there some folder, cuz Im used to Windows and Mac is totally new and not really clear to me for now. I need to download pictures from my iPhone and iPhoto seems to be the only way??
    thanks
    elen

    How to sign in using the Apple ID that I initially used to set up the computer? I cant update my iPhoto and download pictures from Iphone :((
    Try to remember any AppleID you ever may have used.
    In the AppStore Application go to the "Store" menu.
    It will show you the AppleiD You are currently using (in the last menu entry "View my account ....".
    Use the "Sign out" command and sign in with any AppleID you ever used, ten check the "Purchases" tab of the App Store, if that will show the bundled apps.
    And also, where are my pictures stored in my Air?
    If you have used iPhoto to download your pictures, the photos will be stored in the iPhoto Library, a package, that is stored in the folder "Pictures" in your Home folder.
    Terence Devlin has written some very useful user tips, that describe the iPhoto Library:  See the links below:
    iPhoto and File Management
    How to Access Files in iPhoto
    Exporting From iPhoto

  • My husband and I share a new PC.  We have different music tastes and each have an iphone.  How can we both use our one computer and one itunes program with separate music libraries and separate iphones?

    My husband and I share a new PC.  We have different music tastes and each have an iphone.  How can we both use our one computer and one itunes program with separate music libraries and separate iphones?

    Each device only syncs waht you select.
    Select only what you want for each phone.

  • I have ad Apple ID on my iPad , when I use the apple on my iPhone for the first time, I put in my Apple ID for the iPad, didn't work. Need to create a new one. Why? How can I just use my iPad ID on my iPhone?

    I have ad Apple ID on my iPad , when I use the apple on my iPhone for the first time, I put in my Apple ID for the iPad, didn't work. Need to create a new one. Why? How can I just use my iPad ID on my iPhone?

    Hi kamfong,
    Went to Settings where?
    If you want to use your exisiting Apple ID on your iPad, you need to:
    1.     Go to Settings>iTunes & App Store and sign out the new ID, and then sign on the old one
    2.     Go to Settings>iCloud, scroll to the bottom and delete the iCloud account, and the sign back onto iCloud using the old ID
    You still have not indindated why you are saying that using your old ID originally "didn't work". What do you mean by that? Did you get some sort of error when you tried to sign on with your exisiting Apple ID?
    Cheers,
    GB

  • I have a $10 gift card balance on my Apple ID but when I try to rent a movie it wants me to use my debit card. How can Make it use the iTunes credit?

    I have a $10 gift card balance on my Apple ID but when I try to rent a movie it wants me to use my debit card. How can Make it use the iTunes credit?

    Hi ...
    Select None for payment method > iTunes Store: Changing account information
    Be aware, an auto renewing subsciption by require a credit card.

Maybe you are looking for