JScrollPane Resizing

Can anyone tell me if there is some method i need to call to have force a JScrollPane to update itself? I have a JComponent inside a JScrollPane and I'm doing some custom graphics within the component. When the graphics are too large i want to scroll.
From the tutorial, I tried to update the preferred size of the component but that doesn't seem to work. I have to manually resize the window for the scrollbars to resize properly.
Setting the maximum vertical scroll bar size does work, but my scrollbar policy must always be set to display the scrollbars. In other words, if my scrollbars are already showing, setting the max size works, but if they are not and the graphics resize to large for the first time, the scroll bars are not painted immediately (i need to manually resize).
Any Suggestions? Thanks in advance.

needed. Btw, other than the javadocs, do you know of
a good source for this type of information?This site?
This is something I had to learn the hard way too; in fact I think a great majority of people learning to build guis in java have this exact same problem. Now that you've seen it and done it you'll know for the future.

Similar Messages

  • JScrollPane resizing problem, I think...

    The Task
    I want to build a dialog that holds different option panels.
    Instead of using a JTabbedPane, I want to use a JTree to select among the different panels.
    I put the tree in a nice scroll pane, place the whole thing in the left side of
    the dialog. I think I have the logic down except for one thing...
    The Problem
    Whenever I click a node when the JTree is expanded, it resizes itself. It does this so that words that go off to the right can be seen.
    I don't want this to happen, but I do have to revalidate the main panel for it to change.
    Apparently, just revalidating the main panel revalidates everything.
    The Question
    Is there a setting in the JTree or the JScrollPane that stops this from happening?
    I have tried to change the LayoutManager, but the same thing happens with GridBagLayout.
    I'll put example code in the following post so you can see my issue. I put the most pertinent code to the front, so that you don't have to read too deeply.
    Can anyone advise me?
    Thanks.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class ScrollPaneProblem extends JDialog
       implements TreeSelectionListener
       private JButton jbClose;
       private JTree optionsTree;
       private MainPanel jpMain;
       private ActionListener terminator;
       public ScrollPaneProblem()
          // I would prefer that it stay this size.
          setSize( 535, 375 );
          setResizable( false );
          setTitle( "Preferences" );
          setupGui();
          setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
       protected void setupGui()
          Container contentPane = getContentPane();
             The left side of dialog will hold the option tree.
          optionsTree = buildTheTree();
          JScrollPane scrollPane = new JScrollPane( optionsTree );
          contentPane.add( scrollPane, BorderLayout.WEST );
             The center panel will hold another panel
             that changes according to what has been selected
             in the JTree.
          JPanel centerPanel = new JPanel( new BorderLayout() );
          Box bxButtons = buildTheButtonBox();
          centerPanel.add( bxButtons, BorderLayout.SOUTH );
          jpMain = new MainPanel();
          centerPanel.add( jpMain, BorderLayout.CENTER );
          contentPane.add( centerPanel, BorderLayout.CENTER );
       } // end setupGui()
          Changes the text on the main panel, according to what
          has been clicked in the JTree.
       public void valueChanged( TreeSelectionEvent evt )
          TreePath path = evt.getPath();
          Object obj = path.getLastPathComponent();
          if ( obj instanceof DefaultMutableTreeNode )
             DefaultMutableTreeNode node =
             (DefaultMutableTreeNode)obj;
             obj = node.getUserObject();
             // The problem happens when I do the following...
             jpMain.setText( obj.toString() );
             jpMain.revalidate();
             jpMain.repaint();
          } // end if ( a DefaultMutableTreeNode )
       } // end valueChanged( TreeSelectionEvent )
       private JTree buildTheTree()
          // First, build the parent nodes
          Object [] smurfNodes =
             "Smurfette", "Vanity", "Papa Smurf",
             "Greedy Smurf", "Lazy Smurf",
             "O.J., the ostracized orange smurf"
          ParentNode theSmurfs = new ParentNode(
                                  "The Smurfs", smurfNodes );
          Object [] dwarfNodes =
             "Doc", "Happy", "Dopey", "Sneezy",
             "Scratchy", "Sniffy", "Stuffy Head",
             "Fever", "So you can rest medicine"
          ParentNode theDwarfs = new ParentNode(
                                  "The Seven Plus Dwarfs", dwarfNodes );
          // These are all the nodes that go on the tree.
          Object [] theNodes =
             "Scooby Doo",
             "Inspector Gadget",
             "Mighty Mouse",
             "Captain Caveman",
             theSmurfs,
             theDwarfs
          JTree theTree = new JTree( theNodes );
          theTree.addTreeSelectionListener( this );
          return theTree;
       } // end buildTheTree()
       public Box buildTheButtonBox()
          Box box = Box.createHorizontalBox();
          box.add( Box.createHorizontalGlue() );
          // Make it so that we can close this JDialog.
          jbClose = new JButton( "Exit" );
          jbClose.addActionListener( terminator );
          box.add( jbClose );
          box.add( Box.createHorizontalGlue() );
          // help button that does absolutely nothing.
          JButton jbHelp = new JButton( "Help" );
          box.add( jbHelp );
          box.add( Box.createHorizontalGlue() );
          return box;
       } // end buildTheButtonBox()
       // Main entry point.
       public static void main( String [] args )
          JDialog dialog = new ScrollPaneProblem();
          dialog.setVisible( true );
       // So we can shut the dialog off
       static
          terminator =
          new ActionListener()
             public void actionPerformed( ActionEvent evt )
                System.exit( 0 );
    } // end ScrollPaneProblem class
       This MainPanel class goes in the middle of the dialog.
       My other program switches panels instead of using
       the same panel, but that's too much code to put here.
    class MainPanel extends JPanel
       String theText = "Tell me what to draw";
       Font theFont = new Font( "Sans Serif", Font.PLAIN, 12 );
       Dimension theSize;
       // Draws the selected text
       public void paintComponent( Graphics g )
          super.paintComponent( g );
          theSize = getSize( theSize );
          Font oldFont = g.getFont();
          g.setFont( theFont );
          g.drawString( theText, theSize.width / 10, theSize.height / 2 );
          g.setFont( oldFont );
       public void setText( String text )
          theText = text;
    } // end class MainPanel
       This helps with the JTree parent nodes.
    class ParentNode extends Vector
       String theName;
       public ParentNode( String name )
          this( name, null );
       public ParentNode( String name, Object [] values )
          theName = name;
          if ( values != null )
             addAll( Arrays.asList(values) );
       public String toString()
          return theName;
    } // end ParentNode class

  • Make jscrollpane resize automatically while resizing the parent window

    Hello,
    I am using jscrollpane and have different components added to it. When I am resizing parenr frame which contains jscrollpane, then jscrollpane is not getting updated(like gridbaglayout) but manually I can do so using mouse. JScrollPane should resize all components automatically. Any help will really be appreciated.
    regards,
    Ranjan

    Please find the code below. My requirement is that the initial size of below panel should remain static after maximizing the frame.
    import javax.swing.*;
    import java.awt.*;
    public class MainFrame extends JFrame {
    private JSplitPane treesSplitter;
    private JSplitPane splitPaneV;
    private JSplitPane splitPaneH;
    JPanel treesPanel;
    JPanel leftPanel;
    JPanel rightPanel;
    JPanel splashPanel;
    JPanel statusBar;
    JLabel statusMessage;
    MainPanel mainPanel;
    private QueryConsolePanel queryConsolePanel;
    private JTabbedPane tabs = new JTabbedPane();
    GridLayout gridLayout1 = new GridLayout();
    public MainFrame() {
    Container main = getContentPane();
    main.setVisible(true);
    main.show();
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String args[]){
    MainFrame main = new MainFrame();
    main.setLocation(10,10);
    main.setVisible(true);
    main.setSize(1024,805);
    main.show();
    public class MainPanel extends JPanel{
    JTabbedPane tabs;
    JPanel splashPanel;
    MainPanel(JTabbedPane t, JPanel splashP){
    super();
    tabs = t;
    splashPanel = splashP;
    //setLayout(new BorderLayout());
    setLayout(new GridBagLayout());
    public void showSplashPane(){
    remove(tabs);
    // add(splashPanel,BorderLayout.CENTER);
    add(splashPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(3, 1, 0, 1), 608, 350));
    // setBorder(BorderFactory.createEmptyBorder());
    public void showTabs(){
    remove(splashPanel);
    //add(tabs,BorderLayout.CENTER);
    add(tabs, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(3, 1, 0, 1), 608, 350));
    setBorder(BorderFactory.createEmptyBorder());
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(gridLayout1);
    leftPanel = new JPanel();
    leftPanel.setLayout( new BorderLayout() );
    queryConsolePanel = new QueryConsolePanel();
    rightPanel = new JPanel();
    rightPanel.setLayout(new BorderLayout() );
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    getContentPane().add(leftPanel,BorderLayout.CENTER );
    statusBar = new JPanel();
    statusBar.setLayout(new BorderLayout());
    getContentPane().add(statusBar,BorderLayout.SOUTH);
    statusMessage = new JLabel("Application Ready");
    statusMessage.setFont(new Font("MS Sans Serif",Font.PLAIN, 13));
    statusBar.add(statusMessage,BorderLayout.WEST);
    // create the splash
    splashPanel = new JPanel();
    splashPanel.setLayout( new BorderLayout() );
    mainPanel = new MainPanel(tabs,splashPanel);
    treesPanel = new JPanel();
    treesPanel.setBorder(BorderFactory.createEmptyBorder());
    treesPanel.setLayout(new BorderLayout());
    treesSplitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    treesPanel.add(treesSplitter, BorderLayout.CENTER);
    treesPanel.setPreferredSize(new Dimension(250,250));
    treesSplitter.setOneTouchExpandable(true);
    treesSplitter.setDividerLocation(400);
    splitPaneV = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    rightPanel.add(splitPaneV,BorderLayout.CENTER);
    splitPaneV.setLeftComponent(treesSplitter);
    mainPanel.setPreferredSize(new Dimension(250,600));
    splitPaneV.setRightComponent(mainPanel);
    mainPanel.showSplashPane();
    splitPaneV.setOneTouchExpandable(true);
    splitPaneV.setDividerLocation(400);
    splitPaneV.setLeftComponent(treesSplitter);
    splitPaneH = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
    //splitPaneH.setDividerLocation(600);
    splitPaneH.setOneTouchExpandable(true);
    splitPaneH.setLeftComponent(rightPanel);
    JTextArea textArea = new JTextArea();
    JPanel textPanel = new JPanel();
    textPanel.setLayout(new BorderLayout());
    textPanel.add(textArea,BorderLayout.SOUTH);
    textPanel.setPreferredSize(new Dimension(608, 20));
    splitPaneH.setRightComponent(textPanel);
    leftPanel.add( splitPaneH, BorderLayout.CENTER );
    }

  • JTextPane inside JScrollPane resizing when updated

    Hiya all,
    I've been struggling with this problem and checking the forums, but didn't find a solution, so I hope someone can help...at least help me for the nice picture :) It has to do with JTextPane's automatically resizing to their content on a GUI update, rather than scrollbars appearing (the desired result).
    Basically, I have a scenario where I am creating a series of multiple choice answers for a question. Each answer consists of a JTextPane inside a JScrollPane, and a JRadioButton, which are all contained in a JPanel (called singleAnswerPanel). So for 2 answers, I would have 2 of these singleAnswerPanels. There is a one large JPanel that contains all the singleAnswerPanels (called allAnswersPanel). This allAnswersPanel is contained in a JScrollPane. Graphically, this looks like:
       |       JPanel (allAnswersPanel) inside a JScrollPane            |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
        ----------------------------------------------------------------So above, I show 2 answers that can be filled in with text. So assuming both answer JTextPanes are filled with text beyond their current border (scrollbars appear as expected) and the user wishes to add more answers. I have a button to add another singleAnswerPanel to the containing JPanel (allAnswersPanel), and then I validate the main JScrollPane that contains the allAnswersPanel as it's view. The problem that occurs is the existing single answer JTextPanes resize to the size of their text and the vertical scrollbars (only vertical ones setup) of the JTextPanes dissappear! My intent is to keep the existing JScrollPanes the same size (with their scrollbars) when a new answer is added.
    The code snippet below shows what gets done when a new answer is added:
    private void createAnswer()
        // The panel that will hold the new single answer JTextPane pane
        // (inside a JScrollPane) and radio button.
        JPanel singleAnswerPanel = new JPanel();
        // Create the text pane for the single answer.
        JTextPane singleAnswerTextPane = new JTextPane();
        Dimension dimensions = new Dimension(200, 30);
        singleAnswerTextPane.setPreferredSize(dimensions);
        singleAnswerTextPane.setMaximumSize(dimensions);
        // Create a scroll pane and add the single answer text pane.
        JScrollPane singleAnswerScrollPane =
         new JScrollPane(singleAnswerTextPane);
        // Create a radio button that is associated with the single
        // answer text pane above.
        JRadioButton singleAnswerRadioButton = new JRadioButton();
        // Add the scroll pane and radio button to the panel (for a single
        // answer).
        singleAnswerPanel.add(singleAnswerScrollPane);
        singleAnswerPanel.add(singleAnswerRadioButton);
        // Add the panel holding a single answer to the panel holding
        // all the answers.
        m_allAnswersPanel.add(singleAnswerPanel);
        // Update the display.  m_allAnswersScrollPane is a JScrollPane
        // that has the m_allAnswersPanel (JPanel) as its view.
        m_allAnswersScrollPane.validate();
    }     Sorry for the length of the message, but I really want to solve this problem. So again, when updating the JScrollPane with validate(), the JTextPane for a single answer resizes to it's contents (plain text currently) and loses it's vertical scrollbars, but I want it to stay the same size and maintain the scrollbars.
    Thanks!

    http://java.sun.com/docs/books/tutorial/uiswing/mini/layout.htmlimport javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Test extends JFrame {
        int cnt=0;
        Random r = new Random();
        String[] nouns = {"air","water","men","idjits"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        JScrollPane mainScroll = new JScrollPane(mainPanel);
        JScrollBar mainScrollBar = mainScroll.getVerticalScrollBar();
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JLabel("QuizMaster 2003"), BorderLayout.NORTH);
         content.add(mainScroll, BorderLayout.CENTER);
         JButton jb = new JButton("New");
         content.add(jb, BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              JPanel questionPanel = new JPanel(new GridBagLayout());
              questionPanel.add(new JLabel("Question "+cnt++),
                   new GridBagConstraints(0,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              questionPanel.add(new JLabel("Why is there "+
                            nouns[r.nextInt(nouns.length)]+"?"),
                   new GridBagConstraints(1,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              JTextArea jta = new JTextArea();
              JScrollPane jsp = new JScrollPane(jta);
              jsp.setPreferredSize(new Dimension(300,50));
              questionPanel.add(jsp, new GridBagConstraints(0,1,2,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.BOTH,
                        new Insets(1,2,1,2),0,0));
              mainPanel.add(questionPanel, new GridBagConstraints(0,cnt,1,1,0.0,0.0,
                            GridBagConstraints.EAST,GridBagConstraints.NONE,
                            new Insets(0,0,0,0),0,0));
              mainPanel.revalidate();
              mainScroll.getViewport().setViewPosition(new Point(0, mainPanel.getHeight()));
         setSize(400,300);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • JScrollPane resize policy

    Hi.
    When you resize a jframe with JScrollPane inside, the top left corner maintains fixed position, that is the point visible in the corner does not change.
    I would like to keep the center point fixed, that is that a point which is visible exactly in the center should be also in the center after resize.
    How to achieve this with JScrollPane? Efficiently, without double repainting after resize.
    Thanks for any help.

    One way is by leveraging JViewport#setViewPosition. Example with some graphics so the effect can be seen:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FreezeCenterScrollPane {
       private JPanel panel;
       private JScrollPane scrollPane;
       private int midX = 0;
       private int midY = 0;
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new FreezeCenterScrollPane().makeUI();
       public void makeUI() {
          panel = new JPanel() {
             @Override
             public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.RED);
                int w = getWidth();
                int h = getHeight();
                for (int i = 0, j = 0; i < w / 2 && j < h / 2; i += 20, j += 20) {
                   g.drawRect(i, j, w - 2 * i - 1, h - 2 * j - 1);
          panel.setPreferredSize(new Dimension(1000, 1000));
          scrollPane = new JScrollPane(panel);
          scrollPane.addComponentListener(new ComponentAdapter() {
             @Override
             public void componentResized(ComponentEvent e) {
                Point oldPosition = scrollPane.getViewport().getViewPosition();
                Rectangle rect = scrollPane.getViewportBorderBounds();
                if (midX != 0 || midY != 0) {
                   int diffX = midX - rect.width / 2;
                   int diffY = midY - rect.height / 2;
                   Point newPosition = new Point(Math.max(0, oldPosition.x + diffX),
                         Math.max(0, oldPosition.y + diffY));
                   scrollPane.getViewport().setViewPosition(newPosition);
                midX = rect.width / 2;
                midY = rect.height / 2;
          JButton increase = new JButton("Increase panel size");
          increase.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
                resizePanel(50);
          JButton decrease = new JButton("Decrease panel size");
          decrease.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
                resizePanel(-50);
          JFrame frame = new JFrame();
          frame.setGlassPane(new JComponent() {
             @Override
             public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.BLUE);
                int w = getWidth();
                int h = getHeight();
                g.drawLine(w / 2, 0, w / 2, h);
                g.drawLine(0, h / 2, w, h / 2);
          frame.getGlassPane().setVisible(true);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 400);
          frame.add(increase, BorderLayout.NORTH);
          frame.add(scrollPane, BorderLayout.CENTER);
          frame.add(decrease, BorderLayout.SOUTH);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       private void resizePanel(int increment) {
          Dimension d = panel.getPreferredSize();
          panel.setPreferredSize(new Dimension(d.width + increment,
                d.height + increment));
          panel.revalidate();
    }Scroll to the approximate center of the JPanel (the smallest rectangle) and resize the JFrame.
    db

  • Need some guidance on JScrollPane resizing

    Right now I have a JScrollPane that is populated with some JPanels. At a certain size, the vertical scroll bar shows up but covers part of the fields that populate it. I am looking to re-size the scroll pane contents to accommodate the vert. scroll bar AND fully show the labels, but I am not seeing exactly how to do this.
    Can someone please point me in the right direction?

    Check out the [url http://www.camick.com/java/blog.html?name=scrollable-panel]Scrollable Panel. The scrollable width hint of fit/stretch might be what you need.

  • JscrollPane, Resize when InternalFrame maximize

    Hello all. I have 4 Internal Frames that contain 1 Jtable´s each, and all JTable´s has a JscrollPane. I have the four Internal frames added to a JFrame using GridLayout.. I add code below thats important.
    // Create an Desktop For That All Four I-Frame Use
    JDesktopPane forInternalFrameDesktop = new JDesktopPane();
    // Create an Internal Frame For CustomTable.
    JInternalFrame customerFrame = new JInternalFrame("Add Customer To Order",true,false,true,true);
    // Create Table For Customer InternalFrame.
    customerModel = new DefaultTableModel(customerRow,customerCol);
    customerTable = new JTable(customerModel)
    customerTable.setOpaque(true);
    // Create an ScrollPane for customerTable. 
    JScrollPane scroll = new JScrollPane(customerTable);
    scroll.set //  ? What will i put here
    // Set Size for customFrame
    customerFrame.setBounds(0, 0, 500,210);
    // Add customFrame to the Desktop.
    forInternalFrameDesktop.add(customerFrame);
    customerFrame.setVisible(true);
    // This is in MainFrame. an Normal JFrame that uses GridLayout To Lay out my Four I-Frames.
    GridLayout MstLayout = new GridLayout(0,2);
    mstFrame.setLayout(MstLayout);
    mstFrame.add(customerIFrame());
    mstFrame.add(productInternalFrame());
    mstFrame.add(orderReadyInternalFrame());
    mstFrame.add(orderDoneInternalFrame());When i maximize any of the four I-Frames, or the main frame i want the ScrollPane to follow. I know there is 1 row command to do that, had it before, but have forgott it. Anyone that has better memory then me?

    I use one
    JDesktopPane forInternalFrameDesktop = new JDesktopPane();I use four.
    private JInternalFrame orderDoneInternalFrame() {
            JInternalFrame orderDone = new JInternalFrame("Order Ready to Send",true,false,true,true);
            JPanel panel = new JPanel();
            orderDoneCol.addElement("Customer ID");
            orderDoneCol.addElement("Product Id");
            orderDoneCol.addElement("Quantity");
            orderDoneModel = new DefaultTableModel(orderDoneRow,orderDoneCol);
            orderDoneTable = new JTable(orderDoneModel);
            orderDoneTable.getTableHeader().setReorderingAllowed(false);
            JScrollPane scroll = new JScrollPane(orderDoneTable);
            orderDone.setBounds(510,320, 500,300);
            orderDone.add(panel);
            panel.add(scroll);
            forInternalFrameDesktop.add(orderDone);
            orderDone.pack();
            orderDone.setVisible(true);
            return orderDone;
        }And one mainFrame holding it all.
    public JFrame productFrame() {
            JFrame mstFrame = new JFrame();
            GridLayout MstLayout = new GridLayout(0,2);
            mstFrame.setLayout(MstLayout);
            mstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mstFrame.setSize(1000,700);
            mstFrame.setJMenuBar(openMenu());
            mstFrame.add(customerInternalFrame());
            mstFrame.add(productInternalFrame());
            mstFrame.add(orderReadyInternalFrame());
            mstFrame.add(orderDoneInternalFrame());
            mstFrame.pack();
            mstFrame.setVisible(true);
            return mstFrame;
    }Does this make sence to you? Is this the wrong way to handle InternalFrames?

  • JTable Height Relative to JScrollPane's Height?

    Is there a way to set the height of the JTable equal to the height of the JScrollPane? And as the JScrollPane resizes in height, I also want the JTable to resize relative to the height of the JScrollPane.
    I am putting the JScrollPane to a JPanel with BorderLayout (located at the CENTER) as it's layout manager. And as the JPanel increase/decrease in size, so is the JScrollPane. And as the JScrollPane increase/decrease in size, I want the JTable to do the same.
    Any help is highly appreciated. Thank you.

    import java.awt.*;
    import java.lang.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class App2b extends JFrame {
         public App2b() {
              JPanel contentPane=(JPanel)getContentPane();
              contentPane.setLayout(new FlowLayout());
              contentPane.setBackground(Color.gray);
              JTable table=new JTable(4,3);
              JScrollPane sp=new JScrollPane(table);
              contentPane.add(sp);
              ////////////table.setPreferredScrollableViewportSize(table.getPreferredSize());
              setBounds(10,10,500,400);
              setVisible(true);
              System.out.println(sp.getPreferredSize());
         public static void main(String[] args) {
              new App2b();
    The problem is only if the panel layout is FlowLayout.
    If uncomment the setPreferredScrollableViewportSize line, the scrollpane is sized correctly, but this will not take account of the table size changing as its row count changes. Subclassing JTable may help but neither helps me in this particular case (I must use a JTable) or explain if this is a bug or ...
    With or without the initial sizing of the scrollpane, the scollbars bever appear when resize the frame smaller than the table (imitating a resize of the containing panel in a complex GUI).

  • JTabbed+Jscroll+JTable...

    Hi all, I have a problem mixin all this components:
    I have a JTabbedPane with some tabs. Each tab has a JscrollPane in it, and each JScrollPane has a JTable.
    The JTable is not allowed to resize its width so all the other components should arrange its width according to the JTable. For example: if the JTable's width is 200 pixels, the JScrollPane and the JTabbed should also have a width of 200 pixels. I'm using gridbaglayout, and as far as I see, in a gridbaglayout, the jtabbed changes its size acording to the jframe size, the jscrollpane changes it according to the jtabbed one, but should be in the 'reverse way'. The jscrollpane resize acording to the jtable and the jtabbed according to the jscroll.
    Thanks a lot.

    Hi, I don't think you can resize a JTable until and unless you add it some component (like a JScrollPane). So, there is no question of you trying to resize a JTable individually. All that you can do is, resize the JScrollPane inorder to resize a JTable. So, the first question of resizing a JScrollPane when a JTable is resized is ruled out. Now, when you resize the JScrollPane, you want to resize the tabbed pane. Yes, you can do this. But for this you might have to set the minimum size of the tabbed pane to the size of the resized scorllpane. You might have to handle the resize event.
    Thanks,
    Kalyan

  • Border on a JEditorPane

    Hi there,
    I'm trying to create a LineBorder on a JScrollPane, which I want to be in the center of a JPanel, the latter having no other components added.
    Please could someone tell me how to do this. I can do this with an EmptyBorder and MatteBorder, but cannot do this with other borders. How can I?
    Currently I have done it by adding an Empty/MatteBorder to the JScrollPane, which I add to the center of a JPanel. This works but looks silly. Is the proper way to create an empty border for the JPanel, then add the JScrollPane to that - because if it is, when I try it the JScrollPane resizes itself to a ridiculously small size in the middle of the JPanel - which I don't want.
    Please could you help because - well.. because that'd be great.
    Thanks again guys..
    Edward.

    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BorderOnImage {
        public static void main(String[] args) throws IOException {
            int h = 100, w = 300;
            Border b = new BevelBorder(BevelBorder.RAISED, Color.LIGHT_GRAY, Color.GRAY);
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0,0,w,h);
            b.paintBorder(new JPanel(), g, 0, 0, w, h);
            g.dispose();
            ImageIO.write(image, "png", new File("test.png"));
    }

  • JTable in JScrollPane auto resize refresh problem

    Hello,
    I have a JTable in a JScrollPane. Number of rows is changing.
    I'm using the following to auto-resize JScrollPane.
    public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
             }There is a JButton, which adds an empty row to the JTable. It all works fine, except the auto-resize when a new row is added. I want all rows of JTable to be visible, with no scrollbars present. I tried repaint(), revalidate(), addNotify(). What should I do?
    Thanks.

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • Resize jtable in jscrollpane

    Hi,
    I have a frame containing a JTable and a panel with buttons. When the window gets resized, I would like that the jtable takes the extra space and that the button panel stays the same. How can I do that? The jtable panel is already the "Center" and both panels stay the same...
    Thanks,
    Marie
    Here's the code:
    package test;
    import javax.swing.*;
    import java.awt.AWTEvent;
    import java.awt.event.WindowEvent;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    public class Testframe extends JFrame {
        private JPanel mainPanel = new JPanel();
        private JPanel buttonPanel = new JPanel();
        private JPanel tablePanel = new JPanel();
        //Button panel
        private JButton applyTableBt = new JButton("Generate Table");
        private JButton addBt = new JButton("Add");
        private JButton editBt = new JButton("Edit");
        private JButton deleteBt = new JButton("Delete");
        private JButton matchBt = new JButton("Find");
        private JButton saveBt = new JButton("Save to file");
        private JButton loadBt = new JButton("Load from file");
         * Constructor.
         * @param a_parent Frame
        protected Testframe() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
                this.setResizable(true);
                this.setVisible(true);
                pack();
            } catch (Exception e) {
                e.printStackTrace();
         * Initialization of the dialog.
         * @throws Exception
        private void jbInit() throws Exception {
            this.setTitle("Pattern management - CAT");
            Object[][] data = { {"11", "12", "13", "14", "15", "16", "17", "18"},
                              {"21", "22", "23", "24", "25", "26", "27", "28"}
            Object[] names = {"col1", "col2", "col3", "col4", "col5", "col6",
                             "col7", "col8"};
            JTable table = new JTable(data, names);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            //table.setColu
            TableColumnModel colModel = table.getColumnModel();
            for (int i = 0; i < table.getColumnCount(); i++) {
                TableColumn column = colModel.getColumn(i);
                column.setPreferredWidth(511);
            JScrollPane scrollPane = new JScrollPane(table);
            tablePanel.add(scrollPane);
            //Layout = vertical box with vertical gap
            buttonPanel.setLayout(new GridLayout(7, 1, 0, 5));
            buttonPanel.add(applyTableBt);
            buttonPanel.add(addBt);
            buttonPanel.add(editBt);
            buttonPanel.add(deleteBt);
            buttonPanel.add(matchBt);
            buttonPanel.add(saveBt);
            buttonPanel.add(loadBt);
            //mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tablePanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.EAST);
            this.setContentPane(mainPanel);
         * Overrides this class to call the good method when the dialog is closed.
         * @param a_windowE WindowEvent
        protected void processWindowEvent(WindowEvent a_windowE) {
            //If it is a request to close the window (X)
            if (a_windowE.getID() == WindowEvent.WINDOW_CLOSING) {
                cancel();
            super.processWindowEvent(a_windowE);
         * Closes the dialog.
        private void cancel() {
            dispose();
        private static void createAndDisplayFrame() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            new Testframe();
        public static void main(String[] args) {
            createAndDisplayFrame();
    }

    try changing these lines
    mainPanel.add(tablePanel, BorderLayout.CENTER);
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    this.setContentPane(mainPanel);
    to this
    mainPanel.add(buttonPanel, BorderLayout.EAST);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(mainPanel, BorderLayout.EAST);

  • Can't resize JScrollPane

    I put a JTable in a JScrollPane using
    new JScrollPane(table);
    I can't change the Dimension of the JScrollPane and if the table is greater than the Panel it is cuted even if I scroll max ...
    Any Help is welcomed

    if changing size of the scrollpane does not work and the reason is not the layout you use you could try to put the scrollpane on a panel with Gridlayout(1,1) and resize the panel.

  • Resizing columns in a JTable in a JScrollpane

    I have a JTable in a JScrollpane and I after I load the table, I resize the columns to fit the data (works well).
    The problem is that I want the scrollpane to stay the same size and let the table scroll horizontally inside the viewport. The actual result is the scrollpane stretches to the width of the table causing the user to scroll the panel rather than the scrollpane.
    I've tried setting the scrollbar policy but that didn't work.

    I am passing the JTable to the constructor of the JScrollPane.
    I have a JTable in a JScrollPane that sits on a JPanel which is in a JScrollPane itself.
    After I load the data into the JTable, I resize all of the columns to fit the data.
    The problem is that the JTable resizes wider than original size causing the whole panel to scroll horizontally. I would rather have the JScrollPane that the JTable is in scroll.

  • Resizing variable size panel with JScrollPane

    I have a JPanel which contains four radio buttons. Selecting each of them opens another panel which are of different sizes.
    These panels open in the same parent panel below the radio button panel.
    However these panels contain large no of components. i.e. the final size of the main panel varies depeding on which button is selected.
    I am using a JScrollPane to view them properly.
    However, I am facing problem while resizing the main panel. If I mention the preferred size of the JScrollPane, the main panel on maximizing, shows this scrollpane with the size mentioned and does not get maximized as the parent panel.
    If I don't mention the scrollpane size, resizing the main panel don't show the scrollbars.
    what is the correct way to implement a JScrollpane in this case?
    Also can anyone tell me what is the exact deifference between setSize() and setPreferredSize()?

    i think you are looking for this if i got it right.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.ComboBoxModel;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JToggleButton;
    import javax.swing.WindowConstants;
    public class TestVariablePanelSize extends javax.swing.JPanel
        private JPanel buttonPanel;
        private JRadioButton jRadioButton3;
        private JRadioButton jRadioButton4;
        private JLabel jLabel3;
        private JPanel displayPanel2;
        private JLabel jLabel2;
        private JLabel jLabel1;
        private JPanel jPanel1;
        private ButtonGroup buttonGroup1;
        private JScrollPane jScrollPane1;
        private JToggleButton jToggleButton1;
        private JComboBox jComboBox1;
        private JPanel topPanel;
        private JPanel displayPanel;
        private JPanel parentPanel;
        private JRadioButton jRadioButton2;
        private JRadioButton jRadioButton1;
        JFrame container;
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.getContentPane().add(new TestVariablePanelSize(frame));
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        public TestVariablePanelSize(JFrame frame)
            super();
            container = frame;
            initGUI();
        private void initGUI()
            try
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                System.out.println("screenSize" + screenSize);
                container.setMaximumSize(screenSize);
                final ErrorReportImportPanel errorReportPanel = new ErrorReportImportPanel();
                BorderLayout thisLayout = new BorderLayout();
                container.setLayout(thisLayout);
                container.setPreferredSize(new java.awt.Dimension(655, 365));
                container.setFocusable(false);
                // START >> jScrollPane1
                // START >>
                buttonGroup1 = new ButtonGroup();
                // END << buttonGroup1
                jScrollPane1 = new JScrollPane();
                container.add(jScrollPane1, BorderLayout.NORTH);
                jScrollPane1.setPreferredSize(new java.awt.Dimension(602, 285));
                // START >> parentPanel
                parentPanel = new JPanel();
                jScrollPane1.setViewportView(parentPanel);
                GridBagLayout parentPanelLayout = new GridBagLayout();
                parentPanelLayout.columnWeights = new double[]{0.1};
                parentPanelLayout.columnWidths = new int[]{7};
                parentPanelLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0};
                parentPanelLayout.rowHeights = new int[]{33, 23, 186, 26};
                parentPanel.setLayout(parentPanelLayout);
                // parentPanel.setPreferredSize(new java.awt.Dimension(652, 371));
                // START >> topPanel
                topPanel = new JPanel();
                parentPanel.add(topPanel, new GridBagConstraints(
                    0,
                    0,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jComboBox1
                ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[]{"Item One", "Item Two"});
                jComboBox1 = new JComboBox();
                topPanel.add(jComboBox1);
                jComboBox1.setModel(jComboBox1Model);
                jComboBox1.setPreferredSize(new java.awt.Dimension(75, 20));
                // END << jComboBox1
                // END << topPanel
                // START >> buttonPanel
                buttonPanel = new JPanel();
                parentPanel.add(buttonPanel, new GridBagConstraints(
                    0,
                    1,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jRadioButton1
                jRadioButton1 = new JRadioButton();
                buttonPanel.add(jRadioButton1);
                jRadioButton1.setText("jRadioButton1");
                jRadioButton1.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel.setVisible(true);
                        // displayPanel2.setVisible(false);
                        // parentPanel.remove(displayPanel2);
                // END << jRadioButton1
                // START >> jRadioButton2
                jRadioButton2 = new JRadioButton();
                buttonPanel.add(jRadioButton2);
                jRadioButton2.setText("jRadioButton2");
                jRadioButton2.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel2.setVisible(true);
                        displayPanel.setVisible(false);
                        parentPanel.remove(displayPanel2);
                // END << jRadioButton2
                // START >> jRadioButton3
                jRadioButton3 = new JRadioButton();
                buttonPanel.add(jRadioButton3);
                jRadioButton3.setText("jRadioButton3");
                // END << jRadioButton3
                // START >> jRadioButton4
                jRadioButton4 = new JRadioButton();
                buttonPanel.add(jRadioButton4);
                jRadioButton4.setText("jRadioButton4");
                // END << jRadioButton4
                // END << buttonPanel
                buttonGroup1.add(jRadioButton1);
                buttonGroup1.add(jRadioButton2);
                buttonGroup1.add(jRadioButton3);
                buttonGroup1.add(jRadioButton4);
                // START >> displayPanel
                displayPanel = new JPanel();
                parentPanel.add(displayPanel, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel.setVisible(false);
                // START >> jLabel2
                jLabel2 = new JLabel();
                displayPanel.add(jLabel2);
                jLabel2.setText("displayPanel");
                jLabel2.setPreferredSize(new java.awt.Dimension(462, 152));
                jLabel2.setOpaque(true);
                jLabel2.setBackground(new java.awt.Color(128, 128, 255));
                jLabel2.setVisible(false);
                // END << jLabel2
                // END << displayPanel
                // START >> displayPanel2
                displayPanel2 = new JPanel();
                parentPanel.add(displayPanel2, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel2.setVisible(false);
                // START >> jLabel3
                jLabel3 = new JLabel();
                displayPanel2.add(jLabel3);
                jLabel3.setText("displayPanel2");
                jLabel3.setOpaque(true);
                jLabel3.setBackground(new java.awt.Color(0, 128, 192));
                jLabel3.setPreferredSize(new java.awt.Dimension(460, 171));
                // END << jLabel3
                // END << displayPanel2
                // START >> jToggleButton1
                jToggleButton1 = new JToggleButton();
                parentPanel.add(jToggleButton1, new GridBagConstraints(
                    0,
                    3,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.WEST,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                jToggleButton1.setText("jToggleButton1");
                // END << jToggleButton1
                // START >> jPanel1
                jPanel1 = new JPanel();
                parentPanel.add(jPanel1, new GridBagConstraints(
                    0,
                    4,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jLabel1
                jLabel1 = new JLabel();
                jPanel1.add(jLabel1);
                jLabel1.setText("Another Panel");
                jLabel1.setPreferredSize(new java.awt.Dimension(469, 87));
                jLabel1.setBackground(new java.awt.Color(0, 128, 0));
                jLabel1.setForeground(new java.awt.Color(0, 0, 0));
                jLabel1.setOpaque(true);
                // END << jLabel1
                // END << jPanel1
                // END << parentPanel
                // END << jScrollPane1
            catch (Exception e)
                e.printStackTrace();
    }

Maybe you are looking for

  • Sharing More than One Movie with iDVD????

    Okay.. I would like to know if there is another way to burn MORE than one movie an iDVD project. It seems that sending the movie straight to iDVD creates it's own project, and when you try to send another movie, it creates a completely different proj

  • Adobe Forms Error Message 'Error when transforming object data'

    Hi,   When i tried to save(Adobe Forms) after making changes in Layout its giving an error message 'Error when transforming object data' and takes me out of the transaction. How do i solve this ? Can anyone help me out. Thanks and Regards, Franklin.

  • Help me overclock plz

    sup guys... can u guys gimme some tips to overclock my cpu...i have an amd 2100+...i wanna get the best out of my computer...can u plz help

  • TS1567 How do you perform this operation in Windows 8

    Devices not recognized when plugged into USB.  Neither I Phone 5 or I Pod Nano.  Problem began after upgrading to Windows 8.

  • Compressor Encoding with Jagged lines or Crashing totally

    I've been having this problem for some time and have been trying a lot of the standard "fixes" like deleting receipts and preferences then reinstalling Compressor and Qmaster then updating, etc. BUT, when I export a quicktime Ref file then drag it in