如何创建带边框的颜色样式面板?

时间:2018-12-11 06:51:44

标签: java swing jpanel layout-manager

我正在尝试为椭圆形创建一个画布,并且希望它与主要的JFrame颜色不同。到目前为止,在面板上使用setSize无效,最终创建了一个我无法画出的小盒子。这是我想要的面板设计,带有白色部分作为主要框架。

PanelDesign

正如我所说,使用所有三种布局模式(BorderFlowGrid)只能在框架的中上部创建一个黄色的小方框。这是我使用的代码。

如何创建类似于上面图像的面板设计?

    setTitle("Oval Shape Mover");
    setSize(500, 200);
    setLayout(new BorderLayout());
    JPanel mainpanel, panel1, panel2;

    mainpanel = new JPanel();
    panel1 = new JPanel();
    panel2 = new JPanel();

    panel1.setBackground(Color.YELLOW);
    mainpanel.add(panel1, BorderLayout.CENTER);
    mainpanel.add(panel2);
    add(mainpanel);
    setVisible(true);

1 个答案:

答案 0 :(得分:1)

用于制作Java Swing GUI的布局通常会优先使用首选大小而不是大小。话虽如此,自定义呈现的组件应该覆盖(而不是设置)getPreferredSize()

此示例通过使用JLabel显示图标,并使用空边框填充GUI来建议首选大小。

enter image description here

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

public class RedDotLayout {

    private JComponent ui = null;
    String urlToRedCircle = "https://i.stack.imgur.com/wCF8S.png";

    RedDotLayout() {
        try {
            initUI();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public final void initUI() throws MalformedURLException {
        ui = new JPanel(new BorderLayout());
        ui.setBackground(Color.YELLOW);
        ui.setBorder(new LineBorder(Color.BLACK, 2));

        JLabel label = new JLabel(new ImageIcon(new URL(urlToRedCircle)));
        label.setBorder(new CompoundBorder(
                new LineBorder(Color.GREEN.darker(), 2),
                new EmptyBorder(20, 200, 20, 200)));
        ui.add(label, BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(Color.WHITE);
        bottomPanel.setBorder(new EmptyBorder(30, 50, 30, 50));
        ui.add(bottomPanel, BorderLayout.PAGE_END);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            RedDotLayout o = new RedDotLayout();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}
相关问题