2015-04-06 61 views
0

我必須對Shikaku-Game進行編程,而且我沒有問題,我無法使用類MyMouseAdapter的mouseReleased-Method中的ViewIcon-Class中的setLine-Methods之一。 你知道如何使用其中一種方法嗎?如何從已經使用的方法使用Cotainer把JLabel?

感謝和歡呼聲中, 我

類MouseMain和Class MyMouseAdapter:

class MouseMain extends JFrame{ 

Container cont; 

public MouseMain() { 
    super("Test"); 
    cont = getContentPane(); 
    p1 = new defaultPaterns(2); 
    p1.setLayout(new GridLayout(2, 2, 1, 1)); 
    for (int i = 0; i < gameSize; i++) { 
     for (int j = 0; j < gameSize; j++) { 
      JLabel label = new JLabel(new ViewIcon()); 
      label.setName (j + ";" + i); 
      label.addMouseListener(new MyMouseAdapter()); 
      p1.add(label); 
      myLabels[j][i] = label; 
     } 
    } 
    cont.add(p1, BorderLayout.CENTER); 

    JPanel p2 = new JPanel(); 
    cont.add(p2, BorderLayout.SOUTH); 
    setVisible(true); 
} 

public class MyMouseAdapter extends MouseAdapter { 

    public void mouseEntered(MouseEvent e) { 
     lastEntered = e.getComponent(); 
    } 

    public void mousePressed(MouseEvent e) { 
     mousePressed = e.getComponent(); 
     coordPressed = new Coordinate(mousePressed.getName()); 
     System.out.println("mousePressed " + mousePressed.getName()); 
    } 

    public void mouseReleased(MouseEvent e) { 
     mouseReleased = lastEntered; 
     coordReleased = new Coordinate(mouseReleased.getName()); 
     System.out.println("mouseReleased " + mouseReleased.getName()); 
     if (mouseReleased.getName().equals("0;0")) { 
      mouseReleased.setForeground(Color.RED); 
      mouseReleased.repaint(); 
     } 
    } 
} 

類ViewIcon:

class ViewIcon extends JLabel implements Icon { 

    Graphics2D g2; 
    int width; 
    int height; 

public void paintIcon(Component c, Graphics g, int x, int y) { 

    g2 = (Graphics2D) g; 
    width = c.getWidth(); 
    height = c.getHeight(); 
    g2.setColor(Color.LIGHT_GRAY); 
    g2.fillRect(0, 0, width, height); 
} 

public void setLeftLine() { 

    g2.setStroke (new BasicStroke (10)); 
    g2.setColor(Color.RED); 
    g2.drawLine(0, 0, 0, height); 
} 

} 
+0

這不是我所說的[最小示例](http://stackoverflow.com/help/mcve)。 – fabian

回答

1
class ViewIcon extends JLabel implements Icon { 

不要延長的JLabel。您的代碼正在執行Icon界面。

我不能使用的setLine的方法之一從ViewIcon級

風俗畫只應在的paintIcon(...)方法來實現。你不應該直接調用繪畫方法。

如果你想改變繪畫的外觀,那麼你需要設置圖標的屬性。例如畫上線,你重命名和更改setTopLine(...)方法看起來是這樣的:

public void setTopLinePainted(boolean topLinePainted) 
{ 
    this.topLinePainted = topLinePainted; 
} 

然後在的paintIcon(...)方法你有這樣的代碼:

g2.fillRect(0, 0, width, height); 

if (topLinePainted) 
{ 
    g2.setStroke (new BasicStroke (10)); 
    g2.setColor(Color.RED); 
    g2.drawLine(0, 0, width, 0); 
} 

然後在你的鼠標釋放(...)代碼你做類似:

JLabel label = (JLabel)lastEntered; 
ViewIcon icon = (ViewIcon)label.getIcon(); 
icon.setTopLinePainted(true); 
label.repaint(); 
+0

真棒!感謝您的幫助camickr。我被困在這個問題約10個小時,現在它只是工作!瘋了! :) – Kawa

相關問題