Search code examples
javaswingjpanelsizelayout-manager

How can I resize the height of a JPanel?


//Attributes
//Stats GUI components
JLabel hp = new JLabel();
JLabel hpPoints = new JLabel("TEST");
JLabel chakra = new JLabel();
JLabel chakraPoints = new JLabel("TEST");
JLabel ryo = new JLabel();
JLabel ryoPoints = new JLabel("TEST");

//Output & Input GUI components
JTextField input = new JTextField();
JTextArea output = new JTextArea(1000, 300);
JPanel statsPanel = new JPanel(); 
JPanel outputPanel = new JPanel();
JPanel inputPanel = new JPanel();

//Constructor
public Terminal() {
    
    setTitle("Shinobi Shinso");
    setSize(1000, 600);
    //setResizable(false);
    setLocation(400, 100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container panneau = getContentPane();
    panneau.setLayout(new GridLayout(0, 1));
    statsPanel.setLayout(new GridLayout(1, 3));
    
    //Output & input
    //Add outputPanel to the panneau
    panneau.add(outputPanel);
    //Add output to outputPanel
    outputPanel.add(output);
    //Add input to outputPanel
    outputPanel.add(input);
    input.setColumns(98);
    output.setRows(15);
    output.setEditable(false);
    output.setBackground(Color.BLACK);
    output.setForeground(Color.WHITE);
    //Add stats panel
    panneau.add(statsPanel);
    //Statistics
    //Health
    hp.setIcon(new ImageIcon(new ImageIcon("D:\\eclipse-workspace\\Shinobi Shinso\\images\\scroll-hp.png").getImage().
            getScaledInstance(300, 150, Image.SCALE_DEFAULT)));
    hp.setHorizontalAlignment(JLabel.CENTER);
    statsPanel.add(hp);
    hpPoints.setBounds(100, 25, 100, 100);
    hp.add(hpPoints);

    setVisible(true);
}

Here's how it appears :

https://i.sstatic.net/yZ9UZ.png

I tried to use a JScrollPanel and a lot of obscure coding witchcraft to no avail. I can't seem to find a way to reduce the height of the JPanel containing the pictures.

I deleted 2 of the scrolls in the picture, but I don't think that it will change anything.


Solution

  • I can't seem to find a way to reduce the height of the JPanel containing the pictures.

    Don't use a GridLayout as the parent layout manager. The GridLayout makes all components the same size.

    I would suggest you don't change the layout manager of the content pane. Leave it as the default BorderLayout.

    Then use:

    panneau.add(outputPanel, BorderLayout.CENTER);
    panneau.add(statsPanel, BorderLayout.PAGE_END);
    

    Also, your creation of the JTextArea is incorrect:

    JTextArea output = new JTextArea(1000, 300);
    

    The parameters are for rows/columns, not width/height.

    So you should use something like:

    JTextArea output = new JTextArea(15, 40);
    

    and a text area is usually added to a JScrollPane so scrollbars can appear when needed.

    Read the Swing tutorial for Swing basics. There are section on:

    1. Layout managers
    2. How to Use Text Areas

    that should help.