I've created the r Jbutton and inserted an image into the c JButton.All I want to do is add an event handler to the r JButton that when it is clicked the image in c button to be changed as specified in the method roll.But it shows an error inside thehandler class in the line:r.roll .Can someone show me how to add the handler into the r JButton in a way that when the r JButton is clicked the method roll executes and the image is changed? This is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;
import javax.imageio.*;
public class Background extends JFrame{
private Random ran;
private int value;
private JButton r;
private JButton c;
public Background ()
{
super("title");
ran = new Random();
value = nextValue() ;
setLayout(new FlowLayout());
r=new JButton("ROLL ");
r.setForeground(Color.WHITE);//ndryshon ngjyren e shkrimit
r.setBackground(Color.YELLOW);
add(r,BorderLayout.SOUTH);
Icon i=new ImageIcon(getClass().getResource("1.png"));
Icon im=new ImageIcon(getClass().getResource("2.png"));
c= new JButton(i);
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() ;
if (value==1){
Icon i=new ImageIcon(getClass().getResource("1.png"));
c= new JButton(i);
add(c);
}
else if(value==2){
Icon im=new ImageIcon(getClass().getResource("2.png"));
c= new JButton(im);
add(c);
}
repaint() ;
}
public int getValue() {
return value ;
}
private class thehandler implements ActionListener{
private Background m ;
thehandler(Background thisone) {
m = thisone ; }
public void actionPerformed(ActionEvent event) {
m.roll();
r.roll();//ERROR
}
}
public static void main(String[] args) {
Background d = new Background() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}
Aucun commentaire:
Enregistrer un commentaire