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(); }
}

Similar Messages

  • 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

  • How not to sort datagrid column on double click

    Hello,
    I am currently building an application containing a datagrid for data representation. I've created a custom datagridheader in order to add a input text for filtering the columns (see code below).
    My goal is to hide the textinput, and then show it on a double click on the header. So i would like to know how to avoid the sort of this column each time i double click.?
    <?xml version="1.0" encoding="utf-8"?>
    <s:GridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                        xmlns:s="library://ns.adobe.com/flex/spark"
                        xmlns:mx="library://ns.adobe.com/flex/mx" resize="onColumnResize(event)" clipAndEnableScrolling="true" doubleClick="managefilterField(event)">
        <fx:Declarations>
            <!--- The default value of the <code>sortIndicator</code> property.
            It must be an IFactory for an IVisualElement.       
            <p>This value is specified in a <code>fx:Declaration</code> block and can be overridden
            by a declaration with <code>id="defaultSortIndicator"</code>
            in an MXML subclass.</p>
            @langversion 3.0
            @playerversion Flash 10
            @playerversion AIR 2.0
            @productversion Flex 4.5
            -->
            <fx:Component id="defaultSortIndicator">
                <s:Path data="M 3.5 7.0 L 0.0 0.0 L 7.0 0.0 L 3.5 7.0" implements="spark.components.gridClasses.IGridVisualElement">
                    <fx:Script>
                        <![CDATA[
                            import spark.components.DataGrid;
                            import spark.components.Grid;
                             *  @private
                            public function prepareGridVisualElement(grid:Grid, rowIndex:int, columnIndex:int):void
                                const dataGrid:DataGrid = grid.dataGrid;
                                if (!dataGrid)
                                    return;
                                const color:uint = dataGrid.getStyle("symbolColor");
                                arrowFill1.color = color;
                                arrowFill2.color = color;
                        ]]>
                    </fx:Script>
                    <s:fill>
                        <s:RadialGradient rotation="90" focalPointRatio="1">   
                            <!--- @private -->
                            <s:GradientEntry id="arrowFill1" color="0" alpha="0.6" />
                            <!--- @private -->
                            <s:GradientEntry id="arrowFill2" color="0" alpha="0.8" />
                        </s:RadialGradient>
                    </s:fill>
                </s:Path>
            </fx:Component>
            <!--- Displays the renderer's label property, which is set to the column's <code>headerText</code>.
            It must be an instance of a <code>TextBase</code>, like <code>s:Label</code>.
            <p>This visual element is added to the <code>labelDisplayGroup</code> by the renderer's
            <code>prepare()</code> method.   Any size/location constraints specified by the labelDisplay
            define its location relative to the labelDisplayGroup.</p>
            <p>This value is specified with a <code>fx:Declaration</code> and can be overridden
            by a declaration with <code>id="labelDisplay"</code>
            in an MXML subclass.</p>
            @langversion 3.0
            @playerversion Flash 10
            @playerversion AIR 2.0
            @productversion Flex 4.5
            -->
            <s:Label id="labelDisplay"
                     verticalCenter="1" left="0" right="0" top="0" bottom="0"
                     textAlign="start"
                     fontWeight="bold"
                     verticalAlign="middle"
                     maxDisplayedLines="1"
                     showTruncationTip="true" />
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import net.awl.ismp.console.components.misc.FilterCriteria;
                import net.awl.ismp.console.events.ColumnFilteredEvent;
                import net.awl.ismp.console.events.ColumnResizedEvent;
                import mx.events.ResizeEvent;
                import spark.components.gridClasses.IGridVisualElement;
                import mx.core.IVisualElement;
                import spark.components.DataGrid;
                import spark.components.GridColumnHeaderGroup;
                import spark.components.gridClasses.GridColumn;
                import spark.primitives.supportClasses.GraphicElement;
                // chrome color constants and variables
                private static const DEFAULT_COLOR_VALUE:uint = 0xCC;
                private static const DEFAULT_COLOR:uint = 0xCCCCCC;
                private static const DEFAULT_SYMBOL_COLOR:uint = 0x000000;
                private static var colorTransform:ColorTransform = new ColorTransform();
                 *  @private
                private function dispatchChangeEvent(type:String):void
                    if (hasEventListener(type))
                        dispatchEvent(new Event(type));                   
                protected function onColumnResize(event:ResizeEvent):void
                    dispatchEvent(new ColumnResizedEvent(ColumnResizedEvent.COLUMNRESIZED_EVT,this.width,this.column.columnInde x));
                //  maxDisplayedLines
                private var _maxDisplayedLines:int = 1;
                [Bindable("maxDisplayedLinesChanged")]
                [Inspectable(minValue="-1")]
                 *  The value of this property is used to initialize the
                 *  <code>maxDisplayedLines</code> property of this renderer's
                 *  <code>labelDisplay</code> element.
                 *  @copy spark.components.supportClasses.TextBase#maxDisplayedLines
                 *  @default 1
                 *  @langversion 3.0
                 *  @playerversion Flash 10
                 *  @playerversion AIR 1.5
                 *  @productversion Flex 4.5
                public function get maxDisplayedLines():int
                    return _maxDisplayedLines;
                override protected function stateChanged(oldState:String, newState:String, recursive:Boolean):void
                    trace("state changed from : "+oldState+" to "+newState);
                    super.stateChanged(oldState, newState, recursive);
                 *  @private
                public function set maxDisplayedLines(value:int):void
                    if (value == _maxDisplayedLines)
                        return;
                    _maxDisplayedLines = value;
                    if (labelDisplay)
                        labelDisplay.maxDisplayedLines = value;
                    invalidateSize();
                    invalidateDisplayList();
                    dispatchChangeEvent("maxDisplayedLinesChanged");
                //  sortIndicator
                private var _sortIndicator:IFactory;
                private var sortIndicatorInstance:IVisualElement;
                [Bindable("sortIndicatorChanged")]
                 *  A visual element that's displayed when the column is sorted.
                 *  <p>The sortIndicator visual element is added to the <code>sortIndicatorGroup</code>
                 *  by this renderer's <code>prepare()</code> method.  Any size/location constraints
                 *  specified by the sortIndicator define its location relative to the sortIndicatorGroup.</p>
                 *  @default null
                 *  @langversion 3.0
                 *  @playerversion Flash 10
                 *  @playerversion AIR 1.5
                 *  @productversion Flex 4.5
                public function get sortIndicator():IFactory
                    return (_sortIndicator) ? _sortIndicator : defaultSortIndicator;
                 *  @private
                public function set sortIndicator(value:IFactory):void
                    trace("setSortIndicator");
                    if (_sortIndicator == value)
                        return;
                    _sortIndicator = value;
                    if (sortIndicatorInstance)
                        sortIndicatorGroup.includeInLayout = false;
                        sortIndicatorGroup.removeElement(sortIndicatorInstance);
                        sortIndicatorInstance = null;
                    invalidateDisplayList();
                    dispatchChangeEvent("sortIndicatorChanged");
                 *  @private
                 *  Create and add the sortIndicator to the sortIndicatorGroup and the
                 *  labelDisplay into the labelDisplayGroup.
                override public function prepare(hasBeenRecycled:Boolean):void
                    trace("prepare !!");
                    super.prepare(hasBeenRecycled);
                    if (labelDisplay && labelDisplayGroup && (labelDisplay.parent != labelDisplayGroup))
                        labelDisplayGroup.removeAllElements();
                        labelDisplayGroup.addElement(labelDisplay);
                    trace(sortIndicator);
                    trace("sortIndicatorInstance : "+sortIndicatorInstance);
                    const column:GridColumn = this.column;
                    if (sortIndicator && column && column.grid && column.grid.dataGrid && column.grid.dataGrid.columnHeaderGroup)
                        const dataGrid:DataGrid = column.grid.dataGrid;
                        const columnHeaderGroup:GridColumnHeaderGroup = dataGrid.columnHeaderGroup;
                        if (columnHeaderGroup.isSortIndicatorVisible(column.columnIndex))
                            if (!sortIndicatorInstance)
                                sortIndicatorInstance = sortIndicator.newInstance();
                                sortIndicatorGroup.addElement(sortIndicatorInstance);
                                chromeColorChanged = true;
                                invalidateDisplayList();
                            // Initialize sortIndicator
                            sortIndicatorInstance.visible = true;
                            const gridVisualElement:IGridVisualElement = sortIndicatorInstance as IGridVisualElement;
                            if (gridVisualElement)
                                gridVisualElement.prepareGridVisualElement(column.grid, -1, column.columnIndex);
                            sortIndicatorGroup.includeInLayout = true;
                            sortIndicatorGroup.scaleY = (column.sortDescending) ? 1 : -1;
                        else
                            if (sortIndicatorInstance)
                                sortIndicatorGroup.removeElement(sortIndicatorInstance);
                                sortIndicatorGroup.includeInLayout = false;
                                sortIndicatorInstance = null;
                private var chromeColorChanged:Boolean = false;
                private var colorized:Boolean = false;
                 *  @private
                 *  Apply chromeColor style.
                override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
                    //trace("update display list");
                    // Apply chrome color
                    if (chromeColorChanged)
                        var chromeColor:uint = getStyle("chromeColor");
                        if (chromeColor != DEFAULT_COLOR || colorized)
                            colorTransform.redOffset = ((chromeColor & (0xFF << 16)) >> 16) - DEFAULT_COLOR_VALUE;
                            colorTransform.greenOffset = ((chromeColor & (0xFF << 8)) >> 8) - DEFAULT_COLOR_VALUE;
                            colorTransform.blueOffset = (chromeColor & 0xFF) - DEFAULT_COLOR_VALUE;
                            colorTransform.alphaMultiplier = alpha;
                            transform.colorTransform = colorTransform;
                            var exclusions:Array = [labelDisplay, sortIndicatorInstance];
                            // Apply inverse colorizing to exclusions
                            if (exclusions && exclusions.length > 0)
                                colorTransform.redOffset = -colorTransform.redOffset;
                                colorTransform.greenOffset = -colorTransform.greenOffset;
                                colorTransform.blueOffset = -colorTransform.blueOffset;
                                for (var i:int = 0; i < exclusions.length; i++)
                                    var exclusionObject:Object = exclusions[i];
                                    if (exclusionObject &&
                                        (exclusionObject is DisplayObject ||
                                            exclusionObject is GraphicElement))
                                        colorTransform.alphaMultiplier = exclusionObject.alpha;
                                        exclusionObject.transform.colorTransform = colorTransform;
                            colorized = true;
                        chromeColorChanged = false;
                    super.updateDisplayList(unscaledWidth, unscaledHeight);
                 *  @private
                override public function styleChanged(styleProp:String):void
                    var allStyles:Boolean = !styleProp || styleProp == "styleName";
                    super.styleChanged(styleProp);
                    if (allStyles || styleProp == "chromeColor")
                        chromeColorChanged = true;
                        invalidateDisplayList();
                protected function managefilterField(event:MouseEvent):void
                    trace("double click sortIndicator : "+this.sortIndicatorInstance);
                    this.filterInput.visible=!this.filterInput.visible;
                    this.filterInput.includeInLayout=this.filterInput.visible;
                    this.filterSpacer.visible=this.filterInput.visible;
                    this.filterSpacer.includeInLayout=this.filterInput.visible;
                    if(!this.filterInput.visible)
                        this.filterInput.text="";
                        dispatchEvent(new ColumnFilteredEvent(ColumnFilteredEvent.COLUMNFILTERED_EVT,new FilterCriteria(this.column.dataField,this.filterInput.text)));
                    this.filterInput.setStyle("borderColor",0xFF6319);
                    this.filterInput.setStyle("focusColor",0xFF6319);
                    //this.filterInput.setStyle(
                protected function onTextInputSelection(event:MouseEvent):void
                    event.stopImmediatePropagation();
                    this.filterInput.setStyle("borderColor",0xFF6319);
                    this.filterInput.setStyle("focusColor",0xFF6319);
                protected function onKeyUp(event:KeyboardEvent):void
                    if(event.charCode==Keyboard.ENTER)
                        stage.focus=null;
                protected function onFocusOut(event:FocusEvent):void
                    this.filterInput.setStyle("borderColor",0x00ff00);
                    this.filterInput.setStyle("focusColor",0x70B2EE);
                    dispatchEvent(new ColumnFilteredEvent(ColumnFilteredEvent.COLUMNFILTERED_EVT,new FilterCriteria(this.column.dataField,this.filterInput.text)));
            ]]>
        </fx:Script>
        <s:states>
            <s:State name="normal" />
            <s:State name="hovered" />
            <s:State name="down" />
        </s:states>     
        <!-- layer 1: shadow -->
        <!--- @private -->
        <s:Rect id="shadow" left="-1" right="-1" top="-1" bottom="-1" radiusX="2">
            <s:fill>
                <s:LinearGradient rotation="90">
                    <s:GradientEntry color="0x000000"
                                     color.down="0xFFFFFF"
                                     alpha="0.01"
                                     alpha.down="0" />
                    <s:GradientEntry color="0x000000"
                                     color.down="0xFFFFFF"
                                     alpha="0.07"
                                     alpha.down="0.5" />
                </s:LinearGradient>
            </s:fill>
        </s:Rect>
        <!-- layer 2: fill -->
        <!--- @private -->
        <s:Rect id="fill" left="0" right="0" top="0" bottom="0">
            <s:fill>
                <s:LinearGradient rotation="90">
                    <s:GradientEntry color="0xFFFFFF"
                                     color.hovered="0xBBBDBD"
                                     color.down="0xAAAAAA"
                                     alpha="0.85" />
                    <s:GradientEntry color="0xD8D8D8"
                                     color.hovered="0x9FA0A1"
                                     color.down="0x929496"
                                     alpha="0.85" />
                </s:LinearGradient>
            </s:fill>
        </s:Rect>
        <!-- layer 3: fill lowlight -->
        <!--- @private -->
        <s:Rect id="lowlight" left="0" right="0" top="0" bottom="0">
            <s:fill>
                <s:LinearGradient rotation="270">
                    <s:GradientEntry color="0x000000" ratio="0.0" alpha="0.0627" />
                    <s:GradientEntry color="0x000000" ratio="0.48" alpha="0.0099" />
                    <s:GradientEntry color="0x000000" ratio="0.48001" alpha="0" />
                </s:LinearGradient>
            </s:fill>
        </s:Rect>
        <!-- layer 4: fill highlight -->
        <!--- @private -->
        <s:Rect id="highlight" left="0" right="0" top="0" bottom="0">
            <s:fill>
                <s:LinearGradient rotation="90">
                    <s:GradientEntry color="0xFFFFFF"
                                     ratio="0.0"
                                     alpha="0.33"
                                     alpha.hovered="0.22"
                                     alpha.down="0.12"/>
                    <s:GradientEntry color="0xFFFFFF"
                                     ratio="0.48"
                                     alpha="0.33"
                                     alpha.hovered="0.22"
                                     alpha.down="0.12" />
                    <s:GradientEntry color="0xFFFFFF"
                                     ratio="0.48001"
                                     alpha="0" />
                </s:LinearGradient>
            </s:fill>
        </s:Rect> 
        <!-- layer 5: highlight stroke (all states except down) -->
        <!--- @private -->
        <s:Rect id="highlightStroke" left="0" right="0" top="0" bottom="0" excludeFrom="down">
            <s:stroke>
                <s:LinearGradientStroke rotation="90" weight="1">
                    <s:GradientEntry color="0xFFFFFF" alpha.hovered="0.22" />
                    <s:GradientEntry color="0xD8D8D8" alpha.hovered="0.22" />
                </s:LinearGradientStroke>
            </s:stroke>
        </s:Rect>
        <!-- layer 6: highlight stroke (down state only) -->
        <!--- @private -->
        <s:Rect id="hldownstroke1" left="0" right="0" top="0" bottom="0" includeIn="down">
            <s:stroke>
                <s:LinearGradientStroke rotation="90" weight="1">
                    <s:GradientEntry color="0x000000" alpha="0.25" ratio="0.0" />
                    <s:GradientEntry color="0x000000" alpha="0.25" ratio="0.001" />
                    <s:GradientEntry color="0x000000" alpha="0.07" ratio="0.0011" />
                    <s:GradientEntry color="0x000000" alpha="0.07" ratio="0.965" />
                    <s:GradientEntry color="0x000000" alpha="0.00" ratio="0.9651" />
                </s:LinearGradientStroke>
            </s:stroke>
        </s:Rect>
        <!--- @private -->
        <s:Rect id="hldownstroke2" left="1" right="1" top="1" bottom="1" includeIn="down">
            <s:stroke>
                <s:LinearGradientStroke rotation="90" weight="1">
                    <s:GradientEntry color="0x000000" alpha="0.09" ratio="0.0" />
                    <s:GradientEntry color="0x000000" alpha="0.00" ratio="0.0001" />
                </s:LinearGradientStroke>
            </s:stroke>
        </s:Rect>
        <!--<s:Rect id="fill" left="0" right="0" top="0" bottom="0">
            <s:fill>
                <s:LinearGradient rotation="90">
                    <s:GradientEntry color.normal="0xf9f9f9" color.hovered="0xfcfdfa"
                                     color.down="0xdceac2" alpha="0.85" />
                    <s:GradientEntry color.normal="0xeaeaea" color.hovered="0xdceac2"
                                     color.down="0xd2e1b5" alpha="0.85" />
                </s:LinearGradient>
            </s:fill>
        </s:Rect>-->
        <!--<s:VGroup left="7" right="7" top="5" bottom="5" gap="6" verticalAlign="middle">
            <s:TextInput width="100%" />
            <s:HGroup width="100%">
                <s:Group id="labelDisplayGroup" width="100%" />
                <s:Group id="sortIndicatorGroup" includeInLayout="false" />
            </s:HGroup>
        </s:VGroup>-->
        <s:VGroup verticalAlign="middle" left="7" top="5" right="7" bottom="5" gap="2" >
            <s:TextInput id="filterInput" width="100%" visible="false" includeInLayout="false" keyUp="onKeyUp(event)" focusOut="onFocusOut(event)" click="onTextInputSelection(event)"/>
            <s:Spacer id="filterSpacer" visible="false" includeInLayout="false" height="5" />
        <s:HGroup width="100%" height="100%" verticalAlign="middle">
            <s:Group id="labelDisplayGroup" width="100%" />
            <s:Group id="sortIndicatorGroup" includeInLayout="false" />
        </s:HGroup>
        </s:VGroup>
    </s:GridItemRenderer>

    Based on your idea, i've intercepted the click event and I use stopImmediatePropagation.
    THen i added an image to sort the column. So if the image is clicked the sort is ok.

  • 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.

  • TableView Column Mouse Double Click

    Hi,
    I have a table view, if a user double clicks a row - I do something. I notice that if I double click on the header of a column, I receive an ActionEvent just as if the user double clicked a row. Single clicks on the header perform sorting as expected.
    Is here a way to see if the double click mouse event happened on the column header?
    Thanks.

    Depends how you set your event, imo there should be a way to give an event to just a row, if you defined your rows and columns some way(I'm not too sure as I don't have much experience with tables yet...)
    row.addEventHandler(mousEvent.ANY, some event);

  • Resize tabs only when double click on tab name

    I have this code which resizes tab when it's clicked twice no matter where I click on the tab.
    VBox stackedTitledPanes = createStackedTitledPanes();
       ScrollPane scroll = makeScrollable(stackedTitledPanes);
       final TabPane tabPane = new TabPane();
       final BorderPane mainPane = new BorderPane();
       final Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
      tabPane.setStyle("-fx-font-size: 12pt;"); // Set global size for the font
       // Create Tabs
       Tab tabA = new Tab();
      tabPane.setOnMouseClicked(new EventHandler<MouseEvent>()
       private double sizeX, sizeY;
       private boolean first = true;
       @Override
       public void handle(MouseEvent me)
       if (first)
      sizeX = mainPane.getWidth();
      sizeY = mainPane.getHeight();
      first = false;
       if (me.getButton().equals(MouseButton.PRIMARY) && me.getClickCount() % 2 == 0)
       if (sizeX != mainPane.getWidth() || sizeY != mainPane.getHeight())
      mainPane.setPrefSize(sizeX, sizeY);
       else
      mainPane.setPrefSize(primaryScreenBounds.getWidth(), primaryScreenBounds.getHeight());
      tabA.setText("Main Component");
      tabA.setContextMenu(makeTabContextMenu(tabA, tabPane));  // Set right mouse click menu
       // Add something in Tab
       StackPane tabA_stack = new StackPane();
      tabA_stack.setAlignment(Pos.CENTER);
      tabA_stack.getChildren().add(scroll);
      tabA.setContent(tabA_stack);
      tabPane.getTabs().add(tabA);
       Tab tabB = new Tab();
      tabB.setText("Second Component");
      tabB.setContextMenu(makeTabContextMenu(tabB, tabPane));  // Set right mouse click menu
       // Add something in Tab
       StackPane tabB_stack = new StackPane();
      tabB_stack.setAlignment(Pos.CENTER);
      tabB_stack.getChildren().add(new Label("Label@Tab B"));
      tabB.setContent(tabB_stack);
      tabPane.getTabs().add(tabB);
       Tab tabC = new Tab();
      tabC.setText("Last Component");
      tabC.setContextMenu(makeTabContextMenu(tabC, tabPane));  // Set right mouse click menu
       // Add something in Tab
       StackPane tabC_vBox = new StackPane();
      tabC_vBox.setAlignment(Pos.CENTER);
      tabC_vBox.getChildren().add(new Label("Label@Tab C"));
      tabC.setContent(tabC_vBox);
      tabPane.getTabs().add(tabC);
      mainPane.setCenter(tabPane);
      mainPane.setPrefSize(300, 500);
       //mainPane.setLayoutX(5); // Horizontal Position
      mainPane.setLayoutY(32);   // Vertical Position
      scroll.setPrefSize(395, 580);
      scroll.setLayoutX(5);
      scroll.setLayoutY(32);
    Can you tell me how I can modify the code in a way that I can size the tab only when I double click on a tab name?

    See:
    *https://support.mozilla.com/kb/Firefox+keeps+opening+many+tabs+or+windows

  • 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.

  • Resize JTable that doesn't include header

    hi all
    I want to insert the table that is not include header and want to allow the user to resize the column
    thanx

    You already asked the same question in this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=526540]post.
    Don't clutter the forum by asking the same question over and over again. You won't get an answer faster.

  • JTable's cell double click question...

    Hello everyone,
    My JTable has some cells with icons and text, and some contains only text.
    All cells are editable, so double clicking on it goes to "edit mode" where user enters new value for the cell.
    Here is my question: Can I somehow determine if user has clicked on an icon?
    What I'm trying to do is to put additional information for cell (some comment), and if comment exists, icon will appear.
    Double clicking on that icon, dialog will show that comment.
    Thanks in advance!

    You did not mention that before. ...You are absolutely right, I didn't.
    Let me emphasize importance of this:
    Can I somehow determine if user has clicked on an icon?
    And when I said "clicked" I mean double click when entering edit mode
    of a cell.
    If I could somehow determine that, I could than
    perform desired action (open a dialog, or something else).
    Thank you for your help so far.

  • 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

  • Retrieving JTable column number when clicked

    Hello, I'm new in this forum but not so new to java.....but I'm really worried about an issue with an application made using Swing.
    Well , my problem is with JTables. It's about selecting a table cell in order to get the column index when selected. Ok I'm able to get the column index when the cells are simple cells, but the problem appears when the cell is a JComboBox....It's imposible to retrieve the column index. I was trying and trying but finally I couldn't see what the solution is......and I must get that problematic index....
    Please, I really need and advice.
    Thanks in advance for your help
    Best Regards
    Mariojulio Zaldivar

    Hello, I created a short example of my java class:
    * NewClass.java
    * Created on 26 de octubre de 2007, 0:03
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package pruebas;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    public class TableDemoApplet extends JApplet {
    JTable table;
    public TableDemoApplet() {
    createGUI(getContentPane());
    public void createGUI(Container contentPane) {
    Object[][] rowData = new String[][] { {"98-43", "AraAra! SL"},
    {"81-31", "Aragones Transports SA"},
    {"12-72", "Rocca SL"},
    {"99-10", "Rodriguez e Hijos SA"},
    {"00-65", "Rimbau Motors SL"} };
    table = new JTable(rowData, new String[] {"Part No", "Provider"});
    JComboBox companyComboBox = new JComboBox(new Object[] {"AraAra! SL", "Aragones Transports SA", "Rocca SL", "Rodriguez e Hijos SA", "Rimbau Motors SL"});
    companyComboBox.setEditable(true);
    //new S15WorkingBackspace(companyComboBox);
    // setup the ComboBoxCellEditor, DefaultCellEditor won't work!
    table.getColumnModel().getColumn(1).setCellEditor(new ComboBoxCellEditor(companyComboBox));
    table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setPreferredScrollableViewportSize(new Dimension(400, 100));
    addListener();
    JScrollPane scrollPane = new JScrollPane(table);
    contentPane.setLayout(new java.awt.FlowLayout());
    contentPane.add(scrollPane);
    contentPane.add(new JTextField("HALLO!"));
    public void addListener(){
    /*table.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
    int column = table.getSelectedColumn();
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    // get most recently selected column index
    int column = table.getSelectedColumn();
    System.err.println("numero de columna: " + column);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(3);
    TableDemoApplet demo = new TableDemoApplet();
    demo.createGUI(frame.getContentPane());
    frame.pack(); frame.setVisible(true);
    I'm showing there the wrong behavior of the JTable, I hope this help you to help me :)
    Thanks a lot for your time!!
    Greetings
    Mariojulio Zaldivar

  • Expanding the datagrid column on double-click?

    The title says it all...
    How do i get it to expand to certain value?

    This is not a Flex Builder question, so it should go in the
    General Discussion forum, not here.
    Regarding the question, set the colum width.
    Tracy

  • Jtable column resize

    Hi all!
    i'm using:
    jTable1.getColumnModel().getColumn(1).setPreferredWidth(7);     
    to resize jtable column width but it's not working, do you know what can be happening?
    thanks!

    All you've done is say what size you would prefer.
    You then have to force the component to repaint, with something like
                jTable1.invalidate();
                jTable1.doLayout();
                jTable1.repaint();Ps. I posted a nice utility class to automaticaly fit the JTable columns to the exact size required here.
    http://forum.java.sun.com/thread.jspa?forumID=54&messageID=2532529&threadID=527301
    regards,
    Owen

  • Problem while displaying the data when double clicked on JTable element

    Hi All,
    i have one List box( JList ) and one table (JTable). Both JTable and JList are positioned on the same Frame. I am able to drag the elements from JList to JTable and also i have added the mouse click action on both List box and JTable.
    if i double click on JList element, that will popup one dialog box.
    if i double click on JTable cell element that was dragged from JList, that will popup same dialog box which was opened earlier for JList action.
    But my problem here is:
    Suppose if i drag the four elements one by one from JList to JTable and (after four elements dragged) double clicked the first element which was dragged first that displayed the popup dialog box structure correctly but the data displayed in that was not correct. It is showing the data of recent dragged element( i.e, fourth element).
    But if i double click on JList element that is showing the correct data according to the double clicked element.
    What might be the problem here, why it was not displaying the correct data when double clicked on JTable element.
    Please help me here.
    Many thanks in advance.
    The following code is used in mouse clicked event method of JList
    private void listMouseClicked(java.awt.event.MouseEvent evt) {                                              
             if(evt.getClickCount()==2){
             AssigningResourcesUI assignResource=new AssigningResourcesUI(this,true);
             assignResource.show();
    }                AND The following code is used in mouse click enevet method of JTable.
    private void tableMouseClicked(java.awt.event.MouseEvent evt) {                                          
            if(evt.getClickCount()==2){
             int row=table.rowAtPoint(new Point(evt.getX(), evt.getY()));
             int col=table.columnAtPoint(new Point(evt.getX(), evt.getY()));
             if(row==-1||col==-1){
                 return;
              Object obj=table.getModel().getValueAt(row, col);
             if(obj==null||(obj.equals(""))){
               }else{
             AssigningResourcesUI assignResource=new AssigningResourcesUI(this,true);
             assignResource.show();
         }            Thanks & Regards,
    Maadhav....
    Edited by: maadhav on Jul 1, 2009 7:22 AM

    I doubt it is related to your problem but:
    int row=table.rowAtPoint(new Point(evt.getX(), evt.getY()));Why are you creating a new Point? Just use evt.getPoint().
    Object obj=table.getModel().getValueAt(row, col);Don't get the data through the model method, get the data through the table method:
    Object obj = table.getValueAt(...)
    This way it will work even if the table happens to be sorted.
    Instead of creating a AssigningResourcesUI object, just disply the value retrieved from the model. That way you know whether the problem is with the mouse event code or your UI class. Like Walter suggested above I"m guess the problem is with your UI class.

  • Dynamically resize JTable cell to fit a JList

    Hi!
    I've been banging my head trying to add some dynamic behavior to a TableCellEditor. In short I'm trying trying to make it resize the height of the current row (the one it is in) to reflect the changes made to the JList used to let the user edit the cells value (which is a list of items).
    I've come across some threads dealing with the problem of resizing a cell to fit its content. This however is usually only done once (in the 'getTableCellEditorComponent' function) and so only provides half the answer. Also, since the editor is only active during cell editing I've been trying to make it revert to the old cell height after the editing is done.
    So far I have not come up with any decent solution to this problem and was hoping someone out there might have an idea or have read something similar and can point me to something helpful... anyone?
    Cheers!
    Teo

    The Swing tutorial on[url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables shows how to dynamically change the size to Table Columns.
    If you need help calculating the acutal size then try searching the forum. Using keywords "resize jtable column" (keywords I took directly from your topic title) I found some promising postings.

Maybe you are looking for