2011-11-26 222 views
3

在我的paintComponent中,我有drawRect,它繪製了一個矩形。但是,我想讓矩形的輪廓更粗,但我不知道如何。所以我想在現有的一個裏面製作另一個矩形。我試圖把另一個drawRect,但矩形不在中心。如何在矩形中創建矩形?

感謝那些會幫助的人!

回答

4
g2d.setStroke(new BasicStroke(6)); 

傳遞給Swing組件的paintComponent(Graphics)方法的參數實際上應該是一個Graphics2D實例。它可以投射到一個。

看到這個例子,其中3筆畫分層。

Stroke It

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

class StrokeIt { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       StrokePanel sp = new StrokePanel(); 
       sp.setPreferredSize(new Dimension(400,100)); 
       sp.setBackground(Color.BLUE); 
       JOptionPane.showMessageDialog(null, sp); 
      } 
     }); 
    } 
} 

class StrokePanel extends JPanel { 

    int pad = 12; 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2d = (Graphics2D)g; 

     g2d.setColor(Color.RED); 
     g2d.setStroke(new BasicStroke(10)); 
     g2d.drawRect(0+pad, 0+pad, 
      getWidth()-(2*pad), getHeight()-(2*pad)); 

     g2d.setColor(Color.YELLOW); 
     g2d.setStroke(new BasicStroke(6)); 
     g2d.drawRect(0+pad, 0+pad, 
      getWidth()-(2*pad), getHeight()-(2*pad)); 

     g2d.setColor(Color.ORANGE); 
     g2d.setStroke(new BasicStroke(2)); 
     g2d.drawRect(0+pad, 0+pad, 
      getWidth()-(2*pad), getHeight()-(2*pad)); 
    } 
} 
+0

這不是隻Graphics2D的?你需要把super.paintComponent for Graphics2D? – alicedimarco

+0

查看編輯答案。 –

+0

謝謝你,我已經成功地做到了。 – alicedimarco