在Java Swing中安排非矩形JPanel

时间:2013-08-03 10:19:11

标签: java swing jpanel paintcomponent preferredsize

我已经定义了一个新类LShapePanel,它扩展了JPanel,看起来像是L。

import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class LShapePanel extends JPanel{

    public Color color;

    public LShapePanel(Color color) {
        this.color = color;
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        g2d.setColor(color);

        /* coordinates for polygon  */
        int[] xPoints = {0,100,100,20,20,0};
        int[] yPoints = {0,0,20,20,100,100};

        /* draw polygon */
        g2d.fillPolygon(xPoints, yPoints, 6);
    }
}

我想像这样安排其中两个LShapePanel:

enter image description here

但我不知道怎么办?这是我连续排列两个LShapePanel的代码。

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.Dimension;

public class DifferentShapes extends JFrame {

    public DifferentShapes() {

        setTitle("different shapes");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(500, 300);

        JPanel panel = new JPanel();

        /* create and add first L in red */
        LShapePanel lsp1 = new LShapePanel(new Color(255,0,0));
        lsp1.setPreferredSize(new Dimension(100,100));
        panel.add(lsp1);

        /* create and add second L in green*/
        LShapePanel lsp2 = new LShapePanel(new Color(0,255,0));
        lsp2.setPreferredSize(new Dimension(100,100));
        panel.add(lsp2);

        add(panel);

        pack();

    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                DifferentShapes df = new DifferentShapes();
                df.setVisible(true);
            }
        });
    }
}

结果:

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要使用layout manager来安排JFrame中的组件。根据此turorial,内容窗格(实际上包含您放入JFrame的组件)默认使用Borderlayout。在LShapePanel看起来的“L”形状中,它实际上是一个矩形(摆动中的每个组件都是一个矩形,事实上),其中一部分是移植的。因此,如果您想以您想要的方式排列面板,它们将不得不相互重叠。不同类型的布局管理器使用不同的布局策略,Borderlayout不允许组件重叠,因此您必须更改为另一个布局管理器。很抱歉,我不知道任何允许组件重叠的布局管理器,但您可以使用JLayeredPane来实现目标。将JLayeredPane添加到JFrame,然后将LShapePanels添加到JLayeredPane

答案 1 :(得分:0)

对不起,布局经理爱好者,但除了使用setLocationnull布局管理器之外,我想不出任何其他方式。这是一个演示:

setLayout(null);
LShapePanel lsp1 = new LShapePanel(new Color(255,0,0));
lsp1.setPreferredSize(new Dimension(100,100));
lsp1.setLocation(0,0);
add(lsp1);

LShapePanel lsp2 = new LShapePanel(new Color(0,255,0));
lsp2.setPreferredSize(new Dimension(100,100));
lsp2.setLocation(30,30);
add(lsp2);