JTable in JScrollPane, preferred size

When I put a JTable in a JScrollPane, the JScrollPane seems to want to be very big. How does the scroll pane determine its size? run this code for an example..
import javax.swing.*;
public class TestPanel extends JPanel
public TestPanel()
     add(new JScrollPane(new JTable(1,1)));
public static void main(String args[])
     JFrame f = new JFrame("big table test");
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     TestPanel thePanel = new TestPanel();
     f.setContentPane(thePanel);
     f.pack();
     f.show();

public class TestPanel extends JPanel {
  public TestPanel() {
    JTable jt = new JTable(1,1);
    jt.setPreferredScrollableViewportSize(new Dimension(100,100));  // Do this
    JScrollPane jsp = new JScrollPane(jt);
    jsp.setPreferredSize(new Dimension(100,100));  //OR this
    add(new JScrollPane(new JTable(1,1)));
}

Similar Messages

  • JScrollPane content changes preferred size; how to show the bars

    Before I have to delve deeply into the code of JScrollPane... I have a component inside a JScrollPane with as-needed scrollbars that changes its preferred size. I can invalidate and repaint every component in the tree, but the scrollbars don't show until I do a hide and reshow the window. Why?

    if you are happy with an answer - even your own self-muttering <g> please mark the question as answered.
    Cheers
    Jeanette

  • Update JScrollBar Extent when JScrollPane Component Changes Preferred Size

    Hi folks,
    I have an interesting, but concise problem that I've been working on for a few days but haven't had any luck.
    In Java 1.5 or Java6, I have a JScrollPane which contains a JPanel. The settings of the scrollbar (for example, the Extent [the width of the "thumb" or "slider" on the scrollbar]) are determined based on the dimension of the underlying contained component, in particular, the Preferred Size.
    My problem is this. The underlying component has a "zoom" capability, such that the actual size of the component can and does change (i.e., zooming out reduces its preferred size).
    Happily, the consequence of this design is that the "size" or extent of the scrollbar sliders/thumbs adjusts to give visual indication of the proportion of the current view (ViewPort View dimension) to the underlying component's dimension.
    The problem is, the scrollbar sliders do NOT automatically update their size in response to programatically changing the JScrollPane's contained component's PreferredSize. They WILL be updated if I RESIZE the parent JFrame manually.
    But for the life of me, I can't get those sliders to update programatically. I've tried repaint(), update, validate(), etc. on the JScrollPane but no luck.
    I've done a debug to get into the stack trace of the Sun code during run time, and there's a lot going on... there's a doLayout(), a reshape() (deprecated), firing various property changes, but I just can't seem to find a good hook into getting the scrollbar to update its internal Bounds model and repaint accordingly. Calling setBounds() on the JScrollPane I think would trigger it, however, looking at the code.. it seems to ignore firing property events and repainting of the bounds themselves didn't actually change (i.e. no action happens if the current dimension and specified dimension in the argument to setBounds() are the same).
    Any ideas here on how to this to get those sliders to update programatically with a new value for the extent?
    Thanks,
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Understood! It was my intention to give credit and now I'm happy to do so! I've now assigned the Duke Points. Minor usability issue, it was not obvious how to do this the first time (and I did poke around a little before I gave up earlier in the day, reverting to just assigning him the correct question). I've got it now though! Thanks again--definitely knocked out an issue I was having today and allowed me to move on to add'l development work today.
    All the best!
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem with setting preferred size

