Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of the gap between JPanels

Tags:

java

swing

Here is my problem

enter image description here

How can I get rid of the gap from the inner rectangle box (it is actually the border of the middle JPanel)?

The outter rectangle is a extends JCompoment. Inside it contains three JPanels. Each of them use GridLayout. I even try to setHgap to a negative value in the big rectangle, but it doesn't change anything.

Edit: Sorry the question is not clear. I do want the border, but I don't want the gap between the inner border and outer border. If there is no gap in between, the whole rectangle will represent a class diagram class.

like image 407
bili Avatar asked Dec 28 '22 15:12

bili


2 Answers

You may mean this way:

enter image description here

import java.awt.*;
import javax.swing.*;

public class GridBadFrame {

    private JFrame frame;
    private JPanel pnlCenter;
    private JPanel pnl1;
    private JPanel pnl2;
    private JPanel pnl3;

    public GridBadFrame() {
        pnl1 = new JPanel();
        pnl1.setBackground(Color.red);
        pnl2 = new JPanel();
        pnl2.setBackground(Color.blue);
        pnl3 = new JPanel();
        pnl3.setBackground(Color.red);
        JLabel lblWest = new JLabel();
        lblWest.setPreferredSize(new Dimension(50, 150));
        JLabel lblEast = new JLabel();
        lblEast.setPreferredSize(new Dimension(50, 150));
        JLabel lblNorth = new JLabel();
        lblNorth.setPreferredSize(new Dimension(600, 50));
        JLabel lblSouth = new JLabel();
        lblSouth.setPreferredSize(new Dimension(600, 50));
        pnlCenter = new JPanel();
        pnlCenter.setBackground(Color.black);
        pnlCenter.setLayout(new java.awt.GridLayout(3, 0, 10, 10));
        pnlCenter.setPreferredSize(new Dimension(600, 400));
        pnlCenter.add(pnl1);
        pnlCenter.add(pnl2);
        pnlCenter.add(pnl3);
        frame = new JFrame();
        frame.add(pnlCenter, BorderLayout.CENTER);
        frame.add(lblNorth, BorderLayout.NORTH);
        frame.add(lblSouth, BorderLayout.SOUTH);
        frame.add(lblWest, BorderLayout.WEST);
        frame.add(lblEast, BorderLayout.EAST);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                GridBadFrame gridBadFrame = new GridBadFrame();
            }
        });
    }
}
like image 102
mKorbel Avatar answered Jan 10 '23 04:01

mKorbel


it is actually the border of the middle JPanel

If it is the border, remove that (setBorder(null)).

like image 21
Thomas Avatar answered Jan 10 '23 04:01

Thomas