我正在使用swing在java中製作一個骰子滾動程序。我有4類:使用舊實例的paintComponent
模具
public class Die{
private int faceValue;
public Die(){
System.out.println("Creating new Dice Object");
setValue(roll());
}
public int roll() {
int val = (int) (6 * Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return faceValue;
}
public void setValue(int spots) {
faceValue = spots;
}
}
DieFace
public class DieFace {
private int spotDiam,wOffset,hOffset,w,h;
public int faceValue;
public DieFace(){
Die die = new Die();
this.faceValue = die.getValue();
}
public void draw(Graphics g, int paneWidth, int paneHeight){
//draw information
}
}
DieFaceComponent
public class DieFaceComponent extends JComponent{
private static final long serialVersionUID = 1L;
DieFace face;
public DieFaceComponent(){
face = new DieFace();
System.out.println("DIEFACE" + face.faceValue);
repaint();
}
public void paintComponent(Graphics g){
revalidate();
face.draw(g,super.getWidth(),super.getHeight());
}
}
DieFaceViewer
public class DieFaceViewer{
static DieFaceComponent component;
static JFrame frame = new JFrame(); // Create a new JFrame object
public static void main(String[] args){
final int FRAME_WIDTH = 500;
final int FRAME_HEIGHT = 500;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); // Set initial size
frame.setTitle("Dice Simulator Version 1.0"); // Set title
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set default close operation
component = new DieFaceComponent(); // Create a new DieFaceComponent object
frame.setLayout(new BorderLayout());
JButton btnRoll = new JButton("Roll!");
btnRoll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
component = new DieFaceComponent();
}
});
frame.add(component, BorderLayout.CENTER); // Add DieFaceComponent object to frame
frame.add(btnRoll, BorderLayout.SOUTH);
frame.setVisible(true); // Set frame to visible
}
}
我的問題是,即使每次按下我的btnRoll時都會創建一個新的Die,DieFace和DieFaceComponent對象,用於繪製組件的值與初始實例保持相同。有什麼我做錯了嗎?在此先感謝
不要在'paintComponent'方法中調用'revalidate',也應該在做任何自定義繪畫之前調用'super.paintComponent'作爲一般規則thumb – MadProgrammer
您在'ActionListener'中創建了一個'DieFaceComponent'的新實例,但是它什麼都沒做,它從來沒有添加到任何東西,所以它永遠不可見。更好的解決方案可以讓你觸發對'DieFaceComponent'的更改,它觸發了對'DieFace'的更改,它觸發了對'Die'的更改並且整個事情都只是'重新繪製'本身 – MadProgrammer