Set the JPanel size to fill parent with little margin

浪尽此生 提交于 2019-12-30 05:28:05

问题


I have two Jpanel (JpanelLeft and JpanelLeftContent) how can i make the JpanelLeftContent fill parent size with a little margin on the left an right side. i have tried different layout and tried to modify the hgap and vgap values, but none of them give me a good result.

  JPanel JpanelLeft = new JPanel();
  JPanel JpanelLeftContent = new JPanel();
  JpanelLeft.add(JpanelLeftContent);

And if possible how can i make the JpanelLeftContent look like a rounded rectangle as shown in the picture.


回答1:


Take a look at how Borders work. Especially
BorderFactory.createEmptyBorder(int top, int left, int bottom, int right) might be helpfull.




回答2:


..how can i make the JpanelLeftContent look like a rounded rectangle as shown in the picture.

See TextBubbleBorder for a start.

Obviously you'd need to remove the little v at the bottom, & shove the bottom border further down. The code is not comprehensively tested, and will require further tweaks and fixes. 'Batteries not included'.




回答3:


Do try this code example :

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

public class InsetTesting extends JFrame
{
    private void createAndDisplayGUI()
    {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationByPlatform(true);

        JPanel contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBorder(BorderFactory.createLineBorder(
                                    Color.DARK_GRAY.darker(), 5, true));
        contentPane.setBackground(Color.WHITE);

        add(contentPane, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

    public Insets getInsets()
    {
        return (new Insets(30, 20, 10, 20));
    }

    public Dimension getPreferredSize()
    {
        return (new Dimension(200, 400));
    }

    public static void main(String\u005B\u005D args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new InsetTesting().createAndDisplayGUI();
            }
        });
    }
}

Here is the output of the same :




回答4:


To make a JPanel appear rounded, you need to make your own class that extends JPanel, override paintComponent and draw the panel as an ellipse Javadoc here This will create a customized object which is an JPanel.

When you specify the size of your ellipse, you want to get the Y and X values from the parent panel (since you will be adding your ellipse ontop of another panel) and then subtract the number of pixels you desire from the X-axis. This could be achived by passing those values to the "ellipse panel" constructor.



来源:https://stackoverflow.com/questions/10122626/set-the-jpanel-size-to-fill-parent-with-little-margin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!