gpt4 book ai didi

java - 我怎样才能通过编写这段代码来使保存按钮工作?

转载 作者:太空宇宙 更新时间:2023-11-04 12:41:53 24 4
gpt4 key购买 nike

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;


public class DiceFrame extends JFrame{

ImageIcon[] dice_im = new ImageIcon[7];
String score="start";
JPanel mainPanel= new JPanel();
JPanel scorePanel=new JPanel();
JPanel buttonPanel =new JPanel();
JLabel picLabel = new JLabel();
JTextArea scorefield = new JTextArea();
JButton roll= new JButton("roll the dice");
JButton save = new JButton("save");

ActionListener action;
ActionListener output;

public DiceFrame(){
super();
setSize(600, 600);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);

getContentPane().add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(save);
buttonPanel.add(roll);

mainPanel.add(picLabel);
picLabel.setIcon(dice_im[0]);
scorePanel.add(scorefield);
scorefield.setText(score);
action = new DiceActionListener();
roll.addActionListener(action);

}
private void loadImage(){
dice_im [0]= new ImageIcon("1.jpg");
dice_im[1] = new ImageIcon("2.jpg");
dice_im[2] = new ImageIcon("3.JPG");
dice_im[3] = new ImageIcon("4.JPG");
dice_im[4] = new ImageIcon("5.JPG");
dice_im[5] = new ImageIcon("6.JPG");
}
public static void main(String args[]){
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

class DiceActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Random rg = new Random();
int k = rg.nextInt(6) + 1;
picLabel.setIcon(dice_im[k]);
}
}
class SaveActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) { //NEW code
String out_file_name = "dice_score.txt";
try {
File outputfile = new File(out_file_name);
PrintStream out = new PrintStream(
new FileOutputStream(outputfile));
out.println(score);
out.flush();`
out.close();
} catch (IOException y) {
System.out.println("IO problem.");
}
}
}


}

如何通过编写此代码使保存按钮起作用?每当我运行它时,滚动按钮可以工作,但保存按钮不起作用?这是一个掷骰子的程序,但我需要使保存按钮起作用,有人可以帮忙吗?我如何将 dice_score.txt 文件链接到该程序?

最佳答案

操作监听器未添加到“保存按钮”。

save.addActionListener(new SaveActionListener()); 

关于java - 我怎样才能通过编写这段代码来使保存按钮工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com