JTabbed+Jscroll+JTable...

Hi all, I have a problem mixin all this components:
I have a JTabbedPane with some tabs. Each tab has a JscrollPane in it, and each JScrollPane has a JTable.
The JTable is not allowed to resize its width so all the other components should arrange its width according to the JTable. For example: if the JTable's width is 200 pixels, the JScrollPane and the JTabbed should also have a width of 200 pixels. I'm using gridbaglayout, and as far as I see, in a gridbaglayout, the jtabbed changes its size acording to the jframe size, the jscrollpane changes it according to the jtabbed one, but should be in the 'reverse way'. The jscrollpane resize acording to the jtable and the jtabbed according to the jscroll.
Thanks a lot.

Hi, I don't think you can resize a JTable until and unless you add it some component (like a JScrollPane). So, there is no question of you trying to resize a JTable individually. All that you can do is, resize the JScrollPane inorder to resize a JTable. So, the first question of resizing a JScrollPane when a JTable is resized is ruled out. Now, when you resize the JScrollPane, you want to resize the tabbed pane. Yes, you can do this. But for this you might have to set the minimum size of the tabbed pane to the size of the resized scorllpane. You might have to handle the resize event.
Thanks,
Kalyan

Similar Messages

  • Problem with JPanel, JScroll and JTable

    Hi.
    On one of my Jframes, i have 3 Jpanels. There are two on one side, and one of the other which spans the height of the other two. However, it does more than span the height of the other two, it streches the height of the Jframe as it is about 300 pixels too heigh.
    I'm not sure which element is streching the JPanel, it might be either the Jpanel itself, the JScroll or the JTable. Theres alot of code, however i'm going to try and cut out the irrelevent parts.
    I call the Jpanel via:
    FarmList = new javax.swing.JPanel();
    FarmList.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Farm List", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
    FarmList.add(new GetFarms());And the code for the GetFarms() class is:
    public class GetFarms extends JPanel {
         private final int COLUMNS = 4;
         private int ROWS = 2;
         private JTable sampleJTable;
         private String[][] cells = new String[ROWS][COLUMNS];
        public static void main(String[] args) throws Exception {
            JFrame frame = new JFrame("Covenant Farm List");
              frame.add(new GetFarms());
            frame.setSize(450,150);
            frame.setVisible(true);
         public GetFarms() throws Exception {
              URL theUrl = new URL("http://www.allydm.co.uk/Covenant/farm_list.php");
              BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        theUrl.openStream()));
              String inputLine = in.readLine();
              String[] lines = inputLine.split("<br>");
              for (int i = 0; i < ROWS; i++) {
                   String[] stuff = lines.split(" ");
                   for (int j = 0; j < COLUMNS; j++) {
                        cells[i][j] = stuff[j];
              in.close();
              String[] columnNames = {"Username", "DA", "Sentry", "Last Update"};
              sampleJTable = new JTable(cells, columnNames);
              JScrollPane tablePane = new JScrollPane(sampleJTable);
    add(tablePane, BorderLayout.CENTER);
    If anyone has any ideas, on how to limit the size of the Jpanel or JScroll it'd be greatly appreciated.

    did you implement setxxxSize() methods?
    see
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

  • JScroller on JTable and table size

    Hi everyone...
    I have a small problem...i added JScrollPane to my JTable...but if i do the following...
    JScrollPane contentScroller= new JScrollPane(myJTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    myJTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);In this case scroller works great....accept if i have a smaller data set to show...for example only one column...
    Basically what i would like is to be able to set like minimum size of my JTable...is that possible...

    Oh ya...
    sorry i apologize...
    Well basically what i did is the following...
    In the constructor of my sub-class that extends JTable i set the following property:
    this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    /*...........................................................................*/ And then i also added the following code...(i created some additional methods...i dont really know if this is the right way but i didnt find anything more suitable for my problem)
    /*i set JScrollPane onto witch i added my JTable class instance, to a private JscrollPane variable*/
    public void setParentJPanel(JScrollPane parentJScrollPane){
            this.parentJScrollPane = parentJScrollPane;
    /*I only added these 3 methods cos i wanted to get the size of JScrollPane onto witch i added my JTable class instance*/
        public JScrollPane getParentJPanel(){
            return this.parentJScrollPane;
    /*this methods sort of sets all the columns to equal size witch i guess i wanted it to do...*/
        public void setAllColumnsWidth(){
            int parentWidth = this.getParentJPanel().getWidth();
            int columnNumber = this.getColumnNumber();/*method that i wrote to work with another class that works with database*/
            int columnWidth = parentWidth/columnNumber;
            for(int i=0;i < columnNumber;i++)
                this.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);     
        }Hmmm sorry again for not posting my solution...its not really that much impressive thats why i didnt post it the first time...
    Well i hope it helps....(what i needed is basically how to set columns to as equal size as possible...)

  • Last column in JTable detaches from edge of JScroll Pane

    i have a JTable in a JScrollPane which is in half of a JSplitPane.
    The table has autoResizeMode set to AUTO_RESIZE_OFF to make the horizontal scrollbar appear.
    However, when i resize the split pane to make the table bigger, the edge of the last column no longer runs to the edge of the JScrollPane, it detaches.
    What i need is for the last column to be able to expand infinitely, but when the split pane size is being reduced, for the columns to disapear off the edge of the scroll pane and the scroll bar to appear. This is a mix of AUTO_RESIZE_OFF and AUTO_RESIZE_LAST_COLUMN.

    I too had this problem. I had a method that would set the minimum size of columns based on the data within the table, etc. It seems that when you do anything to set the pref or min size of a column the horizontal scrolling gets all messed up. How I solved the problem is to basically swap the autosize method on the table back and forth whenever the parent component of the table is resized. Some example code follows.
    First, add a inner class ComponentListener on the parent component the table is in (a frame in my case, I guess this could be the scroll pane too?):
    _myFrame.addComponentListener( new ComponentAdapter()
        public void componentResized(ComponentEvent e)
            _parentResized();
    });Now the _parentResized() method that is called by the inner class looks like this:
    * Our parent container component was resized, so update how the table's
    * columns are layed out.
    private void _parentResized()
        TableColumnModel tcm = _table.getColumnModel();
        int colWidth = 0;
        for( int j = 0; j < tcm.getColumnCount(); j++ )
            colWidth += tcm.getColumn( j ).getPreferredWidth();
        // Have to check scroll for width > 0, because the first time this gets
        // called, it is 0, and that will cause the viewport to scale to fit the
        // entire table (which could be bad).  Note that this will get updated
        // if the window is resized as well.
        if( _tableScroll.getWidth() > 0 && colWidth < _tableScroll.getWidth() )
            _table.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
        else
            _table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    }What that does is whenever the table's parent component is resized it evaluates the pref width of the whole table, if it's greater than the scrollpane's width, it turns autosizing of columns off (which will make the horiz scrollbar work properly), if it is less than the scrollpane's width, it turns autosizing on. Hackish I know.
    You need to make sure to call the _parentResized() method as well whenver you do something else that might cause the pref width of the table to be resized (like you repopulate and calc pref widths, etc.)
    Hope this is of some use to you.

  • JTable in JTabbed Pane

    Hello,
    I am wondering is there anyway to create a Table View and attache that to a tab in a tabbed pane?
    I am confused, because always Table extends from JFrame. (It seems like it is a stand alone application). If I create the table this way, how can I put this in a tab of a tabbed pane?
    Lali

    You can always include a JTable in a JTabbedPane.
    A component can hold another component within it.
    Put the table view inside a JScrollPane,by which you can get a scrollable view of the JTable.

  • JTable - row selection not working + change the text format

    Hi All,
    I have written a code to display Jtable with 2 columns, 1 column to display image+text and other is multiline.
    I have used 2 different cell renderer for achiveing the same.
    Please advice on the following:
    @ When I click on row, only one column gets selected. How to fix this?
    @ Data to be displayed in rows is fetched from database. And on some STATUS value row should be in bold text or plain text. I have achieved this but withou logic to iterate over it.
    @ When user right clicks on the row allow them to set text in the row as bold or plain.(Just like we do with mails in outlook box)
    Below is the code:
    Hi All,
    I have written a code to display Jtable with 2 columns, 1 column to display image+text and other is multiline.
    I have used 2 different cell renderer for achiveing the same.
    Please advice on the following:
    @ When I click on row, only one column gets selected. How to fix this?
    @ Data to be displayed in rows is fetched from database. And on some STATUS value row should be in bold text or plain text. I have achieved this but withou logic to iterate over it.
    @ When user right clicks on the row allow them to set text in the row as bold or plain.(Just like we do with mails in outlook box)
    Below is the code:package jtab;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import jtab.TestIcon.iconRenderer;
    public class SampleJtable {
         JFrame frame;
         JTable table;
         JScrollPane panel;
         JPopupMenu popupMenu ;
         public static void main(String[] args) {
              SampleJtable sample = new SampleJtable();
              sample.loadGUI();
         public void loadGUI(){
              frame = new JFrame("Sample Program for Font and ImageIcons");
              frame.setContentPane(panel);
              frame.setSize(550,250);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         public SampleJtable(){
              BufferedImage images[] = new BufferedImage[1];
              try{
                   images[0] = javax.imageio.ImageIO.read(new File("C:/go.gif"));
              }catch(Exception e){
                   e.printStackTrace();
              final Object data [][] = {{"Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe \n P",new ImageStore(images[0],"Bourquin Rene")},
                        {"Auftrag \n test \n \n 1957,Grenchen Kaufe \n N",new ImageStore(images[0],"Bourquin Rene")}};
              String colIds [] ={"Beschrebung","Von"};
              DefaultTableModel model = new DefaultTableModel(data, colIds) {  
    public Class getColumnClass(int column) {  
    return data[0][column].getClass();
              /*Vector<Object> rowData1 = new Vector(2);
              rowData1.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
              rowData1.add(new ImageStore(images[0],"Bourquin Rene"));
              Vector<Object> rowData2 = new Vector(2);
              rowData2.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
              rowData2.add(new ImageStore(images[0],"Bourquin Rene"));
              Vector<Vector> rowData = new Vector<Vector>();
         rowData.addElement(rowData1);
         rowData.addElement(rowData2);
              Vector<String> columnNames = new Vector<String>();
         columnNames.addElement("Beschrebung");
         columnNames.addElement("Von");     
              DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {  
              table = new JTable(model);
              table.setDefaultRenderer(ImageStore.class, new ImageRenderer());          
              table.getTableHeader().getColumnModel().getColumn(0).setCellRenderer(new LineCellRenderer());
              table.setRowHeight(84);
              panel = new JScrollPane(table);
              panel.setOpaque(true);
         class ImageRenderer extends DefaultTableCellRenderer {  
         public Component getTableCellRendererComponent(JTable table,
         Object value,
         boolean isSelected,
         boolean hasFocus,
         int row, int column) {  
         super.getTableCellRendererComponent(table, value, isSelected,
         hasFocus, row, column);
         ImageStore store = (ImageStore)value;
         setIcon(store.getIcon());
         setText(store.text);
         return this;
         class ImageStore {  
         ImageIcon icons;
         String text;
         int showingIndex;
         public ImageStore(BufferedImage image1,String s) {
         icons = new ImageIcon(image1);
         showingIndex = 0;
         text = s;
         public ImageIcon getIcon() {  
         return icons;
         public void toggleIndex() {  
         showingIndex = (showingIndex == 0) ? 1 : 0;
         class LineCellRenderer extends JEditorPane implements TableCellRenderer {
              public LineCellRenderer() {           
              setOpaque(true);
              setContentType("text/html");          
              public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
              //System.out.println("Whats in value = "+ value.toString());
              String [] strArray = value.toString().split("\n");
              String rtStr = null ;
              System.out.println("TYPE+ "+ strArray[strArray.length-1].toString());
              String val = strArray[strArray.length-1].toString().trim();
              if (val.equalsIgnoreCase("N")){
                   System.out.println("TYPE+ IS NEW");
                   rtStr = "<html><head></head><body><b><div style=\"color:#FF0000;font-weight:bold;\">" + strArray[0] + "</div>" +
                             " <div style=\"color:#0000FF;font-weight:bold;\">" + strArray[1] + "</div>" +
                             "<div style=\"color:#0000FF;font-weight:bold;\">" + strArray[2] + "</div>" +
                             "<div style=\"color:#0000FF;font-weight:bold;\">" + strArray[3] + "</div>" +
                             "</b></body></html>";
              else {
                   System.out.println("TYPE+ IS PENDING");
                   rtStr = "<html><head></head><body><div style=\"color:#FF0000;\">" + strArray[0] + "</div>" +
                   " <div style=\"color:#0000FF;\">" + strArray[1] + "</div>" +
                   "<div style=\"color:#0000FF;\">" + strArray[2] + "</div>" +
                   "<div style=\"color:#0000FF;\">" + strArray[3] + "</div>" +
                   "</body></html>";
              setText(rtStr);
              return this;

    Posting code again........
    package jtab;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import jtab.TestIcon.iconRenderer;
    public class SampleJtable {
    JFrame frame;
    JTable table;
    JScrollPane panel;
    JPopupMenu popupMenu ;
    public static void main(String[] args) {
    SampleJtable sample = new SampleJtable();
    sample.loadGUI();
    public void loadGUI(){
    frame = new JFrame("Sample Program for Font and ImageIcons");
    frame.setContentPane(panel);
    frame.setSize(550,250);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public SampleJtable(){
    BufferedImage images[] = new BufferedImage[1];
    try{
    images[0] = javax.imageio.ImageIO.read(new File("C:/go.gif"));
    }catch(Exception e){
    e.printStackTrace();
    final Object data [][] = {{"Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe \n P",new ImageStore(images[0],"Bourquin Rene")},
    {"Auftrag \n test \n \n 1957,Grenchen Kaufe \n N",new ImageStore(images[0],"Bourquin Rene")}};
    String colIds [] ={"Beschrebung","Von"};
    DefaultTableModel model = new DefaultTableModel(data, colIds) {
    public Class getColumnClass(int column) {
    return data[0][column].getClass();
    /Vector<Object> rowData1 = new Vector(2);
    rowData1.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
    rowData1.add(new ImageStore(images[0],"Bourquin Rene"));
    Vector<Object> rowData2 = new Vector(2);
    rowData2.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
    rowData2.add(new ImageStore(images[0],"Bourquin Rene"));
    Vector<Vector> rowData = new Vector<Vector>();
    rowData.addElement(rowData1);
    rowData.addElement(rowData2);
    Vector<String> columnNames = new Vector<String>();
    columnNames.addElement("Beschrebung");
    columnNames.addElement("Von");
    DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
    table = new JTable(model);
    table.setDefaultRenderer(ImageStore.class, new ImageRenderer());
    table.getTableHeader().getColumnModel().getColumn(0).setCellRenderer(new LineCellRenderer());
    table.setRowHeight(84);
    panel = new JScrollPane(table);
    panel.setOpaque(true);
    class ImageRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
    ImageStore store = (ImageStore)value;
    setIcon(store.getIcon());
    setText(store.text);
    return this;
    class ImageStore {
    ImageIcon icons;
    String text;
    int showingIndex;
    public ImageStore(BufferedImage image1,String s) {
    icons = new ImageIcon(image1);
    showingIndex = 0;
    text = s;
    public ImageIcon getIcon() {
    return icons;
    public void toggleIndex() {
    showingIndex = (showingIndex == 0) ? 1 : 0;
    class LineCellRenderer extends JEditorPane implements TableCellRenderer {
    public LineCellRenderer() {
    setOpaque(true);
    setContentType("text/html");
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println("Whats in value = " value.toString());
    String [] strArray = value.toString().split("\n");
    String rtStr = null ;
    System.out.println("TYPE " strArray[strArray.length-1].toString());
    String val = strArray[strArray.length-1].toString().trim();
    if (val.equalsIgnoreCase("N")){
    System.out.println("TYPE IS NEW");
    rtStr = "<html><head></head><body><b><div style=\"color:#FF0000;font-weight:bold;\">" strArray[0] "</div>"
    " <div style=\"color:#0000FF;font-weight:bold;\">" strArray[1] "</div>"
    "<div style=\"color:#0000FF;font-weight:bold;\">" strArray[2] "</div>"
    "<div style=\"color:#0000FF;font-weight:bold;\">" strArray[3] "</div>"
    "</b></body></html>";
    else {
    System.out.println("TYPE+ IS PENDING");
    rtStr = "<html><head></head><body><div style=\"color:#FF0000;\">" strArray[0] "</div>"
    " <div style=\"color:#0000FF;\">" strArray[1] "</div>"
    "<div style=\"color:#0000FF;\">" strArray[2] "</div>"
    "<div style=\"color:#0000FF;\">" strArray[3] "</div>"
    "</body></html>";
    setText(rtStr);
    return this;
    }

  • Trouble understanding JTable renderers

    I dont properly understand how to JTable.
    In the application I'm writing, I have on main JFrame, with a menu.
    Onto this I load a jTabbed pane and then onto this a JTable , with
    some data loaded from a file , some coulmns are text , others integers
    floats and theres one date column
    I've successfully set up a TableModel extending AbstractTableModel
    as a separate class java file. I can set column widths ok too.
    But I cant get the renderer working , the numeric coumns are left aligned.
    Question 1 :How do I get a column of numeric data in a JTable to be right aligned? Some examples I have found seem to refer to specific cells eg
    // in the custom renderer...
    if(value instanceof Double)
    setHorizontalAlignment(SwingConstants.RIGHT);
    setText(value);
    I've also read this sites JTable tutorial but still dont understand the
    renderer bit.
    Question 2 : where do I put the renderer code, in with the table model
    class file , or in my main application (where I define the column widths)?
    [The JDK is 1.4, the OS is win 98.]
    Thanks in advance for any help
    Mike2z

    HONK !
    Thanks for the reply. The code
    public Class getColumnClass(int c)
    switch (c)
    case 0: return Integer.class;
    case 1: return String.class;
    case 2: return String.class;
    case 3: return String.class;
    case 4: return String.class;
    case 5: return String.class;
    case 6: return Integer.class;
    case 7: return Float.class;
         case 8: return Float.class;
    case 9: return Float.class;
    case 10: return Floatclass;
    default : return getValueAt(0, c).getClass();
    // return getValueAt(0, c).getClass();
    // return Object.class;
    seems to be the key. When I use that (instead of either of the commented
    out lines I was trying before) it works in that numbers are right
    aligned.
    However when I attemp to right scroll on the scroll pane I get a garbled display and the error :
    java.lang.IllegalArgumentException: Cannot format given Object as a Number
         at java.text.NumberFormat.format(NumberFormat.java:219)
         at java.text.Format.format(Format.java:133)
         at javax.swing.JTable$DoubleRenderer.setValue(JTable.java:3348)
         at javax.swing.table.DefaultTableCellRenderer.getTableCellRendererComponent(DefaultTableCellRenderer.java:160)
         at javax.swing.JTable.prepareRenderer(JTable.java:3682)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1149)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:537)
         at javax.swing.JComponent.paint(JComponent.java:804)
         at javax.swing.JComponent.paintChildren(JComponent.java:643)
         at javax.swing.JComponent.paint(JComponent.java:813)
         at javax.swing.JViewport.paint(JViewport.java:707)
         at javax.swing.JComponent.paintChildren(JComponent.java:643)
         at javax.swing.JComponent.paint(JComponent.java:813)
         at javax.swing.JComponent._paintImmediately(JComponent.java:4642)
         at javax.swing.JComponent.paintImmediately(JComponent.java:4464)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:404)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:443)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:190)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    If I just use
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();          // this
    // return Object.class;          // or this
    I can right scroll without that error appearing, but am back to the original problem of left aligned numeric data.
    Don't suppose you encountered the same problem?
    Mike2z

  • JScroller problem

    Hello,
    I have had this proble for a week now and I cannot figure out what is wrong. Whenever I run this code without adding the JScroller there is no problem. As soon as I add the JScroller, I get swing run time errors. Can anyone please help me ? I am a comment on the line that causes the trouble. Its near the end.
    Thanks
    Michael
    package test5;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.table.*;
    import java.util.*;
    public class clientgui extends JFrame{
    private JButton client_open; //
    private JButton client_refresh; //
    private JButton client_search; //
    private JButton client_quit; // GUI Components for various purposes..
    private JButton client_view_files; //
    private JTable client_listing; //
    private JScrollPane client_scroller; //
    int count = 0;
    Container contentpane; // For the placeing the GUI Componments
    JLabel copy;
    TableModel default_table; //
    String names[] = {"Users Connected"}; // For JTable GUI Component
    Object data[][] ={{null},{null},{null},{null},{null},{null}, {null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null},{null}};
    private URLConnection urlconnection; //
    private InputStream url_inputstream; // For Connecting and gaining the information..
    private Socket client_socket;
    boolean go_on = true;
    boolean check = true;
    Vector values = new Vector();
    String information[][];
    int g;
    add_on connection;
    public clientgui(String param, String us, String fs, String present_users[][])
    try{
    contentpane = getContentPane();
    contentpane.setLayout(null); // Setting the Layout to Absolute Layout..
    copy = new JLabel("P2P FileSharing");
    copy.setBounds(20,5,200,15);
    contentpane.add(copy);
    client_open = new JButton("Open"); // Initializing the GUI Component.
    client_open.setMnemonic('O'); // Setting the Mnemonic..
    client_open.setBounds(20,20,80,35); // Positioning the GUI Component.
    client_refresh = new JButton("Refresh"); // Initializing the GUI Component.
    client_refresh.setMnemonic('R'); // Setting the Mnemonic..
    client_refresh.setBounds(100,20,80,35); // Positioning the GUI Component.
    client_search = new JButton("Search"); // Initializing the GUI Component.
    client_search.setMnemonic('S'); // Setting the Mnemonic..
    client_search.setBounds(180,20,80,35); // Positioning the GUI Component.
    client_view_files = new JButton("View Files"); // Initializing the GUI Component.
    client_view_files.setMnemonic('V'); // Setting the Mnemonic..
    client_view_files.setBounds(260,20,100,35); // Positioning the GUI Component.
    client_view_files.setEnabled(false);
    client_quit = new JButton("Quit"); // Initializing the GUI Component.
    client_quit.setMnemonic('Q'); // Setting the Mnemonic..
    client_quit.setBounds(360,20,80,35);// Positioning the GUI Component.
    default_table = new AbstractTableModel()
    // These methods always need to be implemented.
    public int getColumnCount() { return names.length; }
    public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {return data[row][col];}
    // The default implementations of these methods in
    // AbstractTableModel would work, but we can refine them.
    public String getColumnName(int column) {return names[column];}
    public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
    public boolean isCellEditable(int row, int col) {return (col==4);}
    public void setValueAt(Object aValue, int row, int column) {
    data[row][column] = aValue;
    fireTableCellUpdated(row, column);
    client_listing = new JTable(default_table);
    client_listing.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    client_listing.getTableHeader().setReorderingAllowed(false);
    client_listing.setBounds(10,55,440,300);
    client_listing.setGridColor(new Color(255,255,255));
    client_listing.setBackground(new Color(255,255,255));
    client_view_files.setEnabled(true);
    client_scroller = new JScrollPane();
    client_scroller.setBounds(10,55,440,300);
    client_scroller.setViewportView(client_listing);// Adding the Table...
    contentpane.add(client_scroller); // PROBLEM LINE
    contentpane.add(client_open); //
    contentpane.add(client_refresh); //
    contentpane.add(client_search); // Adding the GUI Buttons.....
    contentpane.add(client_view_files); //
    contentpane.add(client_quit);
    setSize(550,550);
    catch(Exception e)
    System.out.println("Error gui "+e.getMessage());
    public static void main(String args[])
    String p="search";
    String u="pic.jpg";
    String f="pic.jpg";
    String ps[][]={{" "," "}};
    clientgui g=new clientgui(p,u,f,ps);
    g.show();
    }

    Cross-posting nitwit shall not be tolerated! NO POSTS FOR YOU!

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Any why to force a JTable to rerender

    in my application i used a progress bar in a Jtabe cell renderer
    and a thread that chack for download progress
    evrey second i am setting the data in the table for progress changes
    and trying to paint the tree again
    i am calling to repaint() ,revalidate() ,validate() on the table
    but the renderer wont paint again.....
    how can i tell the tree to paint a specipic row / a wole tree
    again using the cell renderer?
    thanks

    in my application i used a progress bar in a Jtabe
    cell renderer
    and a thread that chack for download progress
    evrey second i am setting the data in the table for
    progress changes
    and trying to paint the tree againTree or table?
    >
    i am calling to repaint() ,revalidate() ,validate()
    on the table
    but the renderer wont paint again.....
    how can i tell the tree to paint a specipic row / a
    wole tree Tree or table?
    Remember, a cell renderer is little more than a rubber stamp. You make it look like you want and then return it. There is no reason for it to remember what it looked like the last time it was rendered.
    Jim S.
    ================
    import java.awt.Component;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    public class ProgressRendererTest {
        private JTable table;
        Runner[][] data = new Runner[3][3];
        public ProgressRendererTest() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Random r = new Random();
            String[] columnNames = new String[3];
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    data[i][j] = new Runner(r.nextInt(60) + 1);
                columnNames[i] = "Column " + i;
            table = new JTable(data, columnNames);
            table.setDefaultRenderer(Object.class, new ProgressRenderer());
            f.add(new JScrollPane(table));
            f.setSize(800,600);
            f.setVisible(true);
            Thread t = new Thread(new Runnable() {
                public void run() {
                    while(true) {
                        for (int i = 0; i < 3; i++) {
                            for (int j = 0; j < 3; j++) {
                                data[i][j].increment();
                        table.repaint();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ie) {
                            ie.printStackTrace();
            t.start();
        public static void main(String[] args) {
            new ProgressRendererTest();
        private static class ProgressRenderer extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent(final JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                Runner r = (Runner)value;
                JProgressBar pb = new JProgressBar(0,r.getTotalRunTime());
                pb.setStringPainted(true);
                pb.setString(r.getCurrentRunTime() + " of " + r.getTotalRunTime());
                pb.setValue(r.getCurrentRunTime());
                return pb;
        private class Runner {
            private int totalRunTime;
            private int currentRunTime;
            Runner(int runTime) {
                this.totalRunTime = runTime;
            public int getCurrentRunTime() {
                return this.currentRunTime;
            public int getTotalRunTime() {
                return this.totalRunTime;
            public void increment() {
                if (currentRunTime < totalRunTime) {
                    currentRunTime++;
    }

  • JTable Differences between 1.2.2 and 1.3.1 ?

    All,
    I have an application that has worked happily in JDK 1.2.2 for 3 years. I am trying to upgrade the base SDK to 1.3.1. However, after compiling everything with 1.3.1_06 most of the headers on my JTables do not appear. Stangely, in some cases the headers do appear. I have compared the code between the headers that do appear and those that don't and I can see no difference.
    Some basic background so that I don't get trivial responsed here:
    1) Reiterate - everything works fine in 1.2.2.
    2) I am not new to JTable so reminging me that I need to put it on a JScroll pane is unecessary.
    3) All of our tables use a custom TableModel that extends AbastractTableModel. The CUstome table model implements getValueAt(), setValueAt(), etc.
    4) All of our tables use a custom ColumnModel that extends DefaultTableColumnModel.
    5) All of our tables are placed on a JScrollPane - Sometimes using new JScrollPane(myTable)and sometimes using myScrollPane().getViewPort().add(myTable)For the tables that do not show headers switching between these methods doesn't seem to help.
    Has anyone else run into this issue? There are lots of postings here about Header visibility but none seem to apply directly to this issue.
    One final note - the headers do not appear in 1.4.x, either.

    OK. After several hours of trying to determine what is causing the headers to disappear I have figures it out. In many of our tables we have a leading column with a row number in it. It's just like every other column except the header value is set to "". For some reason of the first column header value is an empty string then the header size (height) is set to be very, very small (like 1 pixel high). If I change the first row header value to " " instead everything works as before.
    Can somebody explain which Swing component is determining the size(height) of the header row based on only the first column header value ?

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • JTable - Can I change the color of the text on a row by row basis?

    Hi All,
    I'm redoing a bit of old uni coursework (to model a stockmarket, stock ticker server & stock ticker application) to brush up my Java skills (esp Swing and Event Handling) and am programming the UI by hand using Swing (its the only way to learn something....(I've certianly nailed Layout Management!!))
    In the stocktickerserver GUI I'm using a JTable to display the details about stocks.
    The user can select a stock and view the details of the stock in another frame. In one panel in the JFrame I've got a JTable listing the history items for the stock (Price, Change, Date).
    Is it possible to color the rows of the JTable according to the value of the change column (or at least the value I insert there)?
    e.g
    if (change > 0){
    Blue;
    else{
    if (change < 0){
    Red;
    else{
    Green;
    I'm completly ignorant on how to achieve this (or even if its possible at all) so all your ideas welcome.
    Any help much appreciated
    Pete
    P.S.
    The Stock History is a class that I store in a [private] Vector in the Stock Class.
    For the selected Stock I loop through this vector getting the items (using various accessor methods)
    I extract the values from the return StockHistory object and build a DefaultTableModel from these
    Then I call JTable.setModel(theModel) to build the table

    implement TableCellRenderer and change foreground of the Renderer in the method getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) . Install this renderer to your table.

  • How to select a specific cell in a JTable?

    Hi there,
    in a JTable, I would like to select a specific cell (to highlight it) from a JButton.
    Here a sample code...
    Who could help me to fill it?
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableSelection{
        public static void main (String args[]) {
          JFrame frame = new MyFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.show();
    class MyFrame extends JFrame{
      public MyFrame(){
        setTitle("TableSelection");
        setSize(WIDTH,HEIGHT);
        DefaultTableModel myModel = new DefaultTableModel(2,2);
        JTable myTable = new JTable(myModel);
        myTable.setCellSelectionEnabled(true);
        JButton button00 = new JButton("select 0,0");
        button00.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (0,0)");
         //--- what code is required to select the cell(0,0)?
        JButton button11 = new JButton("select 1,1");
        button11.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (1,1)");
         //--- what code is required to select the cell(1,1)?
        Box myBox = new Box(BoxLayout.Y_AXIS);
        myBox.add(new JScrollPane(myTable));
        myBox.add(button00);
        myBox.add(button11);
        getContentPane().add(myBox, BorderLayout.CENTER);
      private static final int WIDTH=200;
      private static final int HEIGHT=200;
    }Thanks a lot for your help.
    Denis

    Use the addColumnSelectionInterval(int index1, int index2)method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addColumnSelectionInterval(int,%20int)
    and the addRowSelectionInterval(int index1, int index2) method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addRowSelectionInterval(int,%20int)
    Hope that helped.
    afotoglidis

  • Create a JTable based on an ArrayList containing instances of a class.

    I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.
    The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
         public TableDemo() {
              super(new GridLayout(1, 0));
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Add the scroll pane to this panel.
              add(scrollPane);
         class MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return list.size();
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   MyObject object = list.get(row);
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableDemo newContentPane = new TableDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // 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