    Why in the following code the preferred size doesn't change ?
    import java.awt.*;
    import javax.swing.*;
    public class MyTest extends JFrame {
         private GridBagLayout gridBagLayout = new GridBagLayout();
         private JPanel panel = new JPanel(gridBagLayout);
         private JScrollPane scrollPane = new JScrollPane(panel);
         private JTable table;
         public MyTest() {
              table = new JTable(2, 3);
              panel.add(table);
              add(scrollPane);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         public static void main(String[] args) {
              MyTest frame = new MyTest();
              frame.scrollPane.setPreferredSize(new Dimension(700, 500));
    }

    Hi...
    The problem in your code is this:MyTest frame = new MyTest();
    frame.scrollPane.setPreferredSize(new Dimension(700, 500));Here you give the PreferredSize after create the frame... you have to do this before create the frame...
    Try to use like this:import java.awt.*;
    import javax.swing.*;
    public class MyTest extends JFrame {
         private GridBagLayout gridBagLayout = new GridBagLayout();
         private JScrollPane scrollPane;
         private JTable table;
         public MyTest() {
              table = new JTable(2, 3);
              scrollPane = new JScrollPane(table);
                    scrollPane.setPreferredSize(new Dimension(700, 500));
              add(scrollPane);               
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
              setVisible(true);
         public static void main(String[] args) {
              MyTest frame = new MyTest();          
    }Regards...

  • Determine preferred size to be set for the JPanel attached to JScrollBar

    Determine what preferred size to be set for the JPanel attached to JScrollBar.
    Hello all, I am having a JPanel, where new components will be added into it during run-time. When there are too many components inside the JPanel, I need to re-set the JPanel preferred size so that the JScrollBar is scrollable.
    I was wondering what is the good method to determine the preferred size of JPanel during runtime?
    Currently, I am using
    myJPanel.setPreferredSize(new Dimension(
    numberOfNewComponent * preferred width of each component,
    numberOfNewComponent * preferred height of each component
    ));Is there any better alternative?
    Thank you very much.
    yccheok

    Usually a container such as JPanel will calculate its own preferred size from its layout manager - calling setPreferredSize is often unnecessary.
    When you add a component to your JPanel its preferred size will change automatically.
    What's wrong with the behaviour when you simply add your JPanel to a JScrollPane and let it manage its own preferred size?
    Hope this helps.

  • Why is my panel's preferred size changing as I resize the window?

    I have a JEditorPane inside a JPanel, which is wrapped in a JScrollPane. The JEditorPane contains a wide image and I expect to see horizontal scrollbars if the viewport is smaller than the minimum size needed to display the image.
    When my panel is displayed for the first time and the viewport size is smaller than the image, the horizontal scrollbars appear and the size of the scrollable area is set to the width of the image. This is the expected behaviour. When I resize the panel so that its is wider than the image and the scrollbars are no longer needed, the scrollbars disappear. However, when I shrink the panel back, the scrollbars appear at the correct "time" (when the edge of the image is reached), but the scrollable area is too wide, similar to the size I had stretched the panel out to.
    I am printing out the preferred size that the panel is returning (which will be used to set the scrollable area), and it seems to keep changing. The preferred size seems to grow with the panel's actual size, but it does not shrink back when I make the panel smaller.
    Anyone has any idea on what might be happening?

    Welcome to the Sun forums.
    >
    Anyone has any idea on what might be happening?>It probably has to do with the Java code used. Can you prepare an SSCCE that shows the behaviour?

  • JLists, JScrollPanes different size when empty than when populate

    I have a JList which is inside of a JScrollpane, which is inside of a panel who's layout is controlled with a GridBagLayout.
    When I first start my program, and the JList is empty, the JList is the size I want. The GridBagLayout is set to fill both directions for the JList.
    However, when I add an item to the JList, the GridBagLayout resizes the cell that the JList is inside of just slightly. How can I prevent this? It is obnoxious to use the program when the all the items on the screen change size a little bit when a JList goes empty as opposed to when it is populate.
    Why does a JList (inside of a scrollpane) get a different size assigned to it by the grid bag layout when it is empty, as to when it has items in it?

    Setting the preferred size on the scroll pane containing the list corrects 1/2 of my problem - The vertical space alloted by the grid bag layout no longer changes with an empty list compared to a populated list.
    I'll give the first guy a couple of points.
    The rest of the points are still up for grabs ----
    I still have problems with side by side lists which have items that can be moved back and forth.
    I tried setting min size and preferred size on the scroll panes.
    I tried putting each scroll pane into its own JPanel that had a Grid Layout, and then added the panels to my main panel with a grid bag layout, and weights set to .5 for horizontal expansion.
    I even tried putting min, preferred, and max sizes on these panels.
    I still cannot make the grid bag layout alot equal space to the left and right scroll panes.
    Is there any way that I can get the space alloted between my components to be roughly
    ====================
    || 45% || 5% || 45% ||
    || JList || buttons || JList ||
    ====================
    Ane then have only the outside two columns change size when the window is resized (in equal proportion)???

  • Custom column headers for JTable in JScrollPane

    I want a heirachical header structure on a scrolled JTable. I've successfully generated a second JTableHeader which moves it's tabs with the normal header. If I add the secondary JTableHeader into the container above the whole scroll pane it's does almost what I want, but it's not quite correctly aligned.
    What I want to do is to put both the automaticaly generated JTableHeader and my extra one into the JScrollPane's column header area.
    I wrapped the two headers together into a vertical Box and tried calling the setColumnHeaderView() on the scrollpane, and then creating a JViewport and using setColumnHeader(). Niether seems to have any effect. The basic table header obstinately remains unaltered.
    There seems to be some special processing going on when JTable and JScrollPane get together, but I can't understand how replacing the column header viewport can be ineffective.

    Thanks. I think I've just cracked it more thoroughly, though. [I found this bug report|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5032464]. This has guided me to a work-around that seems stable so far. I'm using an extended JTable class anyway (mostly to do with table header width behaviour). I've added a field to my own table class and the following override:
    The trick is to work out where the dirty deed is done, having search all the scroll pane related classes for special casing JTable.
    public class STable extends JTable {
        @Override
        protected void configureEnclosingScrollPane() {
            if (secondaryHeader == null) {
                super.configureEnclosingScrollPane();
            } else {
                Container p = getParent();
                if (p instanceof JViewport) {
                    Container gp = p.getParent();
                    if (gp instanceof JScrollPane) {
                        JScrollPane scrollPane = (JScrollPane) gp;
                        // Make certain we are the viewPort's view and not, for
                        // example, the rowHeaderView of the scrollPane -
                        // an implementor of fixed columns might do this.
                        JViewport viewport = scrollPane.getViewport();
                        if (viewport == null || viewport.getView() != this) {
                            return;
                        JPanel hdrs = new JPanel();
                        hdrs.setLayout(new BorderLayout());
                        hdrs.add(secondaryHeader.getHeader(), BorderLayout.NORTH);
                        hdrs.add(getTableHeader(), BorderLayout.SOUTH);
                        scrollPane.setColumnHeaderView(hdrs);
                        //  scrollPane.getViewport().setBackingStoreEnabled(true);
                        Border border = scrollPane.getBorder();
                        if (border == null || border instanceof UIResource) {
                            Border scrollPaneBorder =
                                    UIManager.getBorder("Table.scrollPaneBorder");
                            if (scrollPaneBorder != null) {
                                scrollPane.setBorder(scrollPaneBorder);
        }I'm hopeful that will prevent the column header view from being overwritten by later layout operations.

  • Preferred size of JEditorPane/ HTML page

    Hi,
    I've loaded an HTML page in a JEditorPane. Since I'm using a layout manager with absolute positioning, I need to know the pane's preferred size.But the preferred size I get is just about (6, 6), although it has a big picture in it. I tried validate() first or to add it with (1,1) to have it set up properly (visible etc.) and then resize it afterwards, but it had no effect. Is there a way to get a preferred size of an HTML page?
    Thanks a lot.
    Greets
    Puce
    Note: Using another layout manager is not a option, since this is a very specialized task.

    I could use this as well. I'm tiling JEditorPanes vertically inside a JPanel using BoxLayout. The problem is that I need to limit the width of the panel, so I need to adjust the sizes accordingly. Any suggestions? I'll give another duke...
    Max

  • How preferred size of JAVA GUI is calculated when the parent component is invisible?

    Hi
    Suppose a Panel has a tabbed pane with two tabs inside it.  If I do setVisible(false) for 2nd tab but not for its child components,
    Will the size of child component's of 2nd tab be considered to calculate the preferred size of the TopPanel ?
    Similarly,  If a Panel has a sub-panel and sub-panel has few child components. If sub-panel is invisible but its child components are visible, they will not be shown on the screen.
    In this case, Will the sizes of sub-panel's child components be considered for calculating the preferred size of the outer panel ?
    Please let me know
    Thanks in advance.

    Are you talking about Java or another language?
    However, when I run this report, JVM tries to allocate these 10 MB objects, but causes an Allocation Failure (AF). Java does get such an error. It can get an OutOfMemoryError.
    At this point, the unusable heap size due to fragmentation is ~100 MB. Again Java doesn't get unusable heap space as the GC will repack the memory to remove fragmentation.
    - is 10 MB object size okay? Is it normal to have object size of 10 MB?In Java it is normal.
    - How can I reduce the fragmentation in the memory?Use Java.

  • How does JEditorPane determine its preferred size?

    Could someone explain how JEditorPane determines the initial preferred
    size? Its default sizing is not giving me what I need and I'm not sure
    how to control it, other than explicitly setting the size with
    setPreferredSize().
    A simple example:
            String s = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 10 20" +
                       "21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39";
            JEditorPane ed = new JEditorPane("text",s);
            JPanel pan = new JPanel();
            pan.setLayout(new BoxLayout(pan,BoxLayout.Y_AXIS));
            pan.add(ed);
            JFrame f = new JFrame();
            f.getContentPane().add(pan);
            f.pack();
            f.setVisible(true);This code generates a window that shows one line, with "1 2 3 4 5 6 7 8 9"
    showing. I'd like to have a larger area showing initially.
    Does the choice of layout manager effect this? (I actually prefer to use
    TableLayout; the above example with a 1x1 TableLayout and widths set to
    PREFERRED yields exactly the same results.)
    Thanks,
    bw

    Set your ruler increments to pixels Preferences>Units & Increments. You can fill the text box with placeholder text Type>Fill with Placeholder text and get a word count from the Info panel with Show Options turned on from the flyout.
    From the Transform panel you can set a text box's width and height

  • Use of minimum, maximum and preferred size?

    Hi,
    What is the use of the three sizes (maximum size, minimun size and preferred size) of component and container?
    And which class use them?
    Thanks for any ideas and input,
    Wing

    I read somewhere on this forum that most layout managers pretty much ignore these properties... just one of them would properly use it (don't know which one, I think it was one of the 'less-common' ones like Card or BoxLayout).
    If somebody has more info I would wanna read it too!

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • JTextField border part of preferred size?

    In an attempt to set the height of a JPanel just tall enough to accommodate its tallest component, a JTextField, I accounted for the preferred height of the JTextField and the insets of the JPanel. However, this failed to provide sufficient height to see (at least) the bottom of the JTextField border.
    I had ignored the height of that border (i.e. the border insets), believing that its height would have been included in the preferred height of the JTextField. Was I wrong?
    JTextField.getPreferredSize()
    Returns the preferred size Dimensions needed for this TextField.
    JComponent.getBorder()
    Returns the border of this component or null if no border is currently set.
    In the Swing component set, borders supercede Insets as the mechanism for creating a (decorated or plain) area around the edge of a component.
    Border.getBorderInsets(Component c)
    Returns the insets of the border.
    Alan Feldstein
    Cosmic Horizon
    http://www.alanfeldstein.com/

    Alan_Feldstein wrote:
    4gui wrote:
    Which layout do you use?
    you must use the layout to locate the componet on the place you want.The JTextFields's container ... has a flow layout.4gui got me thinking about what I should have been thinking about after all. In fact, method FlowLayout.getVgap gives the "vertical gap ... between the components and the borders of the Container." I needed to compensate for that too.
    >
    When I inquire about the JTextField's preferred size, will the numbers include the JTextField's border or not?I think so. It has always made more sense to me to consider the borders to be part of a Component. Now I have seen more evidence in the documentation to support this.
    For example, method FlowLayout.getVgap "gets the vertical gap ... between the components and the borders *of the* Container." Those borders belong to the Container, not to anything outside the Container.
    Method JComponent.getInsets says, "If a border has been set on this component, returns the border's insets ...". My Container is a JComponent and I said before that I had already compensated for its Insets (i.e. the size of its border).
    Since the Container's border is part of the Container, for consistency the JTextField's border would be part of the JTextField.
    I had been looking for a way to explain a discrepancy, by considering the theory that the JTextField's preferred size did not include its border, a theory I was never comfortable with. It turns out that the discrepancy came from failure to compensate for the vertical gap in FlowLayout.
    Since 4gui was on the right track, all of the remaining Duke Stars go to him/her.

  • ScrollPane fill width and preferred size

    I suspect this is going to end up as a feature request, but does anyone know if there is an existing way to have a ScrollPane stretch its content if the available space is greater than the preferred size of the content, but also not shrink the content if the scrollpane is smaller than the preferred size of the content?
    If we have this simple example:
    public void start(Stage stage) throws Exception
        BorderPane contentPane = new BorderPane();
        contentPane.setPrefSize(400, 300);
        contentPane.setStyle("-fx-background-color: blue");
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(contentPane);
        Scene scene = new Scene(scrollPane, 800, 600);
        stage.setScene(scene);
        stage.show();
    } When the window is big, our content pane is left at its preferred size with white space around it and no scroll bars showing. When the window is small our contentPane is still at its preferred size with scrollbars on it and no white space. Much as we'd expect.
    If we add this line of code:
    scrollPane.setFitToWidth(true);Then when the window is big then our contentPane is stretched nicely to fill the available space. When the window is small, the scroll bars don't kick-in (effectively scrolling is turned off) and the contentPane is shrunk to fit the available space.
    What I'd rather have is when the window is small we get scrolling, when the window is big, we get stretching. Possible?
    Cheers,
    zonski

    It is actually possible to do this in markup as well. For example, the following markup creates an observable array list and attaches a controller-based change event handler to it:
    <FXCollections fx:factory="observableArrayList" onChange="#handleListChangeEvent"/> The controller method should look something like this:
    @FXML
    protected void handleListChangeEvent(ObservableListChangeEvent<?> event) {
        // Handle the change event
    }[edit] Note that ObservableListChangeEvent is currently a private class - please feel free to submit a feature request to make this class public if you would like.

Maybe you are looking for