2014-12-02 285 views
0

我已經創建了10x10網格的Jframe /按鈕。每個jbutton都是網格的一部分。我正在試圖通過JFrame /按鈕來影響每個按鈕,因爲我最終想要將它變成戰艦遊戲。JButton是否執行了操作?

frame.setLayout(new GridLayout(width,length)); 
      grid=new JButton[width][length]; 
      for(int y=0; y<length; y++){ 
        for(int x=0; x<width; x++){ 
          grid[x][y]=new JButton("("+x+","+y+")");  
          frame.add(grid[x][y]); 
        } 
      } 

比如我想要的代碼基礎件,看看我是否可以通過單擊JFrame的顏色變爲紅色,但它似乎並不奏效。

public void actionPerformed(ActionEvent e){ 
      if(e.getSource() instanceof JButton) { 
       ((JButton)e.getSource()).setBackground(Color.red); 
      } 
     } 

任何人有任何想法?

+0

你'addActionListener'到JButton?另請參閱https://docs.oracle.com/javase/tutorial/uiswing/components/button.html – Radiodef 2014-12-02 17:58:04

+0

我上個學期使用這種方法制作了戰艦遊戲:) – 2014-12-02 19:20:57

回答

1

我通過單獨創建JButtons而不是網格的一部分來完成這項工作,但總的想法是一樣的。 你不能像你擁有它那樣調用actionPerformed,你必須有一個實現了ActionListener的類,然後對方法actionPerformed進行覆蓋。

您需要爲每個JButton添加一個actionlistener。在這種情況下,因爲您想要將相同的偵聽器應用於多個按鈕,您需要在主要的下方有一個單獨的類。

class buttonListener implements ActionListener { 
    @Override 
    public void actionPerformed (ActionEvent e) { 
     ((JButton)e.getSource()).setBackground(Color.red); 
    } 
} 

爲何按鈕沒有顏色變化的原因是因爲你需要添加下面的以改變的一個JButton

JButton j = new JButton("test"); 
    j.setSize(100, 100); 
    j.setContentAreaFilled(true); 
    j.setOpaque(true); 
    j.addActionListener(new buttonListener()); 

我知道這個顏色不是最直接的答案對你的問題,但我希望我至少幫助搞清楚顏色。

0

,你可以創建自己的動作監聽:

class MyActionListener implements ActionListener { 
    private int x; 
    private int y; 


    public MyActionListener(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public void actionPerformed(ActionEvent e) { 
     DoSomething(x, y); 
    } 
} 

... 
grid = new JButton[wid][len]; 
for(int y = 0; y < len; y++){ 
    for(int x = 0; x < wid; x++){ 
     grid[x][y]=new JButton("("+x+","+y+")");  
     grid[x][y].addActionListener(new MyActionListener(x, y)); 
     frame.add(grid[x][y]); 
    } 
} 
1

比方說,我們有一個按鈕:JButton button。要在按下按鈕時調用動作,必須將動作偵聽器添加到該動作中。有這樣做(我知道的)的方法有兩種:

ActionListener

我認爲這是更爲常用的第二種方法。它也更容易和更快IMO寫:

JButton button = new JButton("Click me"); 
button.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     System.out.println("button was clicked!"); 
    } 
} 

Action

另一種動作監聽。功能和用途有所不同。然而,爲了實現一個按鈕,simarly行爲給ActionListener,這樣做:

Action buttonAction = new AbstractAction("Click me") { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     System.out.println("button was clicked!"); 
    } 
} 

JButton button = new JButton(action); 

注意,在這兩個例子中,我使用匿名類。在大多數情況下,使用命名的內部類或甚至外部類是更可取的。


ActionListenerAction之間進行選擇取決於一點點的情況(如總是...嘆氣),我怕我無法擺脫在這個問題上過多的光。谷歌是你的朋友。一個快速搜索提供這個職位從SO:link

相關問題