如何通过编写此代码使保存按钮工作?

时间:2016-04-21 01:24:26

标签: java

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文件链接到此程序?

3 个答案:

答案 0 :(得分:0)

动作侦听器未添加到“保存”按钮。

save.addActionListener(new SaveActionListener()); 

答案 1 :(得分:0)

DiceFrame()

的末尾添加此内容
save.addActionListener(new SaveActionListener()); 

答案 2 :(得分:0)

action = new DiceActionListener();
roll.addActionListener(action);

你必须遵循这种模式并做

SaveActionListener action2 = new SaveActionListener ();
save.addActionListener(action2);

虽然实际上没有必要创建命名实例,但您只需执行

save.addActionListener (new SaveActionListener ());
相关问题