的頂部,我完成了我的DiceRollGUI,當我運行它,然後按「滾動」彼此頂部的圖像棧,我怎麼做,因此我後再次按下按鈕消失?圖像疊加在彼此
我做什麼最MadProgrammer告訴我,但我碰到了這是錯誤的:
--------------------Configuration: <Default>--------------------
G:\DiceRollGUI\src\DiceRollGUI.java:26: error: constructor RollButton in class RollButton cannot be applied to given types;
button.addActionListener(new RollButton(diceRoll));
^
required: JPanel
found: JLabel
reason: actual argument JLabel cannot be converted to JPanel by method invocation conversion
G:\DiceRollGUI\src\DiceRollGUI.java:42: error: cannot find symbol
contentPane.add(diceRoll);
^
symbol: variable contentPane
location: class RollButton
2 errors
Process completed.
代碼:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Random;
public class DiceRollGUI {
public static JLabel label;
public static JFrame frame;
public static JPanel panel;
private static JButton button;
private static JButton buttonRollDie;
private static JLabel diceRoll;
public static void main (String[] args) {
JFrame frame = new JFrame("Dice Roll GUI");
panel = new JPanel();
JPanel contentPanel = new JPanel(new GridLayout(0,2,5,10));
button = new JButton("Roll");;
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setActionCommand("Roll");
button.addActionListener(new RollButton(diceRoll));
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setPreferredSize(new Dimension(750, 500));
frame.setContentPane(panel);
frame.pack();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.add(button);
}
private static class RollButton implements ActionListener {
private JPanel diceRoll;
public RollButton(JPanel diceRoll){
this.diceRoll = diceRoll;
contentPane.add(diceRoll);
}
public void actionPerformed(ActionEvent event){
int roll = (int) (Math.round((Math.random() * 5) + 1));
ImageIcon dice = null;
if(roll == 1){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_1.png");
}
else if(roll == 2){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_2.png");
}
else if(roll == 3){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_3.png");
}
else if(roll == 4){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_4.jpeg");
}
else if(roll == 5){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_5.png");
}
else if(roll == 6){
dice = new ImageIcon("DiceRollGUI Pictures/die_face_6.png");
}
JLabel diceRoll = new JLabel("",dice, JLabel.CENTER);
panel.add(diceRoll);
panel.revalidate();
}
}
}
我做了最你說什麼,但我得到的錯誤(更新後) – user3163392
不,你沒有。我說要改變'RollButton'接受'JLabel'並且您還沒有實例化diceRoll'的'的實例,如在第一點建議... – MadProgrammer
好吧,我改變了它,所以我RollButton的ActionListener支持的JLabel代替的JPanel但是對於diceRoll.setIcon(dice);改變它到什麼屬性? :\ – user3163392