そのため、このコードでJLabelを機能させようとしています。ボタンとアクションリスナーは機能しますが、ラベルは機能しません。MyDiceは、パネルとボタンを作成する場所です。
public class MyDice
{
public static void main(String[] args)
{
JFrame frame = new JFrame("MyDice v1.0");
frame.setSize(800,600);
frame.setLocation(560, 240);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(new Color(200,200,200));
panel.setSize(800,600);
frame.add(panel);
panel.setVisible(true);
JButton button_d4 = new JButton("Roll d4");
panel.add(button_d4);
button_d4.addActionListener (new MyRoll(4,panel));
}
}
そして、MyRollは、ボタンをクリックしたときに何かを実行するアクションリスナーを取得した場所です。
public class MyRoll implements ActionListener
{
int dice;
JPanel panel;
public MyRoll (int dice, JPanel panel)
{
this.dice = dice;
this.panel = panel;
}
public void actionPerformed(ActionEvent e)
{
rollDice(dice,1);
}
public void rollDice (int dice, int times)
{
int r=0;
for (int i=0; i<times;i++)
{
double rand = Math.random();
rand = rand*dice + 1;
r = (int) rand;
}
System.out.println("You rolled "+r+" out of "+dice);
JLabel output = new JLabel();
output.setText("You rolled "+r+" out of "+dice);
panel.add(output);
}
}
ただし、この最後の部分は機能しません。なぜ何かアイデアはありますか?