Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8806485
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T02:08:13+00:00 2026-06-14T02:08:13+00:00

In short, I want to achieve this layout using swing: Notice two main objectives:

  • 0

In short, I want to achieve this layout using swing:

enter image description here

Notice two main objectives:

  • JPanels behaves as text, they are wrapped to width of a window,
    and in case of lack of space, they are wraped to next “lines” of
    JPanels.

  • There is no horizontal scorll, but vertical scroll is present to
    privide access to view all possible elements in window.

Nick Rippe provided an almost done solution below, it can be seen here as standalone java program with my updated more-random innermost textarea strings and left aligment.

The last step is to fix each-row top alignment of textareas in CPanel:

((WrapLayout)getLayout()).setAlignOnBaseline( true );

Complete solution:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;

public class APanel extends JScrollPane {

    int width = 0;

    public static String getRandomMultilineText() {
        String filler = "";
        int words = (int) (Math.random() * 7) + 1;
        for ( int w = 0 ; w < words ; w++ ) {
            int lettersInWord = (int) (Math.random() * 12) + 1;
            for ( int l = 0 ; l < lettersInWord ; l++ ) {
                filler += "a";
            }
            filler += "\n";
        }
        return filler.trim();
    }

    public APanel() {
        super();

        setAlignmentX( LEFT_ALIGNMENT );
        setAlignmentY( TOP_ALIGNMENT );

        final Box B = Box.createVerticalBox();
        B.setAlignmentX( LEFT_ALIGNMENT );
        B.setAlignmentY( TOP_ALIGNMENT );

        for ( int i = 0 ; i < 4 ; i++ ) {
            B.add( new CPanel() {


                //Important!!! Make sure the width always fits the screen
                public Dimension getPreferredSize() {


                    Dimension result = super.getPreferredSize();
                    result.width = width - 20; // 20 is for the scroll bar width
                    return result;
                }
            } );
        }

        setViewportView( B );

        //Important!!! Need to invalidate the Scroll pane, othewise it
        //doesn't try to lay out when the container is shrunk
        addComponentListener( new ComponentAdapter() {
            public void componentResized( ComponentEvent ce ) {
                width = getWidth();
                B.invalidate();
            }
        } );
    }

    // nothing really very special in this class - mostly here for demonstration
    public static class CPanel extends JPanel {

        public CPanel() {
            super( new WrapLayout( WrapLayout.LEFT ) );
            ((WrapLayout)getLayout()).setAlignOnBaseline( true);


            setOpaque( true );
            setBackground( Color.gray );
            setAlignmentY( TOP_ALIGNMENT );
            setAlignmentX( LEFT_ALIGNMENT );


            int wordGroups = (int) (Math.random() * 14) + 7;

            //Adding test data (TextAreas)
            for ( int i = 0 ; i < wordGroups ; i++ ) {

                JTextArea ta = new JTextArea( getRandomMultilineText() );
                ta.setAlignmentY( TOP_ALIGNMENT );
                ta.setAlignmentX( LEFT_ALIGNMENT);
                add( ta );
            }
            Border bx = BorderFactory.createTitledBorder( "Lovely container" );

            setBorder( bx );
        }
    }

    public static void main( String[] args ) {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new APanel() );
        frame.pack();
        frame.setSize( 400 , 300 );
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T02:08:14+00:00Added an answer on June 14, 2026 at 2:08 am

    Your problem is your calculation of your preferredSize of panel C. This preferred size needs to both be overridden (for the width) and contain the default height.

    I’ve put together a demonstration so you can see how this would be done:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class APanel extends JScrollPane {
    
        int width = 0;
    
        public APanel(){
            super();        
    
            final Box B = Box.createVerticalBox();
    
            for(int i = 0; i < 4; i++){
                B.add(new CPanel(){
    
                    //Important!!! Make sure the width always fits the screen
                    public Dimension getPreferredSize(){
                        Dimension result = super.getPreferredSize();
                        result.width = width - 20; // 20 is for the scroll bar width
                        return result;
                    }
    
                });
            }
    
            setViewportView(B);
    
            //Important!!! Need to invalidate the Scroll pane, othewise it
            //doesn't try to lay out when the container is shrunk
            addComponentListener(new ComponentAdapter(){
                public void componentResized(ComponentEvent ce){
                    width = getWidth();
                    B.invalidate();
                }
            });
        }
    
        // nothing really very special in this class - mostly here for demonstration
        public static class CPanel extends JPanel{
    
            //Test Data - not necessary
            static StringBuffer fillerString;
            static {
                fillerString = new StringBuffer();
                int i = 0;
                for(char c = '0'; c < 'z'; c++){
                    fillerString.append(c);
                    if(i++ %10 == 0){
                        fillerString.append('\n');
                    }
                }
            }
    
            public CPanel(){
                super(new WrapLayout());
                setOpaque(true);
                setBackground(Color.gray);
    
                //Adding test data (TextAreas)
                for(int i = 0; i < 9; i++){
                    JTextArea ta = new JTextArea(fillerString.toString());
                    ta.setAlignmentX(LEFT_ALIGNMENT);
                    add(ta);
                }
    
                setBorder(BorderFactory.createTitledBorder("Lovely container"));
            }
        }
    
        public static void main(String[] args){
            final JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new APanel());
            frame.pack();
            frame.setSize(400, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to accomplish this sort of layout.. Notice how the text is always
I want to be able to achieve the following using guice/gin: Get all sort
In short: I want to have two fullscreen views, where I can switch between
SHORT DESCRIPTION OF PROBLEM: I want to set the text of a searchbar without
I want to achieve this : user check on a unchecked checkbox, a toast
I'm creating an undo-redo mechanism. To achieve this, I'm using Serialization. Recording the current
This is a relatively simple question: I can trim a text with ellipsis using
This is What I want to achieve This is what appears I want to
I want to store short arrays in a field. (I realize there are reasons
I want to develop a short url system, like bitly, and I have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.