JckechBox into JTable -- getselectedrow

I have a problem with Checkbox into JTable
My table has checkbox into first column. If I select checkbox, the program open a new JPanel. To do this I have associated an ActionListener to CheckBox that seems to work fine. This is the related code:
public class AbstractAction implements ActionListener{            
     private static final long serialVersionUID = 1L;     
    public void actionPerformed(ActionEvent evt) {
        JCheckBox cb = (JCheckBox)evt.getSource();
        alarm_NOack_table.getSelectedRow()
        boolean isSel = cb.isSelected();
        if (isSel) {
    } else {
   };As you can see, in the listener I need to know the row number in which there is the selected checkbox, but alarm_NOack_table.getSelectedRow() return always '-1'.
How can I do?
Thanks in advance
Palmis

hey!!!
you will have to use TableModelListener
if you have a look at API
getSelectedRow()
Returns the index of the first selected row, -1 if no row is selected.
it says that only when row is selected. but clicking your check box does not select the whole row. so you need to listen for changes in the table itself. the best would be to write your own table model (extension of AbstractTableModel)
this is how you should be able to get the change a your row where the change occurred
public class YourClass implements TableModelListener{
yourTable.getModel().addTableModelListener(this);
public void tableChanged(TableModelEvent tme){
          int row = tme.getFirstRow();
          int col = tme.getColumn();
//if you want your table model then do this
TableModel tm = (TableModel)tme.getSource();
}and now you should have the row a column where the change has occurred and that's it
hope this will help
v.v.

Similar Messages

  • Cant get data from text file to print into Jtable

    Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
    void dbTest() {
    DataInputStream dis = null;
    String dbRecord = null;
    String hold;
    try {
    File f = new File("customer.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    Vector dataVector = new Vector();
    Vector headVector = new Vector(2);
    Vector row = new Vector();
    // read the record of the text database
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ",");
    while (st.hasMoreTokens()) {
    row.addElement(st.nextToken());
    System.out.println("Inside nested loop: " + row);
    System.out.println("inside loop: " + row);
    dataVector.addElement(row);
    System.out.println("outside loop: " + row);
    headVector.addElement("Title");
    headVector.addElement("Type");
    dataTable = new JTable(dataVector, headVector);
    dataTableScrollPane.setViewportView(dataTable);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    } // end if
    } // end finally
    } // end dbTest

    Here's a thread that loads a text file into a JTable:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172
    And my reply in this thread shows how you can use a text file as a simple database:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=342380

  • How to add data into JTable

    How can I add data into JTable, for instance ("Mike", "Gooler", 21).

    How can I add data into JTable, for instance ("Mike",
    "Gooler", 21).You will have very good results if you segregate out the table model as a seperate user class and provide a method to add a row there. In fact, if you use the table to reflect a database table you can add the row inplace using the existing cursor. I believe it's TableExample2 in the jdk\demo\jfc\TableExamples that has a very good example of this.
    Walt

  • Also problem read txt files into JTable

    hello,
    i used the following method to load a .txt file into JTable
    try{
                        FileInputStream fin = new FileInputStream(filename);
                        InputStreamReader isr = new InputStreamReader(fin);
                        BufferedReader br =  new BufferedReader(isr);
                        StringTokenizer st1 = new StringTokenizer(br.readLine(), "|");
                        while( st1.hasMoreTokens() )
                             columnNames.addElement(st1.nextToken());
                        while ((aLine = br.readLine()) != null)
                             StringTokenizer st2 = new StringTokenizer(aLine, "|");
                             Vector row = new Vector();
                             while(st2.hasMoreTokens())
                                  row.addElement(st2.nextToken());
                             data.addElement( row );
                        br.close();
                        }catch(Exception e){ e.printStackTrace(); }
                   //colNum = st1.countTokens();
                   model = new DefaultTableModel(data,columnNames);
                   table.setModel(model);but there is a problem : if cell A's location is (4,5),and its left neighbour,that is, cell(4,4) is blank (the value is ""), the the cell A's value will be displayed in cell(4,4).if cell(4,3) is also blank ,the cell A's value will be displayed in cell(4,3).that is,the non-blank value will be displayed in the first blank cell of the line.
    how can i solve it?Please give me some helps or links.
    Thank u very much!

    Or, use the String.split(..) method to tokenize the data
    Or, use my SimpleTokenizer class which you can find by using the search function.

  • Adding JButton into JTable cells

    Hi there!!
    I want to add a JButton into JTable cells.In fact I have got two classes.Class2 has been extended from the AbstractTableModel class and Class1 which is using Class2's model,,,here's the code,,
    Class1
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Class1 extends javax.swing.JFrame {
       //////GUI specifications
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestTableButton().setVisible(true);
            Class2 model=new Class2();
            jTable1=new JTable(model);
            jScrollPane1.setViewportView(jTable1);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration                  
        private javax.swing.JTable jTable1;
    }Class2
    import javax.swing.table.*;
    public class Class2 extends AbstractTableModel{
        private String[] columnNames = {"A","B","C"};
        private Object[][] data = {
        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][col];
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         * Don't need to implement this method unless your table's
         * editable.
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
                return false;
         * Don't need to implement this method unless your table's
         * data can change.
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
    }what modifications shud I be making to the Class2 calss to add buttons to it?
    Can anybody help plz,,,,,??
    Thanks in advance..

    Hi rebol!
    I did search out a lot for this but I found my problem was a bit different,,in fact I want to use another class's model into a class being extended by JFrame,,so was a bit confused,,,hope you can give me some ideas about how to handle that scenario,,I know this topic has been discussed before here many a times and also have visited this link,,
    http://forum.java.sun.com/thread.jspa?threadID=465286&messageID=2147913
    but am not able to map it to my need,,,hope you can help me a bit...
    Thanks .....

  • Need to use vector to insert data into JTable?

    hi
    i'm trying to insert data from mssql 2000 into JTable. The number of columns are fixed, but the number of rows are not, since it will depend on how many data retrieved from the database.
    The documentation says that vector class implements a growable array of objects, and I've seen some examples using vector such as from http://forum.java.sun.com/thread.jspa?forumID=57&threadID=238597 .
    I would like to know, in my case, do i need to set my column and row to use vector? or should i only set rows to use vector ? (since the row size will vary, while the column size will stick to 6).

    Because your JTable operation will be done on a table model, the selection of the initial data
    structure for the model is almost non-issue. In other words, whatever will do.
    See the javadoc for the DefaultTableModel class, which you will eventually use, especially the
    construcotr part.

  • URGENT--inserting into JTable

    Hi
    i'm trying to insert data retrieved from the database into JTable
    i have seen some code examples on TableModel on this site but
    getting confused.Can anybody give me a full code example.
    Ashish

    you can take a look at the following link:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=357504
    I published my code for a dynamic table that supports adding/removing columns.

  • JTable.getSelectedRow seems to return wrong index value in J2SDK 1.4

    OS version: Microsoft Windows 2000 [Version 5.00.2195]
    JDK version: J2RE, Standard Edition (build 1.4.2_07-b05)
    I have a pretty simple JTable in which when a user selects a particular value in the first column of a row, the remainder of the columns in that row are populated with text values. The way we tell the JTable which row to populate the column values for is via the getSelectedRow() method. This worked fine using 1.3.1.08. However, when we upgraded to 1.4.2.07, we get an ArrayIndexOutOfBoundsException thrown because for some reason the getSelectedRow method returns the wrong value (e.g. if the user selects the first row, instead of returning an index of 0, the method returns an index of 2, even if there is only 1 row in the table, thus the out-of-bounds). The code has not changed at all -- all we have done is upgrade the version of the JDK. I have seen similar issues on various postings on the web, but these all have to do with removing rows and the like, and having to cancel or stop cell editing before removing the row(s). However, this does not apply in my case, so I think this might be a new bug. Before I post all kinds of code, does anybody know if this is a known bug and/or is there a workaround?
    Here is my stack trace:
    In Thread[AWT-EventQueue-0,6,main]
    caught java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
         at java.util.Vector.elementAt(Vector.java:431)
         at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:633)
         at com.sra.kdd.tools.view.NtwrkDefnVW.propertyChange(NtwrkDefnVW.java:475)
         at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:330)
         at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:257)
         at com.sra.kdd.tools.model.NtwrkSourceDSMDL.setDsNM(NtwrkSourceDSMDL.java:298)
         at com.sra.kdd.tools.view.NtwrkCTRL.handleSourceTableEvent(NtwrkCTRL.java:464)
         at com.sra.kdd.tools.view.NtwrkCTRL.tableChanged(NtwrkCTRL.java:120)
         at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
         at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:259)
         at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:635)
         at javax.swing.JTable.setValueAt(JTable.java:1794)
         at javax.swing.JTable.editingStopped(JTable.java:3167)
         at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:124)
         at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:329)
         at javax.swing.DefaultCellEditor$3.stopCellEditing(DefaultCellEditor.java:139)
         at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:214)
         at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:346)
         at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1197)
         at javax.swing.JComboBox.setSelectedItem(JComboBox.java:561)
         at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:597)
         at javax.swing.plaf.basic.BasicComboPopup$ListMouseHandler.mouseReleased(BasicComboPopup.java:749)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at javax.swing.plaf.basic.BasicComboPopup$2.processMouseEvent(BasicComboPopup.java:452)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    I do have a workaround -- this is definitely not a recommended workaround whatsoever, but it's what I've done just to get by for now, so I thought it might possibly shed some light into the problem. It seems that the index is always off by 2, so I just subtract 2 from the result of getSelectedRow() and then everything works just fine.
    Any ideas? Thank you!

    If I remember correctly there was a big change in the focus subsystem between JDK1.3 and JDK1.4
    Before I post all kinds of code,...Write a 10 line demo program that shows this behaviour. We aren't interested in all kinds of code. If you can't duplicate the problem in 10 lines of code, then the problem is with the rest of your code. So compare you demo code to see why its working and your current code to see why its not working.

  • From Database into JTable

    Hi!
    I have a ResultSet from a database query (select * from table) and I plan to turn it into a Object[][] in order to satisfy one of the DefaultTableModel's constructor ("DefaultTableModel(Object[][] data, Object[] columnNames)") and place it in a JTable - how do I go about in doing this.
    I tried this:
    myJTable.setModel(new DefaultTableModel(getData(rs),columnNames));
    private Object getData(ResultSet rs){
    java.util.ArrayList<Object[]> mySets = new java.util.ArrayList<Object[]>();
    try{
    while(rs.next()){
    Object[] row = {
    rs.getString("column1"), rs.getString("column2"), new Boolean(false)
    ResultSets.add(row);
    catch(Exception e){
    e.printStackTrace();
    return mySets;
    But got this error when I compiled:
    cannot find symbol
    symbol : constructor DefaultTableModel(java.lang.Object,java.lang.String[])
    location: class javax.swing.table.DefaultTableModel
    new DefaultTableModel(
    1 error
    BUILD FAILED (total time: 0 seconds)
    I'm trying to do this because I would want to have my JTable to have a checkbox in it like what's shown in the Java tutorial's SimpleTableDemo.java.
    Basically, am getting data directly from the database - those that are set to 1 is enabled and 0 to disabled, then represent those as check boxes in the JTable.
    Thank you so much for your help!

    Thanks calvino_ind!
    I've managed to get your suggestion to work:
                while(rs.next()){
                    for(int i = 0; i < row; i++){          
                        for(int j = 0; j < col; j++){
                            obj[i][j] = rs.getObject(j+1);
                        rs.next();
                }Issues:
    I had to define the number of rows in order to initialize the Object's size:
                Object[][] obj = new Object[number of rows][number of columns];*column size can be retrieved from what's shown in previous post.
    To get the number of rows I had to do this:
                while(rs.next()){ row++; }But in doing so, the cursor moves to the last row of the ResultSet. To move it back I had to execute this:
                rs.beforeFirst();Here's the whole section of the code that's been my concern:
        private Object[][] getData(ResultSet rs){
            Object[][] obj = null;
            int row = 0;
            int col = 0;
            ResultSetMetaData rsmd;
            try{
                rsmd = rs.getMetaData();
                while(rs.next()){ row++; }
                System.out.println(rs.getFetchSize());
                col = rsmd.getColumnCount();
                obj = new Object[row][col];
                rs.beforeFirst();
                while(rs.next()){
                    for(int i = 0; i < row; i++){          
                        for(int j = 0; j < col; j++){
                            obj[i][j] = rs.getObject(j+1);
                        rs.next();
            }catch(Exception e){
                e.printStackTrace();
            return obj;
        }Now I did a little bit of fiddling around the forums, and came across a discussion that's it's not advisable to get the row count (second post of this link: http://forum.java.sun.com/thread.jspa?threadID=683676&messageID=3982010).
    Anyone care to shed some more light into this?
    Thanks!

  • Problem reading .txt-file into JTable

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
    public TeamTable()                {
    super( "Invoermodule - Team Table" );
    setSize( 740, 365 );
              // setting the rownames
    ListModel listModel = new AbstractListModel()                     {
    String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
    "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
    public int getSize() { return headers.length; }
    public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    A MORE READABLE VERSION !
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
        public TeamTable()                {
            super( "Invoermodule - Team Table" );
            setSize( 740, 365 );
              // setting the rownames
            ListModel listModel = new AbstractListModel()                     {
                String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
                "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
                public int getSize() { return headers.length; }
                public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

  • Search on a row in jTable...and load a file into jTable...

    hello i'm new to this community however...
    i'm trying to source in jtable row...let's say i have 3 columns...and 3 rows...the third row is filled with data like: "John", "Johnny", "94252" ... the two other rows are filled with other data...now i want to search for "John"...when the word is found the row get highlighted...any ideas ?? and another thing... i want to load a textfile into a jTable cells...the file is saved as a textfile which seperates each word with the character ; like ... Camel;Nanny;552353 ... any ideas about this one ?
    thnx
    //Andr�

    It didn't work of course...or did i missunderstand you ?1) You need to loop through all rows, since you don't know which row contains the string your are searching for.
    2) Never use "==" when comparing Objects. You use the equals method:
    if (....getValueAt(row, 0).equals( str ))

  • Drag and Drop Image into JTable

    I was wondering if anyone can tell me if it is possible to have an image dragged and dropped into a JTable where the single image snaps to multiple columns and rows?
    Thank you.

    Can anyone point me in the right direction for doing the following:
    Drag and drop an image into a JTable where the single image snaps to multiple columns and rows.
    Thanks.

  • Save/Load into Jtable

    How can I load data and save data from Jtable in a comma delimited format?
    And how can I execute a calculation by writing r1c3+r1c2 in a Jtextfield. R1 means row1 c3 means column3. What method or class can I use to locate the data on the JTable and do the calculation.
    public class SpreadSheetEditor extends JFrame  implements ActionListener
         JFileChooser chooser = new JFileChooser();
          * This constructs the GUI.  It is not a public method to be called by other
          * classes.
         protected SpreadSheetEditor()
              // Set title bar text and close box functionality on the JFrame
              super("SpreadSheetEditor");
              // Add content pane to JFrame and set to Border Layout
              Container contentPane = this.getContentPane();
              contentPane.setLayout(new BorderLayout(20,20));
              // Add JScrollPane to center of ContentPane and set scroll bar policy
              JScrollPane myScrollPane = new JScrollPane();
              myScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              myScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              contentPane.add(myScrollPane, BorderLayout.CENTER);
              // Add JTable to ScrollPane
              JTable myTable = new JTable(20,10);
              TableColumn column = new TableColumn();
              myScrollPane.setViewportView(myTable);
              myTable.setRowHeight(20);
              column.setPreferredWidth(50);
              // Add JPanel to bottom (south) of content pane for buttons
              JPanel myPanel = new JPanel();
              myPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              contentPane.add(myPanel, BorderLayout.SOUTH);
              // Add TextField
              JTextField textField = new JTextField(20);
              contentPane.add(textField, BorderLayout.SOUTH);
              // Create and add load and save and execute buttons to JPanel
              JButton loadButton = new JButton("Load");
              JButton saveButton = new JButton("Save");
              JButton executeButton = new JButton("Execute");
              myPanel.add(executeButton);
              myPanel.add(loadButton);
              myPanel.add(saveButton);
              // Crerate a JMenu
              JMenu menu = new JMenu("File");
              JMenuItem m;
              m= new JMenuItem("Clear SpreadSheet");
              m.addActionListener(this);
              menu.add(m);
              m= new JMenuItem("Exit Editor");
               m.addActionListener(this);
              menu.add(m);
              JMenuBar mBar = new JMenuBar();
              mBar.add(menu);
              setJMenuBar(mBar);
              // Add action listeners to buttons
              loadButton.addActionListener(this);
              saveButton.addActionListener(this);
               executeButton.addActionListener(this);
              // Set frame size and make visible
              super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              super.setSize(500,500);
              super.setVisible(true);
          * This method calls either loadFile or saveFile in reponse
          * to the buttons being pushed.
          * @param e the event from the button push
         public void actionPerformed(ActionEvent e)
              if (e.getActionCommand().equals("Load"))
                   loadFile();
              else if (e.getActionCommand().equals("Save"))
                   saveFile();
              else if(e.getActionCommand().equals("Exit Editor"))
                   System.exit(1);
         //     else if(e.getActionCommand().equals("Clear SpreadSheet"))
         //          theText.setText("");
          * This pops the file chooser and then calls the loadFile(File) method.
         protected void loadFile()
              int returnVal = chooser.showOpenDialog(this);
              if(returnVal == JFileChooser.APPROVE_OPTION)
                   loadFile(chooser.getSelectedFile());
          * This loads the file and displays it in the textArea.
          * @param fileToLoad the file to load in to the text area
         protected void loadFile(File fileToLoad)
              try
                   FileReader freader = new FileReader(fileToLoad);
                   BufferedReader breader = new BufferedReader(freader);
                  String line;
                  while ((line = breader.readLine()) != null)
                  //     myJTable.append(line + "\n");
                  breader.close();
              catch (IOException ioe)
                   ioe.printStackTrace();
          * This takes what is in the JTable and saves it to a file.
          * Pops a JChooser to determine the file name.
         protected void saveFile()
              int returnVal = chooser.showSaveDialog(this);
              if(returnVal == JFileChooser.APPROVE_OPTION)
                   try
                        FileWriter fwriter = new FileWriter(chooser.getSelectedFile());
                        BufferedWriter bwriter = new BufferedWriter(fwriter);
                   //     bwriter.write(myJTable.getText());
                        bwriter.close();
                   catch (IOException ioe)
                        ioe.printStackTrace();
          * The main method creates an instance of SpreadSheetEditor.
         public static void main(String[] args)
              SpreadSheetEditor myEditor = new SpreadSheetEditor();
    }

    First a suggestion, break up your GUI into a couple of classes. It would be perferable if in your constructor you had something more like
    super("SpreadSheet Editor");
    setJMenuBar(new myOwnMenuBar());
    getContentPane.add(new mySpreadsheetPanel());and then the SpreadsheetPanel would be broken up into the JTable, and maybe a panel with some buttons on it if you need them. Just a suggestion, it tends to make the code much easier to debugg and change/add functionality to later.
    As for loading a file, you should know the format of the data. I would store it something like
    rowcol, data, rowcol, data, rowcol, data
    then just read it in and fill it into the table where needed.
    You should create your own TableModel which should be a subclass of AbstractTableModel. This will make your life easier. The TabelModel is where the JTable gets/stores all its data, and it is what is used to update the JTable.
    As for the calculations here is a class I wrote for doing a similar project. There are a couple of classes used but they are mostly small classes and if you need more explenation on them just let me know.
    import java.util.StringTokenizer;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
      *@author
      *@version 1.0 3/5/03
      *the ExpressionTree class is used to evaluate and hold a mathmatical expression
    public class ExpressionTree{
         SimpleStack numberstack, opstack, cellrefs;
         String originalexpression;
         Token root;
         Graph graph;
           *creates an Expression tree
           *@param expression the expression to be evaluated
           *@param graph a reference to the Graph where cells are stored
           *@throws MalformedCellException thrown if the expression is invalid
         ExpressionTree(String expression, Graph graph)throws MalformedCellException{
              originalexpression      = expression;
              this.graph              = graph;
              StringTokenizer extoken = new StringTokenizer(expression, OperatorToken.OPERATORS, true);
              String[] tokens         = new String[extoken.countTokens()];
              for(int i=0;i<tokens.length;i++){
                   tokens=extoken.nextToken();
              buildTree(tokens);
         //creates the tree from the array of tokens each token is a portion of the expression
         private void buildTree(String[] tokens)throws MalformedCellException{
              boolean checkunaryminus = true;
              boolean unaryminus = false;
              numberstack = new SimpleStack(13);
              opstack = new SimpleStack(13);
              cellrefs = new SimpleStack(13);
              for(int i=0;i<tokens.length;i++){
                   if(LiteralToken.isLiteral(tokens[i])){
                        if(unaryminus){
                             numberstack.push(new LiteralToken(-1*Double.parseDouble(tokens[i])));
                             opstack.pop();
                             unaryminus = false;
                        }else{
                             numberstack.push(new LiteralToken(Double.parseDouble(tokens[i])));
                        checkunaryminus = false;
                   }else if(CellToken.isCell(tokens[i])){
                        Cell tempcell = getCell(tokens[i]);
                        cellrefs.push(tempcell);
                        Token temp = new CellToken(tempcell);
                        if(unaryminus){
                             temp = buildSubTree(new LiteralToken(0), (OperatorToken)opstack.pop(), temp);
                             unaryminus = false;
                        numberstack.push(temp);
                        checkunaryminus = false;
                   }else if(OperatorToken.isOperator(tokens[i])){
                        if(unaryminus) throw new MalformedCellException("illegal expression operator after minus");
                        char op = tokens[i].charAt(0);
                        if(checkunaryminus){
                             if(op=='-'){
                                  opstack.push(new OperatorToken(op));
                                  checkunaryminus = false;
                                  unaryminus = true;
                             }else{
                                  opstack.push(new OperatorToken(op));
                        }else{
                             if(op=='('){
                                  opstack.push(new OperatorToken(op));
                             }else if(op==')'){
                                  OperatorToken temp = (OperatorToken)opstack.pop();
                                  while(temp.instancePriority() != OperatorToken.getPriority('(')){
                                       if(numberstack.numObjects()<2){
                                            throw new MalformedCellException("Incefficient Numbers");
                                       Token r = (Token)numberstack.pop();
                                       Token l = (Token)numberstack.pop();
                                       numberstack.push(buildSubTree(l, temp, r));
                                       temp = (OperatorToken)opstack.pop();
                             }else{
                                  if(!opstack.isEmpty()){
                                       OperatorToken ot = (OperatorToken)opstack.peek();
                                       if(OperatorToken.getPriority(op)<ot.instancePriority()){
                                            if(numberstack.numObjects()<2){
                                                 throw new MalformedCellException("Incefficient Numbers");
                                            Token r = (Token)numberstack.pop();
                                            Token l = (Token)numberstack.pop();
                                            numberstack.push(buildSubTree(l, (OperatorToken)opstack.pop(), r));
                                  opstack.push(new OperatorToken(op));
                             checkunaryminus = true;
                   }else{
                        throw new MalformedCellException("illegal expression Failed all tests");
              while(!opstack.isEmpty()){
                   if(numberstack.numObjects()<2){
                        throw new MalformedCellException("Incefficient Numbers");
                   Token r = (Token)numberstack.pop();
                   Token l = (Token)numberstack.pop();
                   numberstack.push(buildSubTree(l, (OperatorToken)opstack.pop(), r));
              root = (Token)numberstack.peek();
         *gets the value of this expression
         *@return String returns the value of this expression in a String
         public String getValue(){
              double temp = root.getValue();
              return String.valueOf(temp);
         *gets the original expression that was parsed
         *@return String the original expression
         public String getEquation(){
              return originalexpression;
         *get the cells that are reference in this expression
         *@return Cell[] array of cells this expression holds
         public Cell[] getReferences(){
              Cell[] returncells = new Cell[cellrefs.numObjects()];
              int index = 0;
              while(!cellrefs.isEmpty()){
                   returncells[index++]=(Cell)cellrefs.pop();
              return returncells;
         //builds one three node subtree
         private Token buildSubTree(Token l, OperatorToken ot, Token r){
              ot.setLeftChild(l);
              ot.setRightChild(r);
              return ot;
         //uses buildSubTree to create a tree until more of the expression needs to be parsed
         private Token buildSubTrees(char op)throws MalformedCellException{
              if(op==')'){
                   OperatorToken ot = (OperatorToken)opstack.peek();
                   while(ot.instancePriority()!=0){
                        if(numberstack.numObjects()<2){
                             throw new MalformedCellException("Incefficient Numbers");
                        Token r = (Token)numberstack.pop();
                        Token l = (Token)numberstack.pop();
                        numberstack.push(buildSubTree(l, (OperatorToken)opstack.pop(), r));
              }else{
                   OperatorToken ot = (OperatorToken)opstack.peek();
                   while(OperatorToken.getPriority(op)<ot.instancePriority()){
                        if(numberstack.numObjects()<2){
                             throw new MalformedCellException("Incefficient Numbers");
                        Token r = (Token)numberstack.pop();
                        Token l = (Token)numberstack.pop();
                        numberstack.push(buildSubTree(l, (OperatorToken)opstack.pop(), r));
              return (Token)numberstack.peek();
         //gets or creates cell that is referenced in expression
         private Cell getCell(String cellname)throws MalformedCellException{
              int row = 0;
              int col = 0;
              Pattern colpatt = Pattern.compile("[a-zA-Z]+");
              Pattern rowpatt = Pattern.compile("\\d+");
              Matcher m = colpatt.matcher(cellname);
              m.find();
              String columnstring = m.group().toUpperCase();
              m = rowpatt.matcher(cellname);
              m.find();
              String rowstring = m.group();
              row = Integer.parseInt(rowstring);
              row--;
              char[] colchar = columnstring.toCharArray();
              for(int j=colchar.length-1;j>=0;j--){
                   col+=colchar[j]-'A'*Math.pow(26, j);
              if(row<0||col<0){
                   throw new MalformedCellException("illegal expression");
              Vertex v = graph.doesCellExist(col, row);
              if(v!=null){
                   return v.getCell();
              return new Cell(col, row, "0", graph);

  • Adding JCheckBox into JTable

    Hi all,
    I added a JCheckBox into a JTable, while clicking the check box the selection will not replicate into the JTable. Please help me to resolve this issue.
    * TableDemo.java
    * Created on September 5, 2006, 11:49 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package simPackage;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    * @author aathirai
    public class TableDemo extends JPanel{
       // public JRadioButton[] dataButton;
        /** Creates a new instance of TableDemo */
        public TableDemo() {
            JCheckBox firstCheck = new JCheckBox("");
            Object[][] data={{firstCheck,"2","4","5","2"}};
                    String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
                    JTable searchResultTable = new JTable(data,columnNames);
                    searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
                    searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
            JScrollPane scrollPane = new JScrollPane(searchResultTable);
            //Add the scroll pane to this panel.
            add(scrollPane);
    public static void main(String args[])   {
         JFrame jFrame  = new JFrame("testing");
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableDemo newContentPane = new TableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            jFrame.setContentPane(newContentPane);
            //Display the window.
            jFrame.pack();
            jFrame.setVisible(true);
    class RadioButtonRenderer implements TableCellRenderer {
        public JCheckBox check1 = new JCheckBox("");
      public Component getTableCellRendererComponent(JTable table, Object value,
       boolean isSelected, boolean hasFocus, int row, int column) {
          check1.setBackground(Color.WHITE);
         return check1;
    class RadioButtonEditor extends DefaultCellEditor{
        public JCheckBox check1 = new JCheckBox("");
      boolean state;
      int r, c;
      JTable t;
      class RbListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          if (e.getSource() == check1){
            state = true;
          else{
            state = false;
          RadioButtonEditor.this.fireEditingStopped();
      public RadioButtonEditor(JCheckBox checkBox) {
        super(checkBox);
      public Component getTableCellEditorComponent(JTable table, Object value,
       boolean isSelected, int row, int column) {
        RbListener rb = new RbListener();
        t = table;
        r = row;
        c = column;
        if (value == null){
          return null;
        check1.addActionListener(rb);
         //check1.setSelected(((Boolean)value).booleanValue());
        /*if (((Boolean)value).booleanValue() == true){
          check1.setSelected(true);
        return check1;
      public Object getCellEditorValue() {
        if (check1.isSelected() == true){
          return Boolean.valueOf(true);
        else{
          return Boolean.valueOf(false);
    }Thanks in advance.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class TableDemo extends JPanel
      public TableDemo()
        //JCheckBox firstCheck = new JCheckBox("");
        //Object[][] data={{firstCheck,"2","4","5","2"}};
        Object[][] data={{new Boolean(false),"2","4","5","2"}};
        String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
        JTable searchResultTable = new JTable(data,columnNames);
        //searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
        //searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
        TableColumn tc = searchResultTable.getColumnModel().getColumn(0);
        tc.setCellEditor(searchResultTable.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(searchResultTable.getDefaultRenderer(Boolean.class));
        JScrollPane scrollPane = new JScrollPane(searchResultTable);
        add(scrollPane);
      public static void main(String args[])
        JFrame jFrame  = new JFrame("testing");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        jFrame.setContentPane(newContentPane);
        jFrame.pack();
        jFrame.setVisible(true);
    }

  • Queue/Array into JTable

    Hi, I am reading some data from a database and I have got it stored locally inside a queue. What i want to do is read in the queue (already got a mehtod for this) but then add each object in the queue, into a row in my JTable. also I want to be able to delete a row of a jtable when i am finished with it. any help very much apprecaited. all i have got so far is declaring the JTable and jscrollpane etc. i sint too crash hot on swing so you might have to make it obvious. thanks.

    Right, I seem to have got myself into a mess with this. i dont think i'm too far off though. if i get this bit then i should have cracked it. I am getting a null pointer exception as i try to enter my first string into the TableModel. PS Its a bit of a hashed together attempt so any tips of how to improve the class generally, greatly appreciated.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ProtocolGUI extends JPanel implements ActionListener
              private JPanel menuPanel;
              private JMenuBar menuBar;
            private JMenu fileMenu;
            private JMenu helpMenu;
              private JMenuItem startMon;
             private JMenuItem exitItem;
            private JMenuItem about;
            private JTabbedPane tabbedPane;
              private JPanel graphicsPanel;
              private JPanel textPanel;
            private JTable pclTable;
         public ProtocolGUI()
            super(new BorderLayout());
            menuBar = new JMenuBar();
            fileMenu = new JMenu("File");
            helpMenu = new JMenu("Help");
            startMon = new JMenuItem("Start");
             exitItem = new JMenuItem("Exit");
            about = new JMenu("About");
            menuPanel= new JPanel();
            menuPanel.setLayout(new BorderLayout());
            this.add(menuPanel, BorderLayout.NORTH);
            exitItem.addActionListener(this);
            fileMenu.add(startMon);
            fileMenu.add(exitItem);
            helpMenu.add(about);
            menuBar.add(fileMenu);
            menuBar.add(helpMenu);
            menuPanel.add(menuBar, BorderLayout.NORTH);
              ///////////end of menu///////////////
            tabbedPane = new JTabbedPane();
              ImageIcon graphIcon = createImageIcon("images/graphtab.gif");
              ImageIcon textIcon = createImageIcon("images/texttab.gif");
            graphIcon = new ImageIcon("images/graphtab.gif");
            textIcon = new ImageIcon("images/texttab.gif");
            graphicsPanel = new JPanel();
            textPanel = new JPanel();
              tabbedPane.addTab("Graphical", graphIcon, graphicsPanel,
                              "Swaps to graphical output");
            tabbedPane.addTab("Text", textIcon, textPanel,
                              "Swaps to text output");
            /*TableModel dataModel = new AbstractTableModel()
              public int getColumnCount()
                     return 6;
              public int getRowCount()
                     return 20;
              public Object getValueAt(int row, int col)
                     return new Integer(row*col);
              //pclTable = new JTable(dataModel);
            MessageSet ms2 = new MessageSet();
              textPanel.add(new JScrollPane(createTable(ms2.getArray())));
            //Add the tabbed pane to the outer panel.
              add(tabbedPane, BorderLayout.CENTER);
            setPreferredSize(new Dimension(500, 500));
            //Uncomment the following line to use scrolling tabs.
            //tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        // Creates a JTable and returns it
         private JTable createTable(Message[] theArray)
              // Define empty data for model creation
              String[][] cellData = new String[0][6];
              String[] colNames = { "ID", "Sent To", "Sent From", "Command", "Data Ref", "Monitored" };
              // Create the table model
              DefaultTableModel tableModel = new DefaultTableModel(cellData, colNames);
              // Create some records and add them to the model
              String[] record = new String[6];
              for (int row=0; row<=theArray.length; row++)
                record[0] = Integer.toString(theArray[row].getID());
                record[1] = theArray[row].getToSection_ID();
                   record[2] = theArray[row].getFromSection_ID();
                   record[3] = Integer.toString(theArray[row].getType_ID());
                   record[4] = theArray[row].getDataRef();
                   record[5] = Integer.toString(theArray[row].getMonitored());
                   tableModel.addRow(record);
              // Create the table and return it
              return new JTable(tableModel);
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path)
            java.net.URL imgURL = ProtocolGUI.class.getResource(path);
            if (imgURL != null)
                return new ImageIcon(imgURL);
              else
                System.err.println("Couldn't find file: " + path);
                return null;
        public void actionPerformed(ActionEvent e)
            Object source = e.getSource();
            if (source == exitItem)
                System.exit(0);
         private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Protocol GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ProtocolGUI();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.getContentPane().add(new ProtocolGUI(),
                                     BorderLayout.CENTER);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

Maybe you are looking for

  • Can't access my external hard drive on my new iMac

    Hello All, I just purchased a brand new iMac and am unable to access my Iomaga external hard drive. It's plugged in thru a usb port and the only way it pops up is if I unplug it from the outlet and plug it back in. When it shows up in the device list

  • Can't open PSD files after saving them

    I haven't ever had this issue before and now have had it twice in the last week or so. I scrap all the time and now after saving the file as a PSE, when I go to reopen from inside Photoshop Elements 7, it's telling me it can't be opened because it's

  • Stop and Start Services

    Hi All, We are stopping and starting the services for daily backup. Is it advisable to stop and start services. Because client wants to stop the services before taking the backup anf start the services after backup. In this scenario, what services do

  • Moving a Selection a specific point distance

    I need to move areas of an image that I have selected using the unit of points. For example, I get corrections in our copy where I need to move certain parts of the image 8 points up or over 3 points. Is there any way to easily do this? I can use the

  • Problemi 3g dopo aggiornamento

    Ciao a tutti. io ho il seguente problema. dopo l'aggiornamento, nella pagina "Cellulare" ho abilitato i dati cellulari, disabilitato LTE, abilitato il roaming dati. il problema sorge che spesso da solo ho il 3g attivo, questo causa spreco di batteria