2016-05-15 94 views
0

我在設置邊框的粗細時遇到問題。我想有一個JPanel帶圓角的虛線邊框。我可以通過覆蓋paintComponent來設置它爲圓形。但是,當我設置中風使邊框變粗和虛線時,它不起作用。我使用setStroke()方法。我的代碼如下在JPanel的邊框上設置描邊

private void loadTopPane() { 

    JPanel topSection = new JPanel() { 
     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Dimension arcs = new Dimension(15, 15); // Border corners arcs 
                // {width,height}, 
                // change this to 
                // whatever you want 
      int width = getWidth(); 
      int height = getHeight(); 
      Graphics2D graphics = (Graphics2D) g; 
      graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

      float dash1[] = { 10.0f }; 
      final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, 
        dash1, 0.0f); 

      // Draws the rounded panel with borders. 
      graphics.setColor(getBackground()); 
      graphics.fillRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint 
                          // background 
      graphics.setColor(getForeground()); 
      graphics.drawRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint 
                          // border 
      graphics.setStroke(dashed); 

     } 
    }; 

    topSection.setLayout(null); 
    topSection.setSize(1150, 175); 
    topSection.setBackground(new Color(222, 225, 226)); 

    topSection.setBounds(25, 13, topSection.getPreferredSize().width, topSection.getPreferredSize().height); 

    topSection.add(new JLabel("TESTING")); 
    topSection.setBounds(20, 10, 1180, 180); 
    frame.add(topSection); 

} 

所以輸出顯示我一個圓角的邊框一個JPanel但它不會給我的虛線和較厚的邊框。我怎樣才能解決這個問題?

+0

爲了更好地幫助更快,發佈[MCVE]或[短的,獨立的,正確的示例](HTTP ://www.sscce.org/)。 –

+0

'topSection.setLayout(null);'Java GUI必須在不同的操作系統上工作',屏幕大小,屏幕分辨率等等,在不同的語言環境中使用不同的PLAF。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

+0

您在繪製邊框之前是否考慮調用'setStroke'? – MadProgrammer

回答

2

你有沒有考慮調用setStroke之前,您繪製邊框...

Stroked

float dash1[] = {10.0f}; 
final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, 
                        dash1, 0.0f); 
graphics.setStroke(dashed); 

// Draws the rounded panel with borders. 
graphics.setColor(getBackground()); 
graphics.fillRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint 
// background 
graphics.setColor(getForeground()); 
graphics.drawRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);// paint