2016-01-21 63 views
0

我創建了2個JButtons.One中的一個具有按鈕功能,另一個處理圖像。如果此按鈕是clicked.So插入方法repaint()並添加一個監聽器到第一個JButton來改變圖像。當試圖添加監聽器或事件處理程序到第一個JButton時,沒有任何反應。所以圖像不會改變。任何人都可以顯示?我怎麼能我的方式,它的工作原理(改變按鈕被按下時,圖像)插入此監聽這裏是我的代碼:將事件處理程序添加到JButton中以重新繪製Java中的圖像時出現錯誤GUI

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.event.*; 
import javax.swing.*; 
import java.util.Random; 

public class Back extends JFrame{ 

    private Random ran; 
    private int value; 
    private JButton r; 
    private JButton c; 

    public Back(){ 


     super("title"); 
     ran = new Random(); 
     value = nextValue(); 
     setLayout(new FlowLayout()); 
     r=new JButton("ROLL"); 
     add(r); 
     Icon i=new ImageIcon(getClass().getResource("1.png")); 
     Icon img=new ImageIcon(getClass().getResource("2.png")); 
     c= new JButton(i); 

     if (value==1){ 
      c= new JButton(i); 

     } 
     else if(value==2){ 
      c= new JButton(img); 

     } 
     add(c); 

     thehandler hand=new thehandler(this);//konstruktori i handler merr nje instance te Background 
     r.addActionListener(hand); 
     c.addActionListener(hand); 

    } 
    private int nextValue() { 
     return Math.abs(ran.nextInt()) % 6 + 1 ; 
     } 
    public void roll() { 
     value = nextValue() ; 

     repaint() ; 
     } 
    public int getValue() { 
     return value ; 
     } 
    private class thehandler implements ActionListener{ 
     private Back d; 
     thehandler(Back thisone) { 
       d = thisone ; } 
     public void actionPerformed(ActionEvent event) { 
      d.roll() ; 
     } 
     } 
    public static void main(String[] args) { 

     Back d = new Back() ; 

     d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     d.getContentPane().setBackground(Color.GREEN); 
     d.setSize(700,500); 

     d.setVisible(true);  
    } 
} 
+1

沒有在你的代碼中你實際上改變了按鈕的狀態或它的初始創建後的圖像 – MadProgrammer

+0

也許你應該看看[這個例子](http://stackoverflow.com/questions/28342538/java-swing - 時間和動畫 - 如何把它放在一起/ 28342986#28342986)一些更好的想法 – MadProgrammer

回答

1

所以,基本上,所有的代碼都歸結到這裏...

public void roll() { 
    value = nextValue(); 

    repaint(); 
} 

這會計算一個新的隨機值並調用repaint。但是,在您調用代碼時,value不會影響您的代碼。

相反,你需要更新一些控件的狀態,也許更多的東西一樣......

public void roll() { 
    value = nextValue(); 

    Icon i = new ImageIcon(getClass().getResource("1.png")); 
    Icon img = new ImageIcon(getClass().getResource("2.png")); 
    if (value == 1) { 
     c.setIcon(i); 
    } else if (value == 2) { 
     c.setIcon(img); 
    } 
} 

接下來的事情我會做的是存儲所有在某種陣列或List的圖像,使它更容易訪問,那麼你可以簡單地做一些事情 像...

public void roll() { 
    value = nextValue(); 
    c.setIcon(listOfImages.get(value - 1)); 
} 

Java Swing Timer and Animation: how to put it together也許看看一個更詳細的例子

+0

嘗試後沒有任何變化! – Doen

+0

基本的想法對我來說工作得很好。確保你的圖像被正確加載,也許使用'ImageIO.read'而不是'ImageIcon' – MadProgrammer

相關問題