How to resize data in JTable?

Hi all,
I wish to provide a resize button on an application which will resize the data in a table (in most cases just text) as well as the table containing it. Is it possible to directly resize the table or must I change the renderer to draw all of the data bigger? I'm also not sure how to increase the width of the table. Any help would be much appreciated.
package gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Resizer extends JFrame
     * @see java.io.Serializable
    public static final long serialVersionUID = 0;
     * Table containing data
    private JTable table = null;
     * Scroll pane containing table
    private JScrollPane scroller = null;
     * Name of button to increase text size
    private static final String INCREASE = "Increase";
     * Name of button to decrease text size
    private static final String DECREASE = "Decrease";
     * An increment to use when resizing
    private static final int INCREMENT = 5;
    public Resizer()
        setTitle("Resizer");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,200);
        getContentPane().setLayout(new BorderLayout());
        // Add the table and its contents
        table = createTable();
        scroller = new JScrollPane(table);
        getContentPane().add(scroller, BorderLayout.CENTER);
        // Add buttons to resize
        JButton increase = new JButton(INCREASE);
        increase.addActionListener(new ButtonListener());
        JButton decrease = new JButton(DECREASE);
        decrease.addActionListener(new ButtonListener());
        JPanel panel = new JPanel();
        panel.add(increase);
        panel.add(decrease);
        getContentPane().add(panel, BorderLayout.SOUTH);
        // Show this window
        setLocationRelativeTo(null);
        setVisible(true);
    private JTable createTable()
        JTable t = new JTable();
        t.setModel(new MyModel());
        // Row 1
        t.getModel().setValueAt("John", 0, 0);
        t.getModel().setValueAt(new Integer(1), 0, 1);
        // Row 2
        t.getModel().setValueAt("Chris", 1, 0);
        t.getModel().setValueAt(new Integer(2), 1, 1);
        // Row 3
        t.getModel().setValueAt("Susan", 2, 0);
        t.getModel().setValueAt(new Integer(3), 2, 1);
        return t;
    private class MyModel extends DefaultTableModel
        private static final long serialVersionUID = 2;
        public MyModel()
            this.setColumnCount(2);
            this.setRowCount(3);
        public String getColumnName(int col)
            switch(col)
            case 0:
                return "Name";
            case 1:
                return "Number";
            default:
                return "Oops";
    private class ButtonListener implements ActionListener
        public void actionPerformed(ActionEvent ae)
                if (((JButton)ae.getSource()).getText().equals(INCREASE))
                    increaseTable();  
                else if (((JButton)ae.getSource()).getText().equals(DECREASE))
                    decreaseTable();
    private void increaseTable()
        this.setSize(this.getWidth()+INCREMENT, this.getHeight()+INCREMENT);
        table.setRowHeight(table.getRowHeight()+INCREMENT);
        table.setSize(table.getWidth()+INCREMENT, table.getHeight()+INCREMENT);
    private void decreaseTable()
        this.setSize(this.getWidth()-INCREMENT, this.getHeight()-INCREMENT);
        table.setRowHeight(table.getRowHeight()-INCREMENT);
        table.setSize(table.getWidth()-INCREMENT, table.getHeight()-INCREMENT);
    public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable()
            public void run()
                new Resizer();
}Using JDK 1.4.2

Thanks all.
The solution was to use setFont() on the table and its headers. Here's what I put in to increase and descrease the table size (for future reference).
     * Increases the size of everything in the table
    private void increaseTable()
        table.setRowHeight(table.getRowHeight() + INCREMENT);
        table.setSize(table.getWidth() + INCREMENT, table.getHeight() + INCREMENT);
        for (int i = 0; i < table.getColumnCount(); i++)
            TableColumn col = table.getColumnModel().getColumn(i);
            col.setWidth(col.getWidth() + INCREMENT / table.getColumnCount());
        Font headerFont = table.getTableHeader().getFont();
        table.getTableHeader().setFont(headerFont.deriveFont(headerFont.getSize2D()+INCREMENT));
        Font dataFont = table.getFont();
        table.setFont(dataFont.deriveFont(dataFont.getSize2D() + INCREMENT));
     * Decreases the size of everything in the table
    private void decreaseTable()
        if (table.getRowHeight() > INCREMENT)
            table.setRowHeight(table.getRowHeight() - INCREMENT);
            table.setSize(table.getWidth() - INCREMENT, table.getHeight() - INCREMENT);
            for (int i = 0; i < table.getColumnCount(); i++)
                TableColumn col = table.getColumnModel().getColumn(i);
                col.setWidth(col.getWidth() - INCREMENT / table.getColumnCount());
            Font headerFont = table.getTableHeader().getFont();
            table.getTableHeader().setFont(headerFont.deriveFont(headerFont.getSize2D()-INCREMENT));
            Font dataFont = table.getFont();
            table.setFont(dataFont.deriveFont(dataFont.getSize2D() - INCREMENT));
    }

