2017-02-15 103 views
0

我使用一個帶GridLayout的JPanel,我把JLabel放在裏面。 Everithing的作品。但我想用我自己的班級(擴展爲JLabel)有一個問題。創建自己的JLabel

當我使用一個JLabel我有這樣的渲染:

result

當我用我自己的JLabel我有:

result

這裏是我的代碼從我JLabel定製:

public class LabelCustom extends JLabel{ 

int x; 
int y; 

public LabelCustom(int x, int y) { 
    super(); 
    this.x = x; 
    this.y = y; 
    this.setBackground(Color.white); 
    this.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); 
} 

public int getX() { 
    return x; 
} 

public void setX(int x) { 
    this.x = x; 
} 

public int getY() { 
    return y; 
} 

public void setY(int y) { 
    this.y = y; 
} 

}

我如何使用它:

JPanel j = new JPanel(); 
    j.setLayout(new GridLayout(nbCaseY, nbCaseX)); 

    for(int i=0; i<nbCaseY; i++) { 
     HashMap<Integer, JLabel> ligne = new HashMap(); 
     for(int y=0; y<nbCaseX; y++) { 
      LabelCustom p = new LabelCustom(i, y); 
      p.addMouseListener(ml); 
      //p.setBounds(100+ y*(hauteur), 100 + i*(hauteur), hauteur, hauteur); 
      p.setPreferredSize(new Dimension(hauteur, hauteur)); 

      //p.setBounds(100+ y*((width-200-2*hauteur)/nbCaseX), 100 + i*((height-200)/nbCaseY), ((width-200-2*hauteur)/nbCaseX), ((height-200)/nbCaseY)); 
      p.setTransferHandler(new TransferHandler("icon")); 
      p.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); 

      p.setOpaque(true); 
      p.setVisible(true); 
      j.add(p); 
      ligne.put(y, p); 
     } 
     Frame.p.getListeNiveau().get(0).ajouterLigne(ligne); 
    } 
+1

'JLabel'已經有'get/X/Y'方法,最好不要重新實現它們,除非你有一個很好的原因 – MadProgrammer

+0

它不適用於x和y的位置。這是一個hashmap的ID,我認爲它是有用的;) – Sebastien

+1

你可能是,你覺得API是如何確定你的組件的位置?我敢打賭,如果您將'@ Override'添加到'getX'和'getY'方法中,它仍會編譯,告訴您您正在重寫父類的方法,它可能希望用於某種目的的方法...像位置的組件...也許 – MadProgrammer

回答

1

JLabel已經有一個getXgetY方法,它是定位在屏幕上的標籤,你(不知不覺地)重寫了這個功能,並現在返回無關的信息。

它不適用於x和y位置。這是一個HashMap的ID,我認爲這是有益的;)

所以,而是採用getX/Y,我建議做一個ID類,它攜帶您需要的信息(可能重寫equalshashcode方法讓它更容易做比較)並用它代替(提供一個getIDsetID方法)