2014-02-05 55 views
1

我想在給定示例中將圖像和形狀下面的文本移動。 請幫我做到這一點。將JLabel定位在圖像下面的JPanel中

package test; 

    import java.awt.BasicStroke; 
    import java.awt.Graphics; 
    import java.awt.Graphics2D; 
    import java.awt.Image;   
    import javax.swing.ImageIcon;   
    import javax.swing.JFrame; 
    import javax.swing.JLabel; 
    import javax.swing.JPanel; 


    public class TestLabel extends JPanel { 

     private Integer size = 70; 
     private String name; 
     private Image image; 

     public TestLabel(Integer size, String name) { 
      this.name = name; 
      this.size = size; 
      setSize(size, size + size/4); 
      this.image = new ImageIcon(new Node().getClass().getResource("/com/businesslense/topology/images/node1.jpg")).getImage(); 
      JLabel textLabel = new JLabel(name); 
      textLabel.setBounds(100,100,70,30); 
      add(textLabel); 
      setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 51), 2)); 
     } 



     @Override 
     public void paintComponent(Graphics g) { 

      Graphics2D g2d = (Graphics2D) g.create(); 
      g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); 

      int imagePaddingVal = (int) ((Math.sqrt(2) * (((size * 115)/100)/2)))/4; 
      int imageSize = (size * 85)/100; 
      int imageRadius = (int) (Math.sqrt(2) * (imageSize/2)); 

      g2d.drawImage(image, imagePaddingVal, imagePaddingVal, imageRadius, imageRadius, this); 

      int shapePaddingVal = (size * 5)/100; 
      int shapeRadius = (size * 90)/100; 

      g2d.drawOval(shapePaddingVal, shapePaddingVal, shapeRadius, shapeRadius); 

      g2d.setStroke(new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); 


     } 

     public static void main(String argv[]){ 
      TestLabel tl = new TestLabel(70,"Test"); 
      JFrame jf = new JFrame(); 

      jf.add(tl); 

      jf.setVisible(true); 
      jf.setSize(300, 400); 
     } 
    } 

在這個例子中,JLable進入面板的頂部。我想將它移動到圖像/形狀。我試過setBounds(),但那不起作用。請告訴我,如果我失去了一些東西。

+1

請注意,未能調用'super.paintComponent'會產生未渲染的油漆工件 – MadProgrammer

+0

只需使用'g.drawString'。忘記標籤。 fyi,你的setBounds不起作用的原因是因爲它只適用於空佈局。 JPanel有一個默認的FlowLayout –

回答

3

考慮利用API的可用功能...

在看看:

比如...

private ImageIcon image; 

public TestLabel100(Integer size, String name) { 
    //... 
    JLabel textLabel = new JLabel(name); 
    textLabel.setIcon(image); 
    textLabel.setHorizontalTextPosition(JLabel.CENTER); 
    textLabel.setVerticalTextPosition(JLabel.SOUTH);   
    //textLabel.setBounds(100, 100, 70, 30); 
    //... 
} 

@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    //...