Similar Messages

  • How to insert data from JTable to mysql Table....

    hello everybody
    i need help about how to insert data from JTable to mysql table... i know about how to create Table model...facing problem about how to insert data from JTable to mysql table....any helping link or code ... ill be thankfulll....for giving me solution...

    table1.getValueAt(table1.getSelectedRow(),0)you are getting the value of a selected row... or if you want you can just use a loop..
    for(.....){
    table1.getValueAt(x,y);
    }I think you know INSERT STATEMENT.. here on it just string concat
    sample e.g. (This not insert)
    "delete from accrule " +
                    "where ruleid= " + tblRA.getValueAt(tblRA.getSelectedRow(),0)+
                    " and accountname='"+tblRA.getValueAt(tblRA.getSelectedRow(),1)+"'"

  • How to add data into JTable

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

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

  • How to fetch data in JTable

    I wanna know how to display the data returned from the database in a Table. I am providing the code in which i am unable to display the data in a Table.
    <HTML>
    <Applet Code="SQLWithTable.class" width=600 height=600>
    </Applet>
    </HTML>
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.sql.*;
    public class SQLWithTable extends JApplet implements ActionListener
    Container c;
         String[] colHead=null;
         Object[][] data=null;
         Connection con;
         ResultSet result;
         JLabel lquery;
         JTextField tquery;
         JButton bsubmit;
         JButton clear;
         String query;
         public void init()
         try
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con=DriverManager.getConnection"jdbc:odbc:MyDataSource","sa","");
         System.out.println("Connected To DataBase Server");
         catch(Exception e)
         System.out.println("Error Loading Driver");
         c=getContentPane();
         c.setLayout(new FlowLayout());
         lquery=new JLabel("Enter Query");
         tquery=new JTextField(20);     
         bsubmit=new JButton("Execute");
         c.add(lquery);
         c.add(tquery);
         c.add(bsubmit);
    bsubmit.addActionListener(this);
    public void actionPerformed(ActionEvent evt)
         query=tquery.getText(); //get query from user
         Object obj=(JButton)evt.getSource();
         if(obj==bsubmit)
         try
         Statement stat=con.createStatement();
         ResultSet result=stat.executeQuery(query);
         ResultSetMetaData rsmd=result.getMetaData();
         int colCount=rsmd.getColumnCount();
         for(int i=1; i<=colCount; i++)
              //How to display the columnHeadings in Table
         while(result.next())
         for(int i=1; i<=colCount; i++)
              //How to insert data in Table
         JTable table=new JTable(data,colHead);
         int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
         int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
         JScrollPane jsp=new JScrollPane(table,v,h);
         c.add(jsp);
         con.close();
         catch(Exception e)
              System.out.println(e);
    }

    Application Details is :-
    A user will enter a query in a Textfield eg. ("select
    * from xyz"). after pressing the execute button the
    user will get the result in a Table format. You can
    think of this application is like SQL Server Query
    Interface where we write query and get result in a
    table format.But what is your question?

  • URGENT !!! HOW CAN CHANGE DATA IN JTABLE!!!

    My Program ....
    pLinhas.dataModel.addTableModelListener(new TableModelListener() {
    public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object data = pLinhas.dataModel.getValueAt(row,column);
    Object valor = pLinhas.dataModel.getValueAt(row,6);
    System.out.println("Quantidade -" + data.toString());
    System.out.println("Valor a Cobrar -" + valor.toString());
    setValueAt(data,row,6);
    public void setValueAt(Object value, int row, int col) {
    System.out.println("Mudou ou nao");
    pLinhas.dataModel.fireTableCellUpdated(row, col);
    this dont work. When the method setValue() run, the java break.
    the message are :
    # An EXCEPTION_STACK_OVERFLOW exception has been detected in native code outside the VM.
    # Program counter=0x77e94aa0
    how can i change my data for a new data in jtable.
    tx for help.

    I had a problem similar to this. I was writing my own table model which would work sometimes and at other times fail similar to what you describe. I ended up printing out the source code to the DefaultTableModel and taking a look at it and then deciding to subclass that class and add my additional functionality as opposed to writing a completely new model and trying to duplicate the DefaultTableModel. My needs were relatively simple and the subclassing fixed the problem. I can change data with no problem in the displayed table. If you're not already subclassing and trying to write your own table model you may want to give this a try. I'd struggled with the problem for several days thinking I'd fixed it and having it come up again. I invested 2 hours doing the subclassing and the problem has never appeared since then. I know I just missed doing something in the table model I was trying to write but my schedule was tight and the subclassing offered a quick fix. Hope this helps!

  • How to change data in  jtable?

    Hai.I have a problem to change data in jtable.Can anbody help me to slove this?
    Think you in advance

    Did you want to change individual cells?
    For example, to change cell (2, 1) to "new data":
    yourTable.setValueAt("new data", 1, 2)

  • How to put data in JTable from database

    hi everyone,
    i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
    thank you
    dhing

    In [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.

  • How to enter data in JTable?

    I have created a JTable.Now,I want to enter data in specific row and column, how can I do that?

    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables for the basics of using a table.
    Once you have data loaded in a table you can change the data in a cell using:
    table.setValueAt(....);

  • How to get data in jtable from database

    i m working on core java application i want to use jtable to show records to user. jtable will get records from mssql database. how to do this.. i m new so plz tell me briefly..with coding...
    thanks

    i have use this link:
    import java.sql.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * This class takes a JDBC ResultSet object and implements the TableModel
    * interface in terms of it so that a Swing JTable component can display the
    * contents of the ResultSet. Note that it requires a scrollable JDBC 2.0
    * ResultSet. Also note that it provides read-only access to the results
    public class ResultSetTableModel implements TableModel {
    ResultSet results; // The ResultSet to interpret
    ResultSetMetaData metadata; // Additional information about the results
    int numcols, numrows; // How many rows and columns in the table
    * This constructor creates a TableModel from a ResultSet. It is package
    * private because it is only intended to be used by
    * ResultSetTableModelFactory, which is what you should use to obtain a
    * ResultSetTableModel
    ResultSetTableModel(ResultSet results) throws SQLException {
         this.results = results; // Save the results
         metadata = results.getMetaData(); // Get metadata on them
         numcols = metadata.getColumnCount(); // How many columns?
         results.last(); // Move to last row
         numrows = results.getRow(); // How many rows?
    * Call this when done with the table model. It closes the ResultSet and
    * the Statement object used to create it.
    public void close() {
         try { results.getStatement().close(); }
         catch(SQLException e) {};
    /** Automatically close when we're garbage collected */
    protected void finalize() { close(); }
    // These two TableModel methods return the size of the table
    public int getColumnCount() { return numcols; }
    public int getRowCount() { return numrows; }
    // This TableModel method returns columns names from the ResultSetMetaData
    public String getColumnName(int column) {
         try {
         return metadata.getColumnLabel(column+1);
         } catch (SQLException e) { return e.toString(); }
    // This TableModel method specifies the data type for each column.
    // We could map SQL types to Java types, but for this example, we'll just
    // convert all the returned data to strings.
    public Class getColumnClass(int column) { return String.class; }
    * This is the key method of TableModel: it returns the value at each cell
    * of the table. We use strings in this case. If anything goes wrong, we
    * return the exception as a string, so it will be displayed in the table.
    * Note that SQL row and column numbers start at 1, but TableModel column
    * numbers start at 0.
    public Object getValueAt(int row, int column) {
         try {
         results.absolute(row+1); // Go to the specified row
         Object o = results.getObject(column+1); // Get value of the column
         if (o == null) return null;
         else return o.toString(); // Convert it to a string
         } catch (SQLException e) { return e.toString(); }
    // Our table isn't editable
    public boolean isCellEditable(int row, int column) { return false; }
    // Since its not editable, we don't need to implement these methods
    public void setValueAt(Object value, int row, int column) {}
    public void addTableModelListener(TableModelListener l) {}
    public void removeTableModelListener(TableModelListener l) {}
    the table is showing column name from database but not showing the data in row now what to do

  • How to import data into JTable from a text file?

    thanks in advance!

    My guess is you will have to read the data in from the file, parse it, populate some vectors or something and use those vectors to instantiate the JTable. You could use FileReader to read in the data:
    FileReader in = new BufferedReader(new FileReader(file));then use StringTokenizer to parse it.
    m

  • How to save data from JTable multiple rows and columns

    Hi Y_Not thanks for your help before...
    But what should I do if I want to get/save many data from many column and rows??

    i don't quite understand your (repeated) question. what is the problem with "multiple rows and columns". Y_NOT and i have shown you ways to access them.
    all you need are 2 loops: one around your number of rows and one around the number of columns or vice versa depending in which order you want to save things:
    for (int col = 0; col < data.size(); col++) {
        for (int row = 0 ; row < data[col].size(); row++) {
            // save your data
            saveData(data[col].getElementAt(row));
            // or use yourtable.getValueAt(row, col);
    }this is not a problem of Swing/Java but of simple algorithm...
    thomas

  • JTable, how to read Data from it when enter is pressed

    How to read Data from JTable on Return or lost focus from cell.
    Also please tell me which listener I should should.
    thx for help

    You should read the tutorial about tables, cell editors and models.
    Also you should not [url http://forum.java.sun.com/thread.jsp?thread=472677&forum=57&message=2186815]crosspost
    Mike

  • How to populate data in a JTable?????????

    hi there
    can anyone tell me how to populate data in a JTable? when a table is displayed, the table should have data retrieved from a file. thank you.

    Hi,
    it is correct, that the best way to learn about JTable is to read the online tutorial about JTable. To give you a quick guideline, where to start your implementation, I will add this:
    A JTables data is hold in a TableModel. TableModel is an interface, so if a class implements this interface correctly, you can simply populate the data hold by this TableModel by constructing a JTable this way
    JTable jt = new JTable(MyTableModel);
    where MyTableModel is your class, which implements the TableModel interface.
    When JTable has to render a cell, it will call the getValueAt(...) method of the TableModel for example.Your implementation of this method must deliver the requested data - if you prefetch a bunch of data from a file and store it internally in this TableModel or fetch it from the file just in time, is up to you.
    greetings Marsian

  • How to set background of jtable in no data?

    How to set background of jtable in no data?
    I use table.setBackground(Color.black) but no successful
    Please help me. thanks very much

    maybe, you don't understand me.
    I have below jtable:
    ============================
    I column1 name l column2 name I
    ============================
    l data l data l
    ============================
    l data l data l
    ============================
    XXX
    ============================
    I wrote:
    table.setBackground(Color.black) then only data area has black colour, but XXX area hasn't black colour.
    How to XXX area also has black colour?
    help me, thanks very much.

  • How to set data in rtf document?

    Hi friends,
    I have a rtf document can anyone suggest how to set data in cells of an rtf document?Is there any way?
    Thanks in advance..
    Regards ,
    Soumyanil

    Convert the resultSet from the db to a Object[][], let's call it result.
    Then create a JTable (jTable1).
    On the JTable you need to define the headers, and the data itself.
    You can get the headers from ResultSetMetaData. Convert these to an array again (headers).
    Now use these methods to create a model and set the model of the JTable.
    Model model =  new DefaultTableModel(result, headers);
    jTable1.setModel(model);That's about the basics.
    If you need more info, use at the tutorial at sun's homepage.
    How to use Tables:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

Maybe you are looking for