Resize JTable Columns without Column Header

Hi all.
I have a JTable that doesn't display a column header.
I would like to allow the user to resize the columns by dragging a mouse at the column edges at any point down the table.
It is not obvious how I can accomplish this.
Does anyone have any ideas?
Thanks, Paul.

That doesn't work, though, since the table has its own listenersIt's not just that. The header's mouse listeners work with instance fields of BasicTableHeaderUI and detection (using e.getPoint) of the header cell and column.
I would start with copying the entire code of BasicTableHeaderUI to a class of my own, then first eliminate anything that obviously isn't related to column dragging/resizing, then refactor, refactor, refactor to make the listener codes work with a table instead of a header. But like I said, easier said than done, particularly when having to deal with the various JTable column resize modes.
db

Similar Messages

  • How  to resize the column header according to row data

    Hi,
    How can i resize the column header according to row date .. means if data is small header should be small and vice versa ,...
    Any help is appreciated .. Snippet will be more helpful .
    Thanks,
    Shekhar

    Oxley (binkley) blogged about this: http://binkley.blogspot.com/2006/01/getting-jtable-columns-widths-to-fit.html
    Christian Ullenboom | tutego

  • (simple q) how do I change the font in a JTable column header?  thanks

    how do I change the font in a JTable column header?
    thanks

    JTableHeader header = yourTable.getTableHeader();
    // Set to serif, bold, size 12...
    header.setFont( new java.awt.Font( "serif", 1, 12 ) );
    // you can set others like color and border, too.
    header.setBackground(Color.white);
    header.setBorder( new EmptyBorder(15,2,15,2) );

  • Multi-colored JTable column heading?  How?

    Hi,
    I'm looking for a way to have JTable column heading text
    that can be displayed in multiple colors, so one string
    in one column header, might have each letter a different
    color.
    My application requires highlighting some of the letters
    of a word as red, while others are normal text (black).
    I've been using multi-line strings to simulate vertical
    naming for my column header, for example:
    PPP
    I I I
    N N N
    1 2 3
    for PIN1, PIN2, PIN3. The column data has a binary
    one or zero for each pin, grouped together in one JTable
    column. In my application, if there is an error, I want to
    color just the text representing, say PIN2 red and leave
    the surrounding PIN1 and PIN3 black.
    What approach should I take for doing this with JTable?
    Thanks!
    John Roberts
    [email protected]

    You should override the default cell renderer used by Java
    - JTable.getTableHeader().setDefaultRenderer(yourRenderer)
    Extend yourRenderer from JLabel and use HTML tags to change the color.
    - setText on JLabel with the HTML code like "<HTML> <BODY> <FONT COLOR="red"> A </FONT> <FONT COLOR="green"> B </FONT></BODY> </HTML>"

  • Resize JTable columns by double-clicking header

    I want to implement column resizing in a JTable so that when the user double clicks on the column header with the mouse in the "resize zone" the column automatically adjusts to the width of the longest text in the column. this is how many applications behave (e.g. windows explorer) but I don't think I've ever seen a swing app that does this. I've looked in the API docs for JTable and JTableHeader and I can't see any way of finding out if the mouse is over the edge of a column header. does anyone know of a way to do this?

    Is this laf independant?import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = {{"R1-C1","R1-C2","R1-C3"},
                {"R2-C1","R2-C2","R2-C3"},
                {"R3-C1","R3-C2","R3-C3"}};
        JTable jt = new JTable(data, head);
        JScrollPane jsp = new JScrollPane(jt);
        content.add(jsp, BorderLayout.CENTER);
        JTableHeader jth = jt.getTableHeader();
        jth.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            JTableHeader jth = (JTableHeader)me.getSource();
            int col = jth.columnAtPoint(me.getPoint());
            Rectangle r = jth.getHeaderRect(col);
            if (jth.getCursor().equals(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR))) {
              System.out.println("Cursor, col="+col);
        setSize(300, 300);
        setVisible(true);
      public static void main(String args[]) { new Test(); }
    }

  • Resize jtable column width

    I am trying implement a utility in JTable by which when a person clicks on the column header, the whole column should resize according to the cell which has lengthiest data. If you have seen this in MS Excel where by clicking on the column this happens. I want the same thing.
    Is there anyway already defined in javax.swing?
    I have added a Mouselistener on Tableheader and when the person clicks on a column header, I first finds out the column index. Now on that column index scan the whole column for the lengthiest data. After finding the lengthiest data I set the preferred width for that column and call doLayout on the table object. In this case the problem is of font as the font is not fixed width. The multiplication factor which returns the pixel doesn't gives the right pixel width. Is there any way by which I can find pixel width of a String?

    Use the following code to compute the width of a
    column in pixels required to display the maximum sized
    string in the table column:
    FontMetrics fm =
    table.getFontMetrics(table.getFont());
    int width =
    SwingUtilities.computeStringWidth(fm,maxSizeString)
    //then to set the width of your column:
    TableColumnModel columnModel =
    table.getColumnModel();
    TableColumn column =
    columnModel.getColumn(YOUR_COLUMN);
    column.setPreferredWidth(width);Rizwanthx that was usefull

  • User cannot resize jTables� columns

    Hello,
    Using NetBeans IDE 3.5.1, I built a jTable, controlled by a
    JScrollpane.
    My problem is that the user cannot resize the jTables� columns.
    Maximum details:
    1.     jtablewidth is set to a fixed value according to internal data:
    JTable1.setPreferredSize( new Dimension(tableWidth, i_TableHeight));
    2.     columnwidth is set according to internal data:
    Col = JTable1.getColumnModel().getColumn(i);
    Col.setWidth(width);
    Col.setResizable(true);
    Col.setMinWidth(width);
    3.     jTable header details:
    JTableHeader anHeader = JTable1.getTableHeader();
    anHeader.setReorderingAllowed(false);
    anHeader.setResizingAllowed(true);
    4.     JTable1.getTableHeader().setResizingAllowed(true);.
    5.     Initial declerations:
    a.     JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
         JTable1.setColumnSelectionAllowed(true);
         JTable1.setDragEnabled(true);
         JTable1.setPreferredScrollableViewportSize(new
    java.awt.Dimension(650, 500));
         JTable1.setPreferredSize(new java.awt.Dimension(1200, 409));
         JTable1.setRequestFocusEnabled(false);
    b.     JScrollPane1.setMaximumSize(new java.awt.Dimension(750, 412));
         JScrollPane1.setPreferredSize(new java.awt.Dimension(750,
    412));
         JScrollPane1.setViewportView(JTable1);
         JScrollPane1.setAutoScolls(false);
    c.     Jtable.autoCreateColumnsFromModel (true);
    Thanks alot,
    Itay

    Columns resizing works by default. You don't need to do anything special.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JTable Column Header Problem, Please help me

    What Listener I have to used to get the column index when user change the width of column header using mouse.

    There is no listener that reports this activity. The TableColumnModelListener can only tell you if columns change position or are added/removed from the column model.
    To detect changes, you will need to use a brute force mechanism, namely, to extend the JTableHeader class just a bit.
    When the user clicks on a header to resize a column, there is a property in JTableHeader called ResizingColumn that has a type of TableColumn. It is set by the UI delegate when the drag operation starts to the column being resized. When the drag operation ends, the value of ResizingColumn is set to null. You might start with something like this:
      JTable table = new JTable(...);
      MyTableHeader header = new MyTableHeader();
      table.setHeader(header);
      table.setModel(...);
    class MyTableHeader extends JTableHeader
        public void setResizingColumn(TableColumn column)
            super.setResizingColumn(column);
            if (column != null)
                System.out.println("Resizing Column #" + column.getModelIndex());
            else
                System.out.println("Resizing Ended");
    }This will only work for user resizing of columns, not for sizes changed programmatically or by the automatic sizing features of the header.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • How to change JTable column header text

    How do you set the text in the JTable column headers? I know you can create a JTable specifying the text in an array:
    <li>JTable(Object[][] rowData, Object[] columnNames)
    But if you create the JTable specifying a TableModel,
    <li>JTable(TableModel dm)
    the header text defaults to "A", "B", "C", etc. I cannot figure out how to access the text in the header names so it can be changed to something useful. I know how to get the JTableHeader for the table, but it does not seem to have methods for actually setting header values.

    I'm sure that model allows you to specify header values so you don't have to do so manually. I would be very surprised if it didn't override the default getColumnName() method to provide a reasonable names.She wasn't writing the class, but [url http://forums.oracle.com/forums/thread.jspa?messageID=9200751#9200751]outlining a design for me to implement. And, based on a previous comment I had made, I think she assumed I wanted the new design to look as much like the old as possible. There were no headers in the original design, which wasn't even a table.
    Anyway, this works:
        final static String statisticsColumnNames[] = {
         "Type", "Count",
         "Red QE", "Green QE", "Blue QE", "Average QE",
         "Distance"
         qErrors = new QEBeanTableModel();
         JTable errorTable = new JTable(qErrors);
         TableColumnModel tcm = errorTable.getColumnModel();
         for (int col = 0; col < statisticsColumnNames.length; col++)
             tcm.getColumn(col).setHeaderValue(statisticsColumnNames[col]);
    It looks like setHeaderValue() on the TableColumn is what I was looking for.Again, only used if you are dynamically changing the values at run time or you don't like the defaults provided by the Bean-aware model.I coded the above before I read your last post. The QEBeanTableModel is extremely specific to my program. I.e. I cannot imagine it being used anywhere else. Would it still be better to implement a getColumnName() within the table model? Looking at your [url http://www.camick.com/java/source/RowTableModel.java]RowTableModel.java source, I can see that it would not be difficult to do so.
    Just decided to add the getColumnName() method. This whole sub-project is based on implementing a clean modern design (and learning about Java Beans). You've clearly stated twice that the method I have implemented is for dynamic header values only, which has already answered what I asked last paragraph.

  • How to resizea JTable column to fit to text programatically?

    hi evreyone,
    i'm trying to resize a JTable column width to fit to the contained text programatically.my approach was that i made a comparison between the length of String objects contained in my column and got the biggest String length value but i want to know how can i resize the column to fit to this biggest String object

    You're going the wrong way about it - don't go calculating string lengths. Get the TableCellRenderer, query it for the renderer component for each cell in the column, obtain its preferred size and keep a record of the greatest width value.

  • Arrow on JTables column header

    Hey guys,
    I have a few dialogs with tables on etc, everythings fine, its just one table when the program runs, when u hovver(sp?) over the line on the column header it normally turns into a black arrow like so <--> and the you can resize it.
    But this one table wont do that, ive created these in netbeans and just cant see the difference with the other tables. the columns are still resizable just remains an normal arrow though rather than <-->
    Thanks for any help

    You can't resize the column if use the code below,but the arrow will display
    TableColumn tableColumn = this.getTableHeader().getColumnModel().getColumn(i);
                             tableColumn.setPreferredWidth(columnsize);
                             tableColumn.setMinWidth(columnsize);
                             tableColumn.setMaxWidth(columnsize);reply if it help you..

  • How to have a combobox in JTable column header?

    Any simple ways for doing this? I am trying to get a filter to a JTable, so that only the rows containing the selected value in that column would be shown.
    I first need to get this combobox into the header of a column.

    Thanks.
    I have already tried with this way, but it was too long and complicated to implement into my file.
    Could someone post the principles here.
    Like this:
    // create my combobox
    JComboBox myBox = new JComboBox();
    myBox.addItem("Cat");
    myBox.addItem("Dog");
    // put the combobox to column header
    ??? ANY CODE HERE ???
    Tnx ahead!
    OK!
    AUlo

  • JTable column header to span multiple columns

    Hi people. I've spent the last day trying to do this with no luck. Most of the links in the forum are old and don't exist any more and the ones that lead to some code end up not working on java 5 (I can compile and run but the result is not what I wanted)!
    So my question is this, how do I have a column header that spans more than one column, which has individual column headers below it?
    Thanks, Paul.
    EDIT: I should point out that this is the place I've tried and although the screen shot of the first example looks exactly like what I want to do, it does not work as advertised. [http://www.crionics.com/products/opensource/faq/swing_ex/JTableExamples1.html]
    Edited by: Boomah on 05-Nov-2008 15:08

    Something like this?import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableColumnModelListener;
    import javax.swing.table.*;
    public class MultiSpanHeader {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new MultiSpanHeader().makeUI();
       public void makeUI() {
          final JTable table = new JTable(5, 6);
          final JTableHeader header = table.getTableHeader();
          header.setReorderingAllowed(false);
          final TableColumnModel model = table.getColumnModel();
          Enumeration<TableColumn> enumColumns = model.getColumns();
          final List<TableColumn> columns = Collections.list(enumColumns);
          final JTable dummy = new JTable(0, 3);
          final JTableHeader dummyHeader = dummy.getTableHeader();
          dummyHeader.setReorderingAllowed(false);
          dummyHeader.setResizingAllowed(false);
          final TableColumnModel dummyModel = dummy.getColumnModel();
          Enumeration<TableColumn> enumDummyColumns = dummyModel.getColumns();
          final List<TableColumn> dummyColumns = Collections.list(enumDummyColumns);
          model.addColumnModelListener(new TableColumnModelListener() {
             @Override
             public void columnAdded(TableColumnModelEvent e) {
             @Override
             public void columnRemoved(TableColumnModelEvent e) {
             @Override
             public void columnMoved(TableColumnModelEvent e) {
             @Override
             public void columnMarginChanged(ChangeEvent e) {
                dummyColumns.get(0).setWidth(columns.get(0).getWidth());
                dummyColumns.get(1).setWidth(columns.get(1).getWidth() +
                      columns.get(2).getWidth());
                dummyColumns.get(2).setWidth(columns.get(3).getWidth() +
                      columns.get(4).getWidth() + columns.get(5).getWidth());
             @Override
             public void columnSelectionChanged(ListSelectionEvent e) {
          JScrollPane pane = new JScrollPane(table);
          pane.setPreferredSize(new Dimension(600, 200));
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(pane);
          frame.pack();
          JPanel panel = new JPanel(new GridLayout(2, 1));
          panel.add(dummyHeader);
          panel.add(header);
          pane.getColumnHeader().setView(panel);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    }Note: this is just presented as an idea, would need a lot of work to make it robust and flexible enough for practical use.
    db

  • JTable : column header with subheaders

    I need to create a table that looks like this:
    ======================
    Car....|...PRICE......
    .......|dollars.|euros
    ======================
    camry..|18K.....|17k...
    bmw....|80K.....|76K...
    metro..|22K.....|30K...
    (sorry for lousy "graphics")
    My quesion is about the two-layered "PRICE" column header that has two subheaders for two different currencies.
    What is the best way to approach this?

    So there's no standard feature for that (like in HTML)-- you basically have to implement it all yourself?

  • How to use JButton as a JTable column header?

    I'd like to use JButtons as my JTable's column headers.
    I built a JButton subclass which implemented TableCellRenderer and passed it to one of my table column's setHeaderRender method. The resulting header is a component that looks like a JButton but when clicked, it does not visually depress or fire any ActionEvents.

    You might want to check this example and use it accordingly for your requirements.
    http://www2.gol.com/users/tame/swing/examples/JTableExamples5.html
    Reason: The reason you're unable to perform actions on JButton is JTableHeader doesn't relay the mouse events to your JButtons.
    I hope this helps.
    have fun, ganesh.

Maybe you are looking for

  • Excel Files become "Broken" and cannot be opened

    Our environment is as follows: SharePoint 2013 server, web application running in 2010 mode.  Our users are primarily on thin clients in a 64-bit Citrix environment running Office 2013 applications.  We use a redirected desktop/my documents on a netw

  • Printing problem on HP 8550

    One of our users is having problems printing a PDF from an HP 8550. The PDF was created in Acro 8, compatible back to 5. The user trying to print the PDF is opening and printing it from Acro 7. It is a 2 page PDF. The first page prints, but instead o

  • How to re-install Win XP on Portege 3500?

    Hi! I've got a problem with our Portege P3500 (PP350E): The Windows XP Tablet PC Edition on it is currently still running, but due to a lot of installed and improperly de-installed software, it's very slow, so I'd like to re-install the OS "from scra

  • Bpel process manager server failed thru JDEV-10.1.3.4

    All, soa Version: 10.1.3.4 I created application server successfully, but when i try to create integration server from jdev I got the error as bpel process manager server failed. I checked my DB is up, as some blog says hw_services should be up(i mad

  • IPhone 5 major glitch

    Recently, when using the iphone 5 during a call, FaceTime or texting it will close out (or hang up) then quickly flash between home screens and then lock. The Power button is no longer working, along with the volume buttons and the home botton. It's