Filling a jtable with an array of Portfolio objects

I have created a class Portfolio and want to put an array of portfolio objects in a Jtable.
I created a tablePortfolioClass based on the AbstratTableModel and
changed the classical 2 dimensional data array into a one dimensional arry of portfolio objects.
The databaselayer correctly fills the Portfolio but does not display it inthe table...
what am I doing wrong ?
package DBpackage;
import java.lang.String;
public class Portfolio
public Portfolio()
public Portfolio(String sE)
sEcode=sE;
//here are normally set and getmethods that I left out
private String sEcode;
private double dQuantity;
private double dAvgPrice;
private double dPrice;
private double dExchRate;
private double dReturn;
private String sDescr;
private double dPerc;
private double dTotal;
=============================================================
package DBpackage;
import javax.swing.table.AbstractTableModel;
class tablePortfolioClass extends AbstractTableModel
Portfolio[]data=new Portfolio[50];
final String[] columnNames={"Ecode","Description","Quantity","Price", "Avg","%","Total","Return"};
public void tablePortfolioClass (int nrofRows)
iRows=nrofRows;
public void tablePortfolioClass(Portfolio[] pp)
data=pp;
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row];
public void setValueAt(Portfolio value, int row, int col) {
data[row] = value;
fireTableCellUpdated(row, col);
private int iRows;
private int iCols=4;
=============================================================
this is what is done in the frame
Portfolio [] pf=new Portfolio[50];
tablePortfolioClass pp=new tablePortfolioClass();
//tablePortfolioClass pp=new tablePortfolioClass(pf); this one does not compile
JTable grdPP=new JTable(pp);
grdPP.setPreferredScrollableViewportSize(new Dimension(200,200));
JScrollPane jscrollPanePP=new JScrollPane(grdPP);
all more traditional implementations of the jtable work without any problem...
anyone ?

Your getValueAt() method should return the actual value you want to display in the table at the given row and column. Right now, it returns the whole Portfolio object. How is the table supposed to render a Portfolio object?
Something more like this would make more sensepublic Object getValueAt(int row, int col)
  switch (col) {
  case 0:
    return data[row].getEcode();
  case 1:
    return data[row].getDescr();
  case 7:
    return new Double(data[row].getReturn());
}The same can be said for your setValueAt() method. It should set the individual attributes of the Portfolio object at the given row rather than changing the whole object.

Similar Messages

  • Hi, i'm having trouble in filling a jtable with data

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

  • Updating a JTable with an array of values

    Ther is a constructor that allows for the cretion of the table with an iniital array of values. However subsequent updates of blocks of data- say you received an array of updated data form a database- reuiqre you to update ince cell at a time. Is ther any way fo updating a whole block at once. I should point out that I am asking this because I am using JTables in the Matlab programming environment where arrays are the basic unit and looping through is a comparatively slow process

    Yes, you can extend the AbstractTableModel and write a method for updating a whole block.
    lets say you've got a Vector with Float[] arrays as elements to hold a 2D array of Float. The you could write:
          TableModel dataModel = new AbstractTableModel() {
                public int getColumnCount() { return col_names.size(); }
                public int getRowCount() { return data.size();}
                public Object getValueAt(int row, int col) {
                   return ((Float)((Float[])data.elementAt(row))[col]).toString();
                public String getColumnName(int col) {
                 return ((String)col_names.elementAt(col));
                public Class getColumnClass(int col) {
                 return String.class;
                public boolean isCellEditable(int row, int col) {
                  return true;
                public void setValueAt(Object aValue, int row, int col) {
                   try {
                     Float fv = Float.valueOf((String)aValue);
                    ((Float[])data.elementAt(row))[col] = fv;
                   } catch (Exception ex) {
                public void setBlock(Float block[][], int row, int col) {
                   // copy the Arrays with System.arrayCopy into data
          };PS: I don't know, if the above is correct written, havn't test this. But I hope you can recognize the idea behind it.
    wami

  • JTable: how to "synchronize" (and update) with an array ?

    Hello.
    I am new to the Swing and I have been googling to find a solution for my problem, but I've spent too much time and found nothing. Please give me some advice.
    So: I have an array of data and a JTable. The array is constantly being changed and I would like to update the JTable with every change in the array.
    Thank you so much for yr help.

    So here I am with an as-simple-as-possible example of my problem.
    Just run it, everything is in this class.
    And you'll have a table with 10 rows with 0 in every row. Every 2 seconds one line should change, but it doesn't, only if you resize the frame, or click in a cell the numbers in the cells will change.
    Q: how to change it without resizing or clicking into the table ?
    package MainFrame;
    import java.awt.BorderLayout;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.SwingUtilities;
    import javax.swing.table.AbstractTableModel;
    class NewJFrame extends javax.swing.JFrame {
         private static JTable jTable;
         public static void main(String[] args) throws Exception {
              SwingUtilities.invokeAndWait(new Runnable() {
                   public void run() {
                        NewJFrame inst = new NewJFrame();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
              Generator gen = new Generator(jTable);
         public NewJFrame() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                   jTable = new JTable(new MyTableModel());
                   getContentPane().add(jTable, BorderLayout.CENTER);
                   pack();
                   this.setSize(399, 263);
              } catch (Exception e) {
                   e.printStackTrace();
    class Generator extends Thread {
         private int[] array = new int[10];
         JTable table;
         public Generator(JTable table) {
              array = new int[10];
              this.table = table;
              this.start();
         public void run() {
              super.run();
              for (int i = 0; i < 10; i++) {
                   array[i] = i + 200;
                   table.getModel().setValueAt(i, i, 0);
                   try {
                        Thread.sleep(2000);
                   } catch (InterruptedException e) {
    class MyTableModel extends AbstractTableModel {
         private int[] array = new int[10];
         public int getColumnCount() {
              return 1;
         public int getRowCount() {
              return array.length;
         public Object getValueAt(int arg0, int arg1) {
              return array[arg0];
         public void setValueAt(Object value, int rowIndex, int columnIndex) {
              array[rowIndex] = ((Integer) value).intValue();
    }Thank you so so much my man.

  • How can I update JTable with new Object[][]

    Hallo, I have got a problem. I want to update my Jtable with new Values,
    with
    setValueAt(Object aValue, int row, int column)
    i can only update one Object.
    Is it possible to update All Objects "Object[][]"??? in a whole Table
    after I clicked a Button???

    Hi,
    AbstractTableModel's method setValueAt(Object aValue, int row, int column)
    is not the way to fill values into a table. It is the way the table returns the changed values to you after the user has entered something. This is a very common misconception, probably because the method names are so confusing.
    The table model uses getValueAt (int row , int column)
    to fill in its rows and columns.
    If you extend AbstractTableModel to make this method fill in the correct values from you data array. then, when you wish to update the whole table, you can
    1) Put new values in the data array
    2) fireTableValuesChanged
    this will cause the table model to call getValueAt for every row and column.
    good luck.

  • How to populate a jsf table with an array?

    I have a JSF project where I'm using a table and I would like to populate that table with some custom information without using a database. I'm trying to write my own data provider. I was wondering if anyone knows how to populate a jsf table using an array. Any help would be appreciated. Thanks.

    Hey thanks for replying. I'm not quite sure what you mean, but I am using a woodstock table in Netbeans. I would love to skip writing the data provider since I've never done that before, but I'm not sure how I would go about populating the table with a regular List or Model. I have populated a JTable with my own model, but never a woodstock table. They don't seem to work the same way. Thanks for the help. I've spent hours trying to figure this out.

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • Problem Filling and Selecting with Paths.jsx

    I have copied Paths.jsx from the Adobe Photoshop CS5 Javascript Scripting Reference, p. 141.  It works OK.  It makes a path that is the outline of an ice cream cone and strokes it with the current foreground color.
    I then tried to fill the path and that does not work.  I have tried 3 methods using the following additional code and changing the appropriate false's to true:
    // Fill the path
    fillColor = new SolidColor
    fillColor.rgb.red = 255
    fillColor.rgb.green = 0
    fillColor.rgb.blue = 0
    try {
       if(false) {
             // This works and gives a gray fill that is neither the
                  // foreground nor background color
         // Only the ice cream part of the cone is selected and filled
                myPathItem.fillPath()
       } else if(false) {
         // With a color specified, it doesn't work
                  myPathItem.fillPath(fillColor)
           } else if(true) {
         // This makes a selection of the PathItem, selects it and fills it
         // Only the ice cream part of the cone is selected and filled
                  myPathItem.makeSelection(0, false, SelectionType.REPLACE)
                   selRef = app.activeDocument.selection;
                  selRef.fill(fillColor, ColorBlendMode.NORMAL)
    } catch(ex) {
            msg = "Error filling path:\n" + ex.message
            alert(msg, "Exception", true);
    They do as the comments say.  None of them does what I would expect.  For the second way, the error message is:
    General Photoshop error occurred.  This functionality may not be available in this version of Photoshop
    - Could not complete the command because of a program error.
    I do not understand why only the      ice cream part of the cone is filled or selected (the third array).  I can manually      make a selection from the Path in PS and it also only selects the      ice cream part.  All of the lines are stroked.  Only the top part is      filled or selected.
    Why does fillPath not work?
    I can supply the whole script if necessary.  I am an experienced programmer but new to Photoshop scripting.  Is this a bug or am I doing something wrong?
    Thanks for any help.

    This is the whole script:
    // Paths.jsx
    #target photoshop
    // Save the current preferences
    var startRulerUnits = app.preferences.rulerUnits
    var startTypeUnits = app.preferences.typeUnits
    var startDisplayDialogs = app.displayDialogs
    // Set Adobe Photoshop CS5 to use pixels and display no dialogs
    app.preferences.rulerUnits = Units.PIXELS
    app.preferences.typeUnits = TypeUnits.PIXELS
    app.displayDialogs = DialogModes.NO
    // First close all the open documents
    while (app.documents.length) {
    app.activeDocument.close()
    // Create a document to work with
    var docRef = app.documents.add(5000, 7000, 72, "Simple Line")
    // line 1--it’s a straight line so the coordinates for anchor, left, and right
    // for each point have the same coordinates
    var lineArray = new Array()
    lineArray[0] = new PathPointInfo
    lineArray[0].kind = PointKind.CORNERPOINT
    lineArray[0].anchor = Array(100, 100)
    lineArray[0].leftDirection = lineArray[0].anchor
    lineArray[0].rightDirection = lineArray[0].anchor
    lineArray[1] = new PathPointInfo
    lineArray[1].kind = PointKind.CORNERPOINT
    lineArray[1].anchor = Array(150, 200)
    lineArray[1].leftDirection = lineArray[1].anchor
    lineArray[1].rightDirection = lineArray[1].anchor
    var lineSubPathArray = new Array()
    lineSubPathArray[0] = new SubPathInfo()
    lineSubPathArray[0].operation = ShapeOperation.SHAPEXOR
    lineSubPathArray[0].closed = false
    lineSubPathArray[0].entireSubPath = lineArray
    // line 2
    var lineArray2 = new Array()
    lineArray2[0] = new PathPointInfo
    lineArray2[0].kind = PointKind.CORNERPOINT
    lineArray2[0].anchor = Array(150, 200)
    lineArray2[0].leftDirection = lineArray2[0].anchor
    lineArray2[0].rightDirection = lineArray2[0].anchor
    lineArray2[1] = new PathPointInfo
    lineArray2[1].kind = PointKind.CORNERPOINT
    lineArray2[1].anchor = Array(200, 100)
    lineArray2[1].leftDirection = lineArray2[1].anchor
    lineArray2[1].rightDirection = lineArray2[1].anchor
    lineSubPathArray[1] = new SubPathInfo()
    lineSubPathArray[1].operation = ShapeOperation.SHAPEXOR
    lineSubPathArray[1].closed = false
    lineSubPathArray[1].entireSubPath = lineArray2
    // Ice cream curve
    // It’s a curved line, so there are 3 points, not 2
    // coordinates for the middle point (lineArray3[1]) are different.
    // The left direction is positioned "above" the anchor on the screen.
    // The right direction is positioned "below" the anchor
    // You can change the coordinates for these points to see
    // how the curve works...
    var lineArray3 = new Array()
    lineArray3[0] = new PathPointInfo
    lineArray3[0].kind = PointKind.CORNERPOINT
    lineArray3[0].anchor = Array(200, 100)
    lineArray3[0].leftDirection = lineArray3[0].anchor
    lineArray3[0].rightDirection = lineArray3[0].anchor
    lineArray3[1] = new PathPointInfo
    lineArray3[1].kind = PointKind.CORNERPOINT
    lineArray3[1].anchor = Array(150, 50)
    lineArray3[1].leftDirection = Array(100, 50)
    lineArray3[1].rightDirection = Array(200, 50)
    lineArray3[2] = new PathPointInfo
    lineArray3[2].kind = PointKind.CORNERPOINT
    lineArray3[2].anchor = Array(100, 100)
    lineArray3[2].leftDirection = lineArray3[2].anchor
    lineArray3[2].rightDirection = lineArray3[2].anchor
    lineSubPathArray[2] = new SubPathInfo()
    lineSubPathArray[2].operation = ShapeOperation.SHAPEXOR
    lineSubPathArray[2].closed = false
    lineSubPathArray[2].entireSubPath = lineArray3
    // Create the path item
    var myPathItem = docRef.pathItems.add("A Line", lineSubPathArray)
    // Stroke it so we can see something
    myPathItem.strokePath(ToolType.BRUSH)
    // Fill the path
    fillColor = new SolidColor
    fillColor.rgb.red = 255
    fillColor.rgb.green = 0
    fillColor.rgb.blue = 0
    try {
        if(false) {
            // This works and gives a gray fill that is neither the
            // foreground nor background color
            // Only the ice cream part of the cone is selected and filled
            myPathItem.fillPath()
        } else if(false) {
            // With a color specified, it doesn't work
            myPathItem.fillPath(fillColor)
        } else if(true) {
            // This makes a selection of the PathItem, selects it and fills it
            // Only the ice cream part of the cone is selected and filled
            myPathItem.makeSelection(0, false, SelectionType.REPLACE)
            selRef = app.activeDocument.selection;
            selRef.fill(fillColor, ColorBlendMode.NORMAL)
    } catch(ex) {
        msg = "Error filling path:\n" + ex.message
        alert(msg, "Exception", true);
    // Reset the application preferences
    preferences.rulerUnits = startRulerUnits
    preferences.typeUnits = startTypeUnits
    displayDialogs = startDisplayDialogs

  • Can we create JTable with multiple rows with varying number of columns ?

    Hi All,
    I came across a very typical problem related to JTable. My requirement is that cells should be added dynamically to the JTable. I create a JTable with initial size of 1,7 (row, columns) size. Once the 7 columns are filled with data, a new row should be created. But the requirement is, the new row i.e. second row should have only one cell in it initially. The number of cells should increase dynamically as the data is entered. The table is automatically taking the size of its previous row when new row is added. I tried by using setColumnCount() to change the number of columns to '1' for the second row but the same is getting applied to the first row also.
    So can you please help me out in this regard ? Is it possible to create a JTable of uneven size i.e. multiple rows with varying number of columns in each row ?
    Thanks in Advance.

    Well a JTable is always going to paint the same number of columns for each row. Anything is possible if you want to rewrite the JTable UI to do this, but I wouldn't recommend it. (I certainly don't know how to do it).
    A simpler solution might be to override the isCellEditable(...) method of JTable and prevent editing of column 2 until data in column 1 has been entered etc., etc. You may also want to provide a custom renderer that renderers the empty column differently, maybe with a grey color instead of a white color.

  • JTable with ImageIcons does not react to even handling

    Hi.
    I have a populated JTable with ONLY ImageIcons in it. I need to generate event responses on mouseClicks. However, any event listener I associate with this, nothing seems to be happening.
    (Somehow, I'm guess the ImageIcons - which are rendered on a JLabel, are/is the source of all troubles!!)
    The code is below :
    import java.io.File;
    import java.awt.Point;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    *     Entry point for the Images Table.
    *     @author Raj Gaurav
    public class SpecialCharacterDialog extends JDialog{
         String collectionString[] = null;
         ImageIcon suite[] = null;
         public SpecialCharacterDialog() {
              Container contentPane = getContentPane();
              //     Create the Table Model and create the Table from the model
              MyTableModel model = new MyTableModel();
              JTable table = new JTable(model);
              table.setDefaultRenderer(ImageIcon.class, new CustomCellRenderer());
              table.setCellSelectionEnabled(true);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
              //     Add the table to the contentPane
              JScrollPane pane = new JScrollPane(table);
              contentPane.add(pane);
    *     This class contains all the DATA information, the ImageIcons
    *     needed for display.
    class SymbolCollection {
         final static int NUMBER_OF_COLUMNS = 15;
         private String collectionString[] = null;
         private ImageIcon suite[] = null;
         *     Constructor : Initialises all the ImageIcon and their Names.
         public SymbolCollection() {
              File f = new File("C:\\Test\\Images");
              collectionString = f.list();
              int numberOfImages = collectionString.length;
              suite = new ImageIcon[numberOfImages];
              for(int i = 0;i < numberOfImages; i++) {
                   suite[i] = new ImageIcon("C:\\Test\\images" + File.separator + collectionString);
         *     Returns the total number of images in "images" folder.
         public int getTotalNumberOfImages() {
              return suite.length;
         *     Returns the target ImageIcon.
         public ImageIcon getImageIconAt(int number) {
              return suite[number];
         *     Returns the target ImageIcon Name.
         public String getImageIconNameAt(int number) {
              return collectionString[number];
         *     Returns an array of ALL the ImageIcons available.
         public ImageIcon[] getImageIcons() {
              return suite;
         *     Returns an array of ALL the ImageIcon names available
         public String[] getImageIconNames() {
              return collectionString;
         *     Returns TRUE for all cells
         public boolean isEditable(int row, int col) {
              return true;
    *     Defines the table model for the tabel.
    class MyTableModel extends AbstractTableModel {
         private SymbolCollection collection = null;
         private Object data[][] = null;
         *     Constructor for the TableModel. Initialises the "data" field for table.
         public MyTableModel() {
              int countOfImages = 0;
              collection = new SymbolCollection();
              data = new Object[getRowCount()][SymbolCollection.NUMBER_OF_COLUMNS];
              for(int i = 0; i < getRowCount(); i++) {
                   for(int j = 0; j < SymbolCollection.NUMBER_OF_COLUMNS; j++) {
                        if(countOfImages == collection.getTotalNumberOfImages()) {
                             break;
                        data[i][j] = collection.getImageIconAt(countOfImages);
                        countOfImages++;
         *     Returns the number of rows for this table.
         *     It is calculated as : TotalNumber/NumberOfColumns if remainder is ZERO or,
         *                              TotalNumber/NumberOfColumns + 1 if not.
         public int getRowCount() {
              int numberOfRows = collection.getTotalNumberOfImages()/SymbolCollection.NUMBER_OF_COLUMNS;
              if(numberOfRows == 0) {
                   return numberOfRows;
              else {
                   return numberOfRows + 1;
         *     Returns the number of Columns for this table
         public int getColumnCount() {
              return SymbolCollection.NUMBER_OF_COLUMNS;
         *     Returns the CLASS data type for this table
         public Class getColumnClass(int col) {
              return collection.getImageIconAt(0).getClass();
         *     Returns the table data at (row, col).
         public Object getValueAt(int row, int col) {
              return data[row][col];
    *     Renders the table to display images in individual cells
    class CustomCellRenderer extends JLabel implements TableCellRenderer {
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              setIcon((ImageIcon)value);
              return this;

    Hi.
    I have a populated JTable with ONLY ImageIcons in it. I need to generate event responses on mouseClicks. However, any event listener I associate with this, nothing seems to be happening.
    (Somehow, I'm guess the ImageIcons - which are rendered on a JLabel, are/is the source of all troubles!!)
    The code is below :
    import java.io.File;
    import java.awt.Point;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Container;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    *     Entry point for the Images Table.
    *     @author Raj Gaurav
    public class SpecialCharacterDialog extends JDialog{
         String collectionString[] = null;
         ImageIcon suite[] = null;
         public SpecialCharacterDialog() {
              Container contentPane = getContentPane();
              //     Create the Table Model and create the Table from the model
              MyTableModel model = new MyTableModel();
              JTable table = new JTable(model);
              table.setDefaultRenderer(ImageIcon.class, new CustomCellRenderer());
              table.setCellSelectionEnabled(true);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
              //     Add the table to the contentPane
              JScrollPane pane = new JScrollPane(table);
              contentPane.add(pane);
    *     This class contains all the DATA information, the ImageIcons
    *     needed for display.
    class SymbolCollection {
         final static int NUMBER_OF_COLUMNS = 15;
         private String collectionString[] = null;
         private ImageIcon suite[] = null;
         *     Constructor : Initialises all the ImageIcon and their Names.
         public SymbolCollection() {
              File f = new File("C:\\Test\\Images");
              collectionString = f.list();
              int numberOfImages = collectionString.length;
              suite = new ImageIcon[numberOfImages];
              for(int i = 0;i < numberOfImages; i++) {
                   suite[i] = new ImageIcon("C:\\Test\\images" + File.separator + collectionString);
         *     Returns the total number of images in "images" folder.
         public int getTotalNumberOfImages() {
              return suite.length;
         *     Returns the target ImageIcon.
         public ImageIcon getImageIconAt(int number) {
              return suite[number];
         *     Returns the target ImageIcon Name.
         public String getImageIconNameAt(int number) {
              return collectionString[number];
         *     Returns an array of ALL the ImageIcons available.
         public ImageIcon[] getImageIcons() {
              return suite;
         *     Returns an array of ALL the ImageIcon names available
         public String[] getImageIconNames() {
              return collectionString;
         *     Returns TRUE for all cells
         public boolean isEditable(int row, int col) {
              return true;
    *     Defines the table model for the tabel.
    class MyTableModel extends AbstractTableModel {
         private SymbolCollection collection = null;
         private Object data[][] = null;
         *     Constructor for the TableModel. Initialises the "data" field for table.
         public MyTableModel() {
              int countOfImages = 0;
              collection = new SymbolCollection();
              data = new Object[getRowCount()][SymbolCollection.NUMBER_OF_COLUMNS];
              for(int i = 0; i < getRowCount(); i++) {
                   for(int j = 0; j < SymbolCollection.NUMBER_OF_COLUMNS; j++) {
                        if(countOfImages == collection.getTotalNumberOfImages()) {
                             break;
                        data[i][j] = collection.getImageIconAt(countOfImages);
                        countOfImages++;
         *     Returns the number of rows for this table.
         *     It is calculated as : TotalNumber/NumberOfColumns if remainder is ZERO or,
         *                              TotalNumber/NumberOfColumns + 1 if not.
         public int getRowCount() {
              int numberOfRows = collection.getTotalNumberOfImages()/SymbolCollection.NUMBER_OF_COLUMNS;
              if(numberOfRows == 0) {
                   return numberOfRows;
              else {
                   return numberOfRows + 1;
         *     Returns the number of Columns for this table
         public int getColumnCount() {
              return SymbolCollection.NUMBER_OF_COLUMNS;
         *     Returns the CLASS data type for this table
         public Class getColumnClass(int col) {
              return collection.getImageIconAt(0).getClass();
         *     Returns the table data at (row, col).
         public Object getValueAt(int row, int col) {
              return data[row][col];
    *     Renders the table to display images in individual cells
    class CustomCellRenderer extends JLabel implements TableCellRenderer {
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
              setIcon((ImageIcon)value);
              return this;

  • [Help Wanted] soap1.1 webservice, filling a tree with the result of calls...

    Hi,
    I'm having trouble with filling a tree with the result to
    calls to a document/wrapped soap 1.1 webservice.
    I first declared the webservice in the mxml file as it was in
    the examples and tried to call it with no luck. The fault was it
    wasn't finding the document type for the call's unique parameter. I
    figured out the solution to this, I added a method in the
    webservice declaration having a single element named the same as
    the required parameter, and inside it, the "actual" parameters,
    bound to variables defined elsewhere.
    The reason for wanting the tree to be filled programatically,
    is the potential whole contents of the tree can be about 1.000.000
    nodes. Huge.
    quote:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" applicationComplete="initM()">
    <mx:Script>
    <![CDATA[
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.controls.treeClasses.TreeListData;
    [Bindable] public var aParentId:String = null;
    [Bindable] public var aLevel:Number = 0;
    ]]>
    </mx:Script>
    <mx:WebService id="lws" wsdl="
    http://myServer/myContext/myPortURI?WSDL"
    useProxy="false" makeObjectsBindable="true">
    <mx:operation name="getNodes" resultFormat="object">
    <mx:request>
    <getNodesElement>
    <parentId>{aParentId}</parentId>
    <level>{aLevel}</level>
    </getNodesElement>
    </mx:request>
    </mx:operation>
    </mx:WebService>
    <mx:Tree x="0" y="0" width="326" height="100%"
    id="layoutTree" enabled="true" labelField="nodeName">
    <mx:dataProvider>{lws.getNodes.lastResult}</mx:dataProvider>
    </mx:Tree>
    <mx:Script>
    <![CDATA[
    public function initM():void {
    lws.getNodes.send();
    return;
    ]]>
    </mx:Script>
    </mx:Application>
    So, here's the problem:
    1.- In both Java2 and .NET, I've been able to produce sets of
    proxy classes from the webservice wsdl, these include a proxy class
    for the service port and a set of classes for both the call
    parameter types and the call result types. I have not found yet a
    way to do the same with flex2, so I wonder, can I produce the
    required classes for dealing with such a webservice in an automatic
    way with flex2?
    2.- The second problem, is I haven't found a way to make a
    webservice call in sychronous mode, and I can't seem to find a way
    to set the parameters for the subsequent calls to the webservice.
    Is there a way to make a call to such webservice programatically? I
    mean, I've been able to make the first call I need programatically,
    but what if I end up making 2 or more simultaneous calls? I can't
    rely on setting the `variables defined elsewhere` before each call,
    because of possible concurrency issues (calls will be long after
    the 2nd level of the tree), so I wonder if there's a way to make a
    call to such webservice (document/wrapped, soap1.1) passing it the
    parameters programatically. If so, can I just put the parameters or
    do I have to produce the complete enclosure? If I have to produce
    also the enclosure, any hint on how to do so? I will need to pass
    different parentId, level pairs probably triggered by tree events.
    3.- the other problem, finally, is Tree looks quite different
    to me than the Java2 one. In java2, I can easily produce a changing
    model for the tree wich will even handle the calls to the
    webservice as needed (triggered by the tree itself), making it a
    `live model`. If there is a way to produce the same behaviour in
    flex2, I haven't found it yet. Sure, I've only downloaded the trial
    version yesterday, so I may have overlooked some docs or blogs.
    Any hints would be appreciated, specially on programatically
    modifying the tree, and making calls to the webservice changing the
    parameters every time.

    1. Not yet, but we're looking into supporting this in an
    upcomming release.
    2. All RPC requests must be made asynchronously... this is a
    restriction of the way the Flash Player makes network requests
    (otherwise movies, which are single threaded, would hang waiting
    for results). You should be able to use the ActionScript API to
    programmatically call web services with normal parameters.
    3. If you leave makeObjectsBindable="true" (which it is by
    default) the Objects and Arrays will be wrapped in ObjectProxies
    and ArrayCollections automatically and will report change events,
    however I don't believe that we have an example that links these
    change events up to subsequent web service calls, but it would be
    possible (but not automatic). A feature that does do this sort of
    thing automatically is the Data Service, although this does not use
    WSDL/SOAP to describe/communicate with remote services and you have
    to setup a Java assembler to work with our adapters on the
    server.

  • HELP Filling a datagrid with data from various tables

    MHI, this is simple.
    I have 2 tables.
    ORDERS and CLIENTS.
    table ORDERS are columns:  order_id, client_id, status
    table CLIENTS are columns: client_id, client_name
    my datagrid would have the columsn: order_id, client_name, status.
    Thats all. I can't simply do it in Flex. HELP PLEASE.
    These are my approaches:
    1 - tried to create a new array collection with mixed data from these 2 tables to use as dataprovider in the datagrid.
    even the ac is [Bindable], the datagrid won't update. Probably Im creating the ac in a wrong way.
    2 - tried to use the ORDERS table call responder lastResult property (that works out to fill the data grid) and add a new colounm (client_name) within each item inside the ORDERS array collection.
    I'm not able to ADD a property/field/column inside the ac.  Of course, when I use .addItem, it will create a new "order"  not a new "order.property"
    if something like:  ac.source[i].push({client_name:clientName}) worked...
    My goals are simple. To fill the datagrid with those data.
    Ah.. i almost forgot...
    supose CLIENTS have 1000 registers.
    I don't have to bring all those registers within flex to look for only one ID to retrieve a name to fill the orders datagrid, right?
    THANKS A LOT
    btp~

    Ok,  this is my first approach:
    this function is an auto-generated event that happens when I drag a databank operator over a datagrid. Datagrid's dataprovider IS set to "orders":
    (in my browser, the following messed lines only show decent while editting. Maybe copy it into a editor to better visualize: )
    protected function getOrders_pagedResult_resultHandler(event:ResultEvent):void             {                 orders = getOrders_pagedResult.lastResult                          //1 - this was previous declared as a Bindable Array Collection.                                             var ta:Array = new Array;                                 for (var t:String in event.result)                 {                     var tp:Array = new Array();                        tp.push(getOrders_pagedResult.lastResult[t].order_id);        //is it any difference to get data like in THIS LINE                           tp.push(event.result[t].status)                               //or THIS?                                             var cn:String = getClientsByID(event.result[t].client_id);     //this won't work in time. The getClientsByID delays to get data.                     var obj:Object = {client_name:cn};                             //so cn, in this line, will be "null". How can I handle this?                                         tp.push(obj);                                         ta.push(tp)                  }                                 orders.source.push(ta)                                             //this is what I wanted datagrid to show, but it doesn't.                                                                                    //if I leave the first statement, everything above is ignored                                                                                    //if I comment the first line, datagrid shows nothing.                            } 
    I realize that the code above won't work because the properties inside each item won't have a "label" to datagrid to call in dataField property...I don't know how to do that. I thought by creating an object (like the obj above) it would work...  it wont.
    My getClientsByID is a modificated auto-generated function which doesn't work properly:
    (in my browser, the following messed lines only show decent while editting. Maybe copy it into a editor to better visualize: )
    protected function getClientsByID(itemID:int):String {         getClientsByIDResult.token = clientsService.getClientsByID(itemID);         return(getClientsByIDResult.lastResult.name); } 
    It seems it doesn't work (returns null) because the function runs faster than the call responder result.
    Creating a listener for everything seems to be not the best practice, but a band-aid...
    Again.
    I should create a class in php to return the "ready-to-use" data. Ok?
    Thanks a lot for your comments. Do I miss any important part of the code?
    Btp~

  • Update row with more data - JTable with Abstracttablemodel

    Hello!
    I got some problems with my program, im using jtable with abstracttablemodel.
    First I include content into the jtable by pressing &rdquo;New Content&rdquo;, then it will pop up a dialog which I fill with information as you can see in the picture.
    http://img42.imageshack.us/img42/6969/jtable.jpg
    But when its done, I want to borrow it and update that row with more information as you can see if its loaned, if it is their shall be a checkbox, name and phone there. I don&rsquo;t really know how to do this. Suppose I should do a similar metodh as when I&rsquo;m adding and removing content. The question is how do I do that? I&rsquo;ve been looking at some tips and hints on google. It seems to me that should use &ldquo;fireTableRowsUpdated&rdquo; but not really sure if its right and how to. When I&rsquo;m borrowing the specific row I guess I need to check which row is clicked before borrowing and then fill in the information and update the table.The borrow button will also pop up a dialog with 3 fields to fill. Here is the code I wrote for adding and removing. I&rsquo;ve tried with the update but its not right which I&rsquo;m going to use when borrowing objects from the database. Please help!
    Code from the abstracttablemodel
    private ArrayList<Objects> obj = new ArrayList<Objects>();
         public void add(Objects o) {
              obj.add(o);
              fireTableRowsInserted(obj.size()-1, obj.size()-1);
         public void remove(int o) {
              int index = obj.indexOf(o);
              obj.remove(o);
              fireTableRowsDeleted(index, index);
         public void update (Objects o){
              // Not sure how to do here
              //int index = obj.indexOf(o);
              //fireTableRowsUpdated(index,index);
         }Code for the button in the main program.
    if (arg.getSource() == borrow) {
    // How should I do here? I need to implement the BorrowDialog, check if a row is pressed then update? How do I do that?
                   BorrowDialog newLoan = new BorrowDialog(frame);
                   if(table.getSelectedRow() == -1)
                        JOptionPane.showMessageDialog(frame,"Select the row before loan");
                   else
                        dir.update(newLoan.getLoan());
                        table.repaint();
              }Code for BorrowDialog
    public class BorrowDialog extends JDialog implements ActionListener {
            //implements JTextFields, Buttons,Labels and Panels.
         public BorrowDialog(JFrame parent) {
         //Setting buttons to panels and such
         public Objects getLoan(){
              return loan;
         public void setLoan()
                    // Not sure if this is right, as I leave some fields empty, will it be empty when its updating aswell?
                    // I tried with add data then it just will be a new row, when I will update a specific row
                    loan = new Objects("", "" , "" , "" , "" ,"", loanField.getText(),nameField.getText(), phoneField.getText());
         public void actionPerformed(ActionEvent arg) {
              if (arg.getActionCommand().equals("Save")) {
                   System.out.println("save");
                   setLoan();
                   dispose();
    }All help is appreciated!
    Edited by: iTech34 on Feb 22, 2010 3:27 AM
    Edited by: iTech34 on Feb 22, 2010 3:31 AM
    Edited by: iTech34 on Feb 22, 2010 3:58 AM

    Look up for the rest of the code!
    I explained everything on the first post, so please read there so you know the problem I got.
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class Database implements ActionListener {
         private final int WIDTH = 800;
         private final int HEIGHT = 800;
         private JTable table = new JTable();
         private JFrame frame = new JFrame("Database");
         private JButton addContent = new JButton("New content");
         private JButton borrow = new JButton("Borrow");
         private JButton returnObject = new JButton("Return");
         private JButton remove = new JButton("Remove");
         private JButton save = new JButton("Save");
         private JButton load = new JButton("Load");
         private JButton exit = new JButton("Exit");
         private Directory dir = new Directory();
         private JPanel buttonPanel = new JPanel();
         private JPanel mainPanel = new JPanel();
         public Database() {
              // BUTTONS
              buttonPanel.add(addContent);
              buttonPanel.add(remove);
              buttonPanel.add(borrow);
              buttonPanel.add(returnObject);
              buttonPanel.add(save);
              buttonPanel.add(load);
              buttonPanel.add(exit);
              // ACTION LISTENERS
              addContent.addActionListener(this);
              remove.addActionListener(this);
              borrow.addActionListener(this);
              returnObject.addActionListener(this);
              save.addActionListener(this);
              load.addActionListener(this);
              exit.addActionListener(this);
              // JTABLE
              table = new JTable(dir);
              table.setAutoCreateRowSorter(true);
              table.setRowHeight(25);
              JScrollPane JScroll = new JScrollPane(table);
              // PANELS
              mainPanel.setLayout(new BorderLayout());
              mainPanel.add("North", buttonPanel);
              mainPanel.add("Center", JScroll);
              // FRAME
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(WIDTH, HEIGHT);
              frame.getContentPane().add(mainPanel);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public void actionPerformed(ActionEvent arg) {
              if (arg.getSource() == addContent) {
                   Dialog newDialog = new Dialog(frame);
                   dir.add(newDialog.getItem());
              if (arg.getSource() == remove) {
                   if (table.getSelectedRow() == -1)
                        JOptionPane.showMessageDialog(frame,"Select the row before remove");
                   else
                        dir.remove(table.getSelectedRow());
              if (arg.getSource() == borrow) {
                   // Not sure how to do here! I need to check which row I've clicked and take that row into BorrowDialog as argument i suppose.. please explain
                   BorrowDialog newLoan = new BorrowDialog(frame);
                   if(table.getSelectedRow() == -1)
                        JOptionPane.showMessageDialog(frame,"Select the row before loan");
                   else
                        dir.update(newLoan.getLoan());
                        table.repaint();
              if (arg.getSource() == returnObject) {
              if (arg.getSource() == save) {
                   dir.writeFile();
              if (arg.getSource() == load) {
                   Objects[] tempObject = dir.readFile("info.txt");
                   for (int i = 0; tempObject[i] != null; i++)
                             dir.add(tempObject);
              if (arg.getSource() == exit){
                   frame.dispose();
         public static void main(String[] argv) {
              new Database();
    }import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class BorrowDialog extends JDialog implements ActionListener {
         private final int WIDTH = 300;
         private final int HEIGHT = 400;
         private JButton exitDialog = new JButton("Exit");
         private JButton saveDialog = new JButton("Save");
         private JTextField loanField = new JTextField();
         private JTextField nameField = new JTextField();
         private JTextField phoneField = new JTextField();
         private JLabel loanLabel = new JLabel("Loan");
         private JLabel nameLabel = new JLabel("Name");
         private JLabel phoneLabel = new JLabel("Phone");
         private JPanel eastPanel = new JPanel();
         private JPanel southPanel = new JPanel();
         private JPanel westPanel = new JPanel();
         private GridLayout layout = new GridLayout(3, 1);
         private Objects loan;
         public BorrowDialog(JFrame parent) {
              super(parent, "Borrow", true);
              southPanel.add(saveDialog);
              southPanel.add(exitDialog);
              westPanel.add(loanLabel);
              eastPanel.add(loanField);
              westPanel.add(nameLabel);
              eastPanel.add(nameField);
              westPanel.add(phoneLabel);
              eastPanel.add(phoneField);
              westPanel.setLayout(layout);
              eastPanel.setLayout(layout);
              add("West", westPanel);
              add("Center", eastPanel);
              add("South", southPanel);
              saveDialog.addActionListener(this);
              exitDialog.addActionListener(this);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setResizable(false);
              setSize(WIDTH, HEIGHT);
              getContentPane();
              setVisible(true);
         public Objects getLoan(){
              return loan;
         public void setLoan()
              // Can I really do like this? Will the the specific row I've chosen be overwriten entirly with blank elements in the six columns as I left empty(see below, when I send the arguments into the constructor)?
              loan = new Objects("", "" , "" , "" , "" ,"", loanField.getText(),nameField.getText(), phoneField.getText());
         public void actionPerformed(ActionEvent arg) {
              if (arg.getActionCommand().equals("Save")) {
                   System.out.println("save");
                   setLoan();
                   dispose();
              if (arg.getSource() == exitDialog) {
                   dispose();
    Edited by: iTech34 on Feb 22, 2010 11:19 AM
    Edited by: iTech34 on Feb 22, 2010 11:20 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTable with a JCheckBox in a header column

    Hi everybody,
    I have implemented a JTable with a JCheckbox in one of the header columns. For this I have used the following code from the Internet for rendering the table cell:
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent;
         protected int column;
         protected boolean mousePressed = false;
         public CheckBoxColumnHeader(ItemListener itemListener) {   
              rendererComponent = this;
              rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (table != null) {     
                   JTableHeader header = (ExtendedJTableHeader)table.getTableHeader();
                   if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());
                        rendererComponent.setBackground(header.getBackground());
                        rendererComponent.setFont(header.getFont());
                        header.addMouseListener(rendererComponent);
              setColumn(column);
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));
              return rendererComponent;
    From a technical point of view, the checkbox works as expected. However, I have problems with the graphical layout of the checkbox in the header column:
    1) The checkbox seems to be bigger than the height of the header column. It overlays the border lines of the table. When I increase the preferred size of the header row, the checkbox also increases its size and still overlays the table border lines.
    2) The checkbox has a diffferent background shading than the other columns in the header.
    Any help for solving these two layout problems are greatly appreciated.
    Thanks, Walter

    Hi,
    here is now the complete code
    package main;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Arrays;
    import java.util.Vector;
    import javax.swing.table.*;
    * <p>�berschrift: </p>
    * <p>Beschreibung: </p>
    * <p>Copyright: Copyright (c) 2007</p>
    * <p>Organisation: </p>
    * @author unbekannt
    * @version 1.0
    public class MainFrame extends JFrame {
         JTable table3;
         JScrollPane scp3; 
      //Den Frame konstruieren
      public MainFrame() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Initialisierung der Komponenten
      private void jbInit() throws Exception  {
        this.setSize(new Dimension(500, 320));
        this.setTitle("Action List");
        Vector<Object> rowData = new Vector<Object>();
        for (int i=0; i<3; i++) {
             Vector<Object> colData = new Vector<Object>(Arrays.asList("Data R" + i + "C0", "Data R" + i + "C1", "Data R" + i +"C2", (i%2 == 0) ? Boolean.TRUE : Boolean.FALSE));
             rowData.add(colData);
        Vector<Object> hdr = new Vector<Object>(Arrays.asList("Column 0", "Column 1", "Column 2 (MyO)", "Column 3"));
         DefaultTableModel tableM = new DefaultTableModel(rowData, hdr);
        table3 = new JTable(tableM);
        TableColumn tc = table3.getColumnModel().getColumn(3);   
        tc.setCellEditor(table3.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(table3.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxColumnHeader(table3, new MyItemListener()));
        scp3 = new JScrollPane(table3);
         scp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
         this.add(scp3);
      //�berschrieben, so dass eine Beendigung beim Schlie�en des Fensters m�glich ist
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent; 
         protected int column; 
         protected boolean mousePressed = false; 
         protected JTable myTable;
         public CheckBoxColumnHeader(JTable t, ItemListener itemListener) {   
              rendererComponent = this;   
              rendererComponent.addItemListener(itemListener);
              myTable = t;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              JTableHeader header = null;
              if (table != null) {     
                   header = (JTableHeader)table.getTableHeader();     
                    if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());       
                        rendererComponent.setBackground(header.getBackground());       
                        rendererComponent.setFont(header.getFont());       
                        header.addMouseListener(rendererComponent); 
              setColumn(column);   
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));   
              return rendererComponent; 
         protected void setColumn(int column) {this.column = column; } 
         public int getColumn() {return column; }
         protected void handleClickEvent(MouseEvent e) {
              if (mousePressed) {
                   mousePressed=false;     
                   JTableHeader header = (JTableHeader)(e.getSource());
                   JTable tableView = header.getTable();
                   TableColumnModel columnModel = tableView.getColumnModel();
                   int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                   int column = tableView.convertColumnIndexToModel(viewColumn);
                   if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
                        doClick();
         public void mouseClicked(MouseEvent e) {   
              handleClickEvent(e);   
              ((JTableHeader)e.getSource()).repaint(); 
         public void mousePressed(MouseEvent e) {   
              mousePressed = true; 
         public void mouseReleased(MouseEvent e) {  }
         public void mouseEntered(MouseEvent e) {  }
         public void mouseExited(MouseEvent e) {  }
         public JTable getTable() {return myTable; }
    public class MyItemListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
             CheckBoxColumnHeader source = (CheckBoxColumnHeader)e.getSource();
             if (source instanceof AbstractButton == false) return;
             boolean checked = e.getStateChange() == ItemEvent.SELECTED;
             for (int x = 0, y = source.getTable().getRowCount(); x < y; x++) {
                  source.getTable().setValueAt(new Boolean(checked),x,3);     
    As originally said, the checkbox in the header column overlays the table borders and also has a different background shading than the other header columns.

  • JTable with Created Class

    I have a class that I designed with 5 data members (2 Strings, 2 Dates and a Boolean) and I was wondering if it would be possible to have a JTable that I could just add objects to easily, and it would fill a row with a data member in each column, and have the boolean as a checkbox that would be checked when true and unchecked when false. Is there an easy way to go about this, or atleast a tip that you can give to help me out.?
    Thanks in advance.

    The [Bean Table Model|http://www.camick.com/java/blog.html?name=bean-table-model] was created for this situation.

Maybe you are looking for

  • HOw to add a 2nd monitor to my DX4380- UR22

    I only have my HDMI open and my monitr is an older version using a SVGA This question was solved. View Solution.

  • Phantom Context lookup or Is "java:" some kind of keyword ? ? ?

    I'm attempting to implement my own Context for capturing performance information out of a third party applications. I've run into a strange problem where the method call doesn't aways work even though the signature appears to be correct, with the onl

  • ITunes Error 7

    Can someone please help me? What am I missing? I updated my iTunes last year roughly around October 2012, and ever since, I have been unable to access my account on my computer. I keep getting the same combination of Error Messages. Whether it is the

  • My facetime isnt working

    my facetime isnt working for serveral days. i dont know why. can someone help me

  • Sitewide Splash page?

    http://webscom.zendesk.com/entries/10272- http://www.dynamicdrive.com/dynamicindex- Those are two tutorials that tell me how to make a splash page. What I want to do though is show a splash page whenever a user comes to my site through ANY link. So t