【发布时间】:2016-04-28 10:15:33
【问题描述】:
我创建了 2 个 JButton。其中一个具有按钮的功能,另一个处理图像。我希望在单击此按钮时更改该图像。因此插入了方法 repaint() 并添加了一个侦听器更改图像的第一个 JButton。尝试将侦听器或事件处理程序添加到第一个 JButton 时没有任何反应。因此图像不会更改。谁能告诉我如何以可行的方式插入此侦听器(单击按钮时更改图像)?这是我的代码:
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);
}
}
【问题讨论】:
-
在您的代码中,您实际上是在更改按钮的状态还是在最初创建按钮后的图像
-
也许你应该看看this example 以获得更好的想法
标签: java swing awt jbutton repaint