2013-08-03 41 views
0

我定義它繼承JPanel和它看起來像一個L.安排的Java Swing非矩形JPanels

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); 
    } 
} 

我想安排其中兩個LShapePanels這樣的一個新的類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

+0

[see](http://stackoverflow.com/a/9258934/714968) – mKorbel

+0

還考慮複合邊框或[這些替代方法]之一(http://stackoverflow.com/a/13768330/230513)。 – trashgod

回答

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); 
1

您需要使用layout manager安排在JFrame中的組件。根據此turorial,內容窗格實際上包含您放入JFrame的組件,默認情況下使用Borderlayout。在LShapePanel看起來的「L」形狀中,它實際上是一個矩形(每個擺動組件都是一個矩形,事實上),其中的一部分是移植的。所以如果你想按照你想要的方式安排面板,它們將不得不彼此重疊。不同類型的佈局管理器使用不同的佈局策略,並且Borderlayout將不允許組件重疊,因此您必須切換到另一個佈局管理器。對不起,我不知道任何允許組件重疊的佈局管理器,但是您可以使用JLayeredPane來實現您的目標。將JLayeredPane添加到JFrame,然後將LShapePanels添加到JLayeredPane