Size in JTable

Hi! I have a little problem with JTables. If I want to show more than 20 files (it�s 20 because of the size of the window, this number is not important), it only shows a certain number of them, the others don�t appear. The autoscrolls field is "true", but it seems don�t work properly.
Does anybody know what�s wrong?
Thanks in advance.

hi! The scrollbars are enabled. I have increased the height in "constraints" parameters so the table is big enough to show more files, but it�s not the best thing because it only makes the table bigger, but it doesn�t have a "resize" behaviour", and that�s what i�m looking for.
Thanks.

Similar Messages

  • ComboBox size in JTable

    How do you set the size of a combobox inside a JTable cell. I have used setPreferredWidth but the ccombo box is still huge. I have done searches and not found any answers.
    Thanks

    I've always let the UI take care of it. I don't set the minimum, maximum or preferred sizes and the UI sets the size to the size fo the cell.

  • Increased Font size in JTable 's printout

    Hi everybody,
    Can anybody help me out. When I use Java Print classes to print a Jtable the Font size appears to be 125% bigger.

    http://search.java.sun.com/search/java/index.jsp?and=font+jtable&phr=&qt=&not=&field=title&since=&nh=10&col=javaforums&rf=0&Search.x=37&Search.y=16

  • Setting size of JTable columns

    Hi everybody,
    Can anyone help me ?
    How can I set a column widths of a JTable, but also allow the user to resize them ?
    I tried with a code like
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
       if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setPreferredWidth(preferedSizeArray);
    But it doesn't work :(
    When i do [ define the minWidth and maxWidth ]
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
        if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setMinWidth(preferedSizeArray);
    tableColumnModel.getColumn(i).setMaxWidth(preferedSizeArray[i]);
    Columns's sizes are exactly what i want but ... the colums are no more resizable.
    So,
    if anyone can help me and tell me how can i set a predefined size for some colums and also allow the user to resize them ... that would be kind from him.
    Thanks

    Hi guys,
    It's me again ... but I tried your tricks and they don't work :(
    Look this example :
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    public class JTableResizing extends JFrame implements ActionListener {
        private JScrollPane scpnl = new JScrollPane();
        private JButton btnClose = new JButton();
        Object[][] data={   new Object[]{"Hi", "everybody", "this is ", "a row"},
                            new Object[]{"and ", "this ", "is the second", "row"},
                            new Object[]{"of a", "very ","usefull","jtable"}
        Object[] columnNames={"Column1", "Column2", "Column3", "Column4"};
        TableModel dataModel=new DefaultTableModel(data, columnNames);
        private JTable jTable = new JTable(dataModel);
        public JTableResizing() {
            try {
                /* We don't care about this code !! just see the code below !
                 * It has been made really quick [and dirty :D]
                this.setSize(new Dimension(530, 400));
                this.getContentPane().setLayout(new GridBagLayout());
                btnClose.setText("close");
                btnClose.addActionListener(this);
                scpnl.getViewport().add(jTable, null);
                this.getContentPane().add(scpnl,    new GridBagConstraints(0, 0, 1, 1, 1.0, 0.5,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.BOTH,
                                                                        new Insets(50, 50, 50, 50),
                                                                        0, 0));
                this.getContentPane().add(btnClose, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.NONE,
                                                                        new Insets(0, 0, 20, 0),
                                                                        0, 0));
                /* is this really necessary ??? I really don't think so */
                JTableHeader headers = jTable.getTableHeader();
                if (headers != null) {
                    headers.setResizingAllowed(true);
                 * Start watching the code from here.
                 * I created a JTable [jTable] with n columns. Now, I want to fix
                 * a size for some columns and the question is how ?? 
                 * Maybe the easiest way is to create a method !!
                 setColumnsSizes(jTable, new int[]{0, 100, 0, 50});
            } catch(Exception e) {
                e.printStackTrace();
        /* I know, the code is not the best but I don't care !! This is a quick
         * and dirty sample code to make you understand my problem ...*/
        public static void setColumnsSizes(JTable jTable, int[] columnsSizes) {
            /* look the array supplied above.  columnsSizes =  int[]{0,100,0,50}
             * but any array can be supplied !!
             * This one means that the second and the fourth columns should take
             * resectively a width of 100 and 50 and the two others columns
             * the first one and the third one, fill as much as possible depending on
             * the available space in the scrollpane.
             * Also, when I resize the frame, the scrollpane is resized
             * (look the gridbagconstraints above, and also here columns with
             * no prefered size must be
            /* Which mode should I suplpy ? I need an autoresize only for columns
               where no prefered size has been defined and I don't think it exists */
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            TableColumnModel tableColumnModel = jTable.getColumnModel();
            for (int i=0; i < columnsSizes.length; i++) {
                if (columnsSizes[i] > 0) {
                    /* If I define a minimum width, the colum will be resizeable but,
                       we will be unable to resize it under his minSize. This can be
                       a good behaviour !*/
                    tableColumnModel.getColumn(i).setMinWidth(columnsSizes);
    /* If I define a prefered width, I'm not sure it will be the
    width of the column.
    I mean, when I define a prefered size on a column, other
    columns are resized depending of the autoResizeMode !*/
    tableColumnModel.getColumn(i).setPreferredWidth(columnsSizes[i]);
    /* if I define a maxWidth (next line code) the column will be fixed */
    // tableColumnModel.getColumn(i).setMaxWidth(columnsSizes[i]);
    public static void main(String[] args) {
    JTableResizing jTableResizing = new JTableResizing();
    jTableResizing.setLocationRelativeTo(null);
    jTableResizing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jTableResizing.setVisible(true);
    * method performed when clicking on button close
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    Copy, paste and run it and you'll understand the problem.
    Also, try to read comments I added (I think they are understandable, although I know they are full of grammar mistakes, but this is another question ... )
    Thanks for your help.
    And may the force be with you

  • Set column's size in JTable?

    This is my code:
    TableColumn col = tbl.getColumnModel().getColumn(3);
    col.setPreferredWidth(50);
    TableColumn col1 = tbl.getColumnModel().getColumn(2);
    col1.setPreferredWidth(10);
    it has no effect, do you know Why?

    tbl.getColumn(Object);
    What is Object here?
    I tried 2 (int), "UserName" (String), all not true.
    What is Object here?You can set an identifier to TableColumns,
    which you probaly didn't do. To get a column at specific index, call
    tbl.getColumnModel().getColumn(int index)

  • How to print a JTable  in Java Swing ?

    Hi,
    I have an application written in java swing.Now I want to write a print module that prints some details.The details includes the JTextArea and JTable that changes in size dynamically.One solution i found is to put them in a panel and print that panel.But it is static.The size of JTable and JTextArea changes, according to the given input.Please give me a solution for this.

    Printing is a bit of a nightmare, actually. Most of the trouble is layout. Basically a Printable is passed a page number and a graphics context and has to work out what components go on that page and where. It can't depend on the pages being requested in sequence.
    You can call getPrintable from a JTable, and you can call that through your own Printable in order to add extra pages. However you can't ask a Printable how many pages it's going to produce, you just have to invoke it and see if it returns a code to say that the page is out of range.
    And the Printable JTable generates is very limited, the table has to occupy full pages, you can't tell it to start in a different place on the first page, or find out how much space it's used on the last page. The headers and footers generate JTable's own idea of a page number, not yours.
    You can call print() on most Swing components, but you'll need to set their size and location first, and/or mess with the transformation in the graphics context.

  • Autofit JTable column headers

    I have a problem. I am using eclipse. What i want to do is that in a Jtable, i want such a mechanism that no matter what the table headers are(any font, size), the jtable adjusts the column width to show the whole table header. The headers and the fonts are read from a file.
    presently i m doing this:
    //used to set the column widths
    FontMetrics metrics = tbl.getFontMetrics(tbl.getFont());
    // Set column widths
    int tempWidth;
    for (int i=0; i<columnNames.length ; i++)
    tempWidth = metrics.stringWidth(tbl.getColumnName(i))+ (2 * tbl.getColumnModel().getColumnMargin());
    tcm.getColumn(i).setPreferredWidth(tempWidth);
    tcm.getColumn(i).setPreferredWidth(columnNames.length()*7);
    The problem is that this does not work for all fonts.
    Can ne 1 plz provide sample code???

    Here's the full code I posted before to do this.
    It resizes the entire JTable to fit the column size, no matter what font properties, and
    optionally includes using the column header as well.
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=606240
    regards,
    Owen

  • MySQL+JTable, AbstractTableModel - solution v.0.1 beta

    Hi everybody, My name is Sergey, I am a student from Russian Federation, Moscow.
    I spent days and nights trying to find how to connect JTable, DB tables.
    To tell you the truth, I visited many russian and english-lang forums. But I didn't get somewhere goog answer. that is terrible.
    Seems like nobody nows how to do simple things.
    So, I've started to do on my own. And I suggest you the first version.
    Ofcourse it is rather raw, but it works.
    Sometimes I was really angry when people suggested others untested and foolish code. With mistakes.
    what we need:
    JDBC adapter - mysql.com (you canget it)
    MySQL server (must be started)
    DB
    Tables in DB
    NetBeans 5.5 - netbeans.org
    NB MySQL server on localhost, thisway you will not need to dig mysql config files
    Create new project application
    Add mysql driver jar file to project library (it is in project window)
    create two classes and enjoy
    import java.sql.*;
    import java.util.Collections;
    import java.util.List;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.table.AbstractTableModel;
    import java.util.Collections;
    * @author SShpk
    //we are going to override methods of AbstracTableModel Class
    /**This class forms view of DB table which will be loaded into JTable swing component*/
    public class JTableAdapter extends AbstractTableModel{
            //my table name
            private String tableName ="Sheet";
         //frame for error exception output
            private JFrame jframeError = new JFrame("Connection error");
            //variables for transactions
            private Connection connection;
            private Statement  statement;
            private ResultSet  resultSet;
            private ResultSetMetaData metaData;
            //names of colums --- will get them from DB table
            public  String[]   columnNames;
            //this Vector will  keep rows of table
            private Vector     rows = new Vector();
            private int i;
            private String t="";
        /** Creates a new instance of JTableAdapter */
        public JTableAdapter(String url, String driverName, String user, String password) {
            jframeError.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//frame for showing errors
            //this String var I use to avoid problem with Date/Datestamps e.t.c. like �0000-00-00�
         //because java converts them to NULL. This is terrible fact. Do not lose this comment!
            String overrideBADDATE="zeroDateTimeBehavior=convertToNull&";
         //let�s put together all params
            //common view is: :jdbc:mysql://yourhost.com:port_num/NameofYourDB?<property&>
            t=url+overrideBADDATE+"user="+user+"&password="+password;
            try{     //trying to load driver
                Class.forName(driverName);
                connection=DriverManager.getConnection(t);
                statement = connection.createStatement();
                                    //this commented code will be useful for you in debug proccess.
                                    //it will give you list of all loaded drivers to driver managers
                                    //so you will be able to see is your jdbc driver loaded or not.
                                     try{
                                          List drivers = Collections.list(DriverManager.getDrivers());
                                          for(int i=0;i<drivers.size();i++){
                                              Driver driver = (Driver)drivers.get(i);
                                              String driverName1 = driver.getClass().getName();
                                              System.out.println("Driver "+i+":::"+driverName1);
                                     }catch(Exception e){
                                          System.out.println(e);
                                     }//catch in try
            }//try
            //let's catch exceptions.
            //see messages to get the meaning of exception
            catch(ClassNotFoundException ex){
                         JOptionPane.showMessageDialog(jframeError,
                                                        "Error occurred during driver load"+driverName,
                                                        "Driver load error:"+ex.getMessage(),
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
            }//catch1
            catch(SQLException ex){
                         JOptionPane.showMessageDialog(jframeError,
                                                        "Error connecting DB"+url,
                                                        "DB Connection error:"+ex.getMessage(),
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
            }//catch2
        //executing SELECT query to fill our table
         executeQuery("SELECT * FROM " + this.tableName);  
        }//constructor
        /**method sends SELECT query and parses result of this query*/
        public void executeQuery(String query){
            //testing for alive connection
            if(connection== null || statement == null){
                            JOptionPane.showMessageDialog(jframeError,
                                                        "Error occurred during query post",
                                                        "DB connection error",
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
         //let�s parse result of query
            try{
                resultSet = statement.executeQuery(query);
                //get num of columns in table   /***/getColumnCount()
                //get names of columns          /***/getColumnLabel(i+1)
                metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
               //getting names of DB table columns
                columnNames = new String[numberOfColumns];
                for(i=0;i<numberOfColumns;i++){
                        columnNames= metaData.getColumnLabel(i+1);
    }//for
    Object testnulledobj;
    rows = new Vector();
    //from the beginning of resultSet up to the END
    while (resultSet.next()){
    //each row of DB table is Vector
    Vector newRow = new Vector();
    for (i=1; i<= getColumnCount();i++){
    testnulledobj=resultSet.getObject(i);
         //this IF statement I will develop
    //to output NULL-object Date (like Date field = 0000-00-00)
    if(resultSet.wasNull()){
    testnulledobj=new String("");
    newRow.addElement(testnulledobj);
    }//for
              //row from DB is completed. Every row will be in Vector of Rows.
              //I hope you got my idea.
              //We collect row cells of DB table row in Vector
              //Then we put this Vector into another Vector, which consists of DB rows
    rows.addElement(newRow);
    }//while
    //table is changed
    fireTableChanged(null);
    }//try
    catch(SQLException ex){
    JOptionPane.showMessageDialog(jframeError,
    "Error occurred during query result parsing",
    "Data accept error",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    }//executeQuery
    /**cell of table editable or not?*/
    public boolean isCellEditable(int row,int column){
    /*Testing field(aka column) property. We get it from DB.
    try{
    return metaData.isWritable(column+1);
    }//try
    catch(SQLException e){
    return false;
    }//catch
    /****LOCKING ID FIELD***/
    if(column>0) return true;
    else return false;
    }//isCellEditable
    //these three methods very simple. I think they do not need any explanations
    /**set column name in JTable*/
    public String getColumnName(int column){
    return this.columnNames[column];
    /**get quantity of rows in table*/
    public int getRowCount(){
    return this.rows.size();
    /**get quantity of columns in table*/
    public int getColumnCount(){
    return this.columnNames.length;
    /**get value from JTable cell*/
    public Object getValueAt(int aRow, int aColumn){
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    //if user edited cell (double-click on it and then went away)
    //we need to update DB table and JTable also.
    //this is not pretty good variant, because we will flood DB with plenty of small queries.
    //the best way is to save value of "double-clicked" cell. Then we have to compare its value before
    //focus and after. If values differ, then we update DB table, else � no update
    //unfortunately I do not know how to control focus method of JTable cell
    /**update DB table cell value*/
    public void setValueAt(Object value, int row, int column){
    //Before updating DB table cell we need to update JTable cell
    Object val;
    val = tbRepresentation(column, value);
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(val,column);
    //Now it's time to update DB table
    try{
    //get name of column in DB table (our JTable has the same column names)
    //it's possible to give them normal names instead of user_id,user_name e.t.c.
    //I am sure, user of your app will prefer to see normal names of columns, not like listed before
    String columnName = getColumnName(column);
    //This is very bad example of update query.
    //You have to determine automatically key field. but still I didn't find how to do that
    //But it's possible to do through metadata. I am sure.
    //Just need some more time
    //When I am designing DB I prefer to name key field in each table as "ID"
    String query = "UPDATE "
    tableName
    " SET "+columnName+" = "+"'"+dbRepresentation(column,getValueAt(row, column))+"'"+
    " WHERE ID = "+dbRepresentation(0,getValueAt(row, 0));
    //extremely important string for debug
    System.out.println("UPDATE QUERY:::"+query);
    //executing update query
    PreparedStatement pstmt = connection.prepareStatement(query);
    pstmt.executeUpdate();
    }//try
    catch(Exception ex){
    JOptionPane.showMessageDialog(jframeError,
    "������ ��� ���������� ������ � ������� ��",
    "������ �������� ��� ���������� ������ � ��",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    }//catch
    }//setValueAt
    //Next two methods are very neccessary. And they need accurate testing
    //they convert DB datatypes into java datatypes and backwards
    /**convert SQL (MySQL in this case) datatypes into datatypes which java accepts*/
    public Object tbRepresentation(int column, Object value) throws NumberFormatException{
    Object val;
    int type;
    if(value == null){
    return "null";
    }//if null
    try{
    type = metaData.getColumnType(column+1);
    }//try
    catch (SQLException e){
    JOptionPane.showMessageDialog(jframeError,
    "Error occured during Table update",
    "Error occured during DB table field type get",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    return value.toString();
    }//catch
    switch(type){
    case Types.BIGINT:
    return val = new Long(value.toString());
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return val = new Integer(value.toString());
    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
    return val = new Double(value.toString());
    case Types.CHAR:
    case Types.BLOB:
    case Types.VARCHAR:
    case Types.LONGNVARCHAR:
    return val = new String(value.toString());
    case Types.DATE:
    return val = new String(value.toString());
    default: return val = new String(value.toString());
    }//switch
    }//tbRepresentation
    /**conver Java datatypes into SQL (MySQL) datatypes*/
    public Object dbRepresentation(int column, Object value){
    Object val;
    int type;
    if(value == null){
    return "null";
    }//if null
    //my preparations for accurate work with "nulled" dates/time/e.t.c
    //this IF statement doesn't play any important role
    String testbaddate="0000-00-00";
    if(value.toString().equals(testbaddate)){
    return value.toString();
    try{
    type = metaData.getColumnType(column+1);
    }//try
    catch (SQLException e){
    return value.toString();
    }//catch
    switch(type){
    case Types.BIGINT:
    return val = new Long(value.toString());
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return val = new Integer(value.toString());
    case Types.DECIMAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    return val = new Double(value.toString());
    case Types.VARCHAR:
    case Types.CHAR:
    return val = new String(value.toString());
    case Types.DATE:
    return val = new String(value.toString());
    default: return val = new String(value.toString());
    }//switch
    }//dbRepresentation
    //my preparations to read from SELECT query result
    //"nulled" dates/time/e.t.c.
    private Object testObject(Object obj){
    Object val= new String("");
    if(obj==null) return new String(val.toString());
    else return obj;
    }//class
    And other class. I will not comment it.
    It is very easy. Ask me if you want something
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class TableCreate extends JPanel{
        /** Creates a new instance of TableCreate */
        public TableCreate() {
            super(new GridLayout(1,0));
            JTable table = new JTable(new JTableAdapter("jdbc:mysql://localhost/Document?","com.mysql.jdbc.Driver","root",""));
            table.setPreferredScrollableViewportSize(new Dimension(500,210));
            JScrollPane scrollpane = new JScrollPane(table);
            add(scrollpane);
        public JPanel getJpanelTable(){
            return this;
        public static void main(String[] args){
            JFrame jframe = new JFrame("Test");
                TableCreate tcreate = new TableCreate();
                    jframe.add(tcreate.getJpanelTable());
                    jframe.pack();
                    jframe.setVisible(true);
    }//main

    So what we have:
    -DB table insert into JTable
    -Can edit values+update them in DB
    -override some common "critical points"
    What we need:
    -control row,col size in JTable
    -control column names in JTable
    -add combobox on fields which keep ID of other instance (I will give test example later)
    -add checkbox to boolean fields and to boolean fields which declared as int-family type, but use only "0" and "1" numbers
    -Add sort to JTable (to its header)
    -Add conrol buttons
    --new row
    --delete row
    --next record
    --previous record
    -Add user friendly GUI (highlight selected row e.t.c.)
    So as you can see, a lot of things to do
    I will be happy to answer all you questions
    But if you want to make me really happy- comment my post and suggest me how to refact code and approach this JTableAdapter class to reusable component (I want it to be useful in common cases when Java-specialist work with DB especially with MySQL)

  • Giving input to jtable from a database in runtime

    friends
    previously i have posted an query asking how to intilize the row size of jtable in run time for which i got good rewsponce to direct me to an page in sun/components,i read the jtable page in specifie link provided in sun,but i could not figure out how to give input to jtable from a database on runtime.In that page they have used by giving input in an array and then displaying it, by that they set the no of rows in the table ,but i want to set the row size based on number of records fetched from the oracle database.kindly guide me
    Arjun

    What you need is to develop a table model which uses a database as the data source.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data

  • JTable  - getting component width

    Hello
    I've come across a small problem I can't overcome as I'm new with Swing.
    I would like to set the initial sizes of JTable column headers using a values from array that indicate the percentage size of JTable container for every header e.i.:
    int[] columnsWidth = new int[]{20,70,5,5};   //4 columns //20%,70%,5%,5% of   JTable width
    //in MyTable constructor
                    TableColumn column = null;
              for(int i =0; i<dm.getColumnCount();i++){
                   column = getColumnModel().getColumn(i);
                      double width = (columnsWidth/100.0)* getWidth();
                   column.setPreferredWidth((int)width);
    unfortunately JComponent:getWidth() returns 0, probably because its in JTable constructor, but where can i get correct component width ?
    Thanks for your help!

    I have some code that does something close; but I don't think it's completely what you want.
    First, in our table model, we define some widths:
    private final static int[] widths = { 10, 20, 20, 10};Then, in our table class, we for each of these columns. We essentially take the width of 10, multiple by some value, and use that value. I was tryign to be able to specify widths in characters, assuming a fixed width font.
        private void setPreferredColumnWidths() {
            for (int i = 0; i < getColumnCount(); i++) {
                TableColumn col = getColumnModel().getColumn(i);
                int w = getColumnWidth(i);
                col.setPreferredWidth(w);
                col.setWidth(w);
        }We disable the resize on the table columns, as we want fixed width columns within a scrollable pane. However, if you enable auto sizing:
    setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);You'll find that the EXTRA space is alloted relative on the preferred size of those columns. It doesn't result in the exact % width you are looking for, so I don't know if that's close enough for you.

  • Dynamically resizing a jpanel

    i have a Jframe. at first i add a panel say panel 1 to it.When a button in panel 1 is pressed another panel Panel2 is loaded.inside panel2 i have Jtable...My doubt is whether it is possible to set the size of jframe or panel2 depending on the size of jtable...i have used setSize() for frame and panel.

    thank you for da reply.I want the frame to resize not to the preferred size but to the size of the jtable .the size of jtable vary according to the data inside it..Is there anny methos for that.

  • Progress bar inside datagrid

    Hi All,
    I have a datagrid in which i have to display progress bar with the task completed in %.
    for example i have  two fields in a table source count and completion count.
    where source count in 100000 rows and 50000 rows have been inserted.
    in another table and status is displayed in the table.
    so i need to display in a progress bar that 50% task has been completed.
    Any suggestions or ideas.
    Sample ex:

    Hello,
    here is something to play with:
    public class ProgressInTableTest {
        private static final Random RANDOM = new Random();
        private final class RunnableDummyProgressProducer implements Runnable {
            private final DefaultTableModel defaultTableModel;
            private final JProgressBar allProgress;
            private RunnableDummyProgressProducer(
                    DefaultTableModel defaultTableModel, JProgressBar allProgress) {
                this.defaultTableModel = defaultTableModel;
                this.allProgress = allProgress;
            @Override
            public void run() {
                for (int i = 0; i < progressEntries.size(); i++) {
                    ProgressEntry progressEntry = progressEntries.get(i);
                    while (100 > progressEntry.progress * 100
                            / progressEntry.fileSize) {
                        progressEntry.progress += 10;
                        defaultTableModel.fireTableCellUpdated(i, 2);
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                    progressEntry.progress = progressEntry.fileSize;
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            allProgress.setValue(allProgress.getValue() + 1);
                            allProgress.setString(String.format("%s / %s",
                                    allProgress.getValue(),
                                    allProgress.getMaximum()));
                    defaultTableModel.fireTableCellUpdated(i, 2);
        private final class DefaultTableCellRendererExample extends
                DefaultTableCellRenderer {
            private static final long serialVersionUID = 1L;
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus, int row,
                    int column) {
                Component rendererComponent = super.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
                JTextField newRenderer = new JTextField();
                ProgressEntry progressEntry = progressEntries.get(row);
                switch (progressEntry.progress * 100 / progressEntry.fileSize) {
                case 0:
                    newRenderer.setText("pending");
                    return newRenderer;
                case 100:
                    newRenderer.setText("done");
                    return newRenderer;
                default:
                    rendererComponent = new JProgressBar(0, progressEntry.fileSize);
                    JProgressBar jProgressBar = (JProgressBar) rendererComponent;
                    jProgressBar.setValue(progressEntry.progress);
                    jProgressBar.setStringPainted(true);
                return rendererComponent;
        private final class DefaultTableModelExample extends DefaultTableModel {
            private static final long serialVersionUID = 1L;
            private final String[] columnNames = { "file name", "file size",
                    "progress" };
            private DefaultTableModelExample(int rowCount, int columnCount) {
                super(rowCount, columnCount);
            @Override
            public String getColumnName(int column) {
                return columnNames[column];
            @Override
            public Class<?> getColumnClass(int collumn) {
                switch (collumn) {
                case 1:
                    return Integer.class;
                case 2:
                    return ProgressEntry.class;
                default:
                    return String.class;
            @Override
            public Object getValueAt(int row, int column) {
                switch (column) {
                case 0:
                    return progressEntries.get(row).fileName;
                case 1:
                    return progressEntries.get(row).fileSize;
                case 2:
                    return progressEntries.get(row).progress;
                default:
                    return super.getValueAt(row, column);
        public class ProgressEntry {
            private final String fileName;
            private final int fileSize;
            private int progress = 0;
            public ProgressEntry(String fileName, int fileSize) {
                this.fileName = fileName;
                this.fileSize = fileSize;
        private final List<ProgressEntry> progressEntries = new ArrayList<ProgressEntry>();
        @Test
        public void test() {
            initializeSampleData();
            JProgressBar allProgress = createFileCountProgress();
            DefaultTableModel defaultTableModel = new DefaultTableModelExample(
                    progressEntries.size(), 3);
            JTable table = createTable(defaultTableModel);
            startDummyProcess(allProgress, defaultTableModel);
            JPanel message = completeGUI(allProgress, table);
            JOptionPane.showMessageDialog(null, message, "ProgressTest",
                    JOptionPane.PLAIN_MESSAGE);
        private JPanel completeGUI(final JProgressBar allProgress, JTable table) {
            JPanel message = new JPanel(new BorderLayout());
            message.add(new JScrollPane(table), BorderLayout.CENTER);
            message.add(allProgress, BorderLayout.SOUTH);
            return message;
        private void startDummyProcess(final JProgressBar allProgress,
                final DefaultTableModel defaultTableModel) {
            new Thread(new RunnableDummyProgressProducer(defaultTableModel,
                    allProgress), "ProgressTest").start();
        private JTable createTable(final DefaultTableModel defaultTableModel) {
            JTable table = new JTable(defaultTableModel);
            table.setDefaultRenderer(ProgressEntry.class,
                    new DefaultTableCellRendererExample());
            return table;
        private JProgressBar createFileCountProgress() {
            final JProgressBar allProgress = new JProgressBar(0,
                    progressEntries.size());
            allProgress.setStringPainted(true);
            return allProgress;
        private void initializeSampleData() {
            for (int i = 0; i < 20; i++) {
                progressEntries.add(new ProgressEntry(String.format("IMG_%03d.jpg",
                        i), RANDOM.nextInt(1000)));
            for (int i = 0; i < 3; i++) {
                progressEntries.get(i).progress = progressEntries.get(i).fileSize;
            progressEntries.get(3).progress = 50;
    bye
    TPD

  • Setvisible with java 1.6.11 and up

    Help please!!!
    We have an application that switches out panels in a JSplitPane. One of the panels is a very large JScrolledPane and when setting the visibility to false it can lock the application 30-60 seconds. This all started happening with the 1.6.11 update. Has anyone seen this or have any clues on why?
    Thanks,
    Mike

    Thanks for the reply. And here you go. But, now I have a bigger problem. This works for 1.5 thru 1.6.14!!! Granted our panels are move complex, but it still should not lock up the application during the remove call.
    Thanks again,
    mike
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class RemoveExample {
    static JFrame frame = new JFrame("Remove Issue");
    static JSplitPane mainPanel = new JSplitPane();
    static JSplitPane panel1 = new JSplitPane();
    static JSplitPane panel2 = new JSplitPane();
    public static void main(String args[]) {
         JPanel buttonPanel = new JPanel(new FlowLayout());
         JButton button = new JButton("Switch Panels");
         button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              if (panel1.isVisible()) {
              mainPanel.remove(panel1);
              panel1.setVisible(false);
              mainPanel.setBottomComponent(panel2);
              panel2.setVisible(true);
              } else {
              mainPanel.remove(panel2);
              panel2.setVisible(false);
              mainPanel.setBottomComponent(panel1);
              panel1.setVisible(true);
         buttonPanel.add(button);
         mainPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
         mainPanel.setTopComponent(buttonPanel);
         panel1.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         panel1.setLeftComponent(new JScrollPane(new JTree()));
         panel1.setRightComponent(new JLabel("small panel"));
         JTabbedPane tabs = new JTabbedPane();
         JPanel thumbnails = new JPanel(new GridLayout(0, 5, 10, 10));
         DefaultTableModel dtm = new DefaultTableModel();
         dtm.addColumn("Label");
         dtm.addColumn("Name");
         dtm.addColumn("Gallery");
         dtm.addColumn("Owner");
         dtm.addColumn("Uploaded");
         dtm.addColumn("Size(KB)");
         JTable table = new JTable(dtm);
         tabs.addTab("Thumbnails", new JScrollPane(thumbnails));
         tabs.addTab("List", new JScrollPane(table));
         panel2.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         panel2.setLeftComponent(new JScrollPane(new JTree()));
         panel2.setRightComponent(tabs);
         mainPanel.setBottomComponent(panel1);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
         frame.setSize(1000, 800);
         frame.setVisible(true);
         LoadThread loader = new LoadThread(thumbnails, table);
         loader.start();
    public static class LoadThread extends Thread {
         JPanel thumbs;
         JTable table;
         public LoadThread(JPanel thumbs, JTable table) {
         this.thumbs = thumbs;
         this.table = table;
         public void run() {
         DefaultTableModel dtm = (DefaultTableModel)table.getModel();
         for (int i = 0; i < 4000; i++) {
              JLabel label = new JLabel("image " + i);
    // set image icon.
              //label.setIcon(new ImageIcon("image.jpg"));
              label.setVerticalTextPosition(SwingConstants.BOTTOM);
              label.setHorizontalTextPosition(SwingConstants.CENTER);
              thumbs.add(label);
              dtm.insertRow(i, new String[]{ "image " + i, "Name", "Gallery",
                             "Owner", "Uploaded", "Size(KB)" } );
    Edited by: Pegasus-3326 on Jun 25, 2009 4:38 AM

  • Tired of Layouts

    Hi,
    I don't know whether I can ever become a good GUI programmer. I am getting screwed up every time my tester opens my GUI apps and tests something. And I am having a great problem with layouting the components. Let me explain what I have just went through...
    I was having JTables at many places in my application. And we wanted to have a consistent size for all the tables throughtout the application. But because the number of columns are different in the tables, I used preferred sizes for the JTables and I was setting the preferred sizes by getting the screen sizes thinking that it work on all screen resolutions.
    But, when I resized the window lesser then the preferred sizes of the JTables, I got screwed up. The tables were becoming very small that it can hardly make a single cell visible. So, I think setting preferred sizes definetly is not the solution for placing the components in a container.
    What kind out layout should I do if I have to use fixed size for JTables but not getting crashed when the window size comes smaller than the preferred size. Or, should I not use preferred sizes at all if the windows can be resized. And by the way, I am adding the Tables to Scrollpanes, so this is clearly stating that there is something seriously wrong with my approach.
    And what is the best and clean way to develop a swing application, I am able to understand all the examples in the swing tutorial, but when it comes to putting several components and do all the actions, I am messing it up. I love Java, but I would like to do it in a neat and good way. Please suggest me something.
    Thank you very much.

    If you want the tables to always be readable then you will probably need to setResizable(false). At some point the user has to realize that they can't make the window real small and still expect to read the data. Because no matter what layout you use something has to give when the window is resized.
    Just read each how to for each layout and keep in mind how each one honors or doesn't honor max size, min size, and preferred size. Nesting layouts is your friend.
    Keep in mind user experience, and user expectations.

  • Changing the size of a jbutton inside a jtable

    Hi,
    I have found this example for adding a jbutton to a jtable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=715330
    however, I have cannot seem to figure out how to set the size of the jbutton. Currently, the jbutton is filled to the size of the cell within the jtable, but i want to have it a bit smaller and centered (the rows of my table are rather large in hieght)
    I tried the setSize()
    setPrefferedSize()
    setMinimumSize()
    setMaximumSize()methods, but nothing seems to work. Has anyone been able to do this?

    Use a JPanel instead of a JButton as cell renderer. Put a button inside the panel - use FlowLayout.

Maybe you are looking for

  • Os-X Tiger DVD unreadable

    I replaced the original CD-RW with a new Lite-on DVDRW SHW-160P6S drive. Works great. I have read CD, DVD, written DVD and successfully tested burned DVDs on another computer. It works with Finder, iTune & Toast. But I bought OS-X tiger and I can't i

  • Strange system mail

    It now happened two times that I received the following mail that the system rejected a message. I originally assumed that it was an "undeliverable" message from an other server for a spam mail using us as reply-to address. I have then looked a bit c

  • OMF Export issue in Premiere CS6

    Hello, I am trying to export a feature length OMF file for my sound mixer. I have the tracks I want on and selected. I then do File - Export - OMF. I do encapsulated audio, with 60 frame handles. I then start the export. I encodes through the files t

  • How do i change a printer's ip address?

    hi i've been given an old hp2100tn laserjet printer and need to get inside and change the ip address settings and device name stored in the printer's memory from its previous location. does anyone have any general experience doing this kind of thing,

  • Add variuos amplitudes to sound graph

    Hi I have the following code that computes a sound graph with a fixed amplitude for a number of waves. I need to be able to control the amplitude of each wave, but am not sure how to amend the following code to produce the effect. There is also an ff