2016-04-21 149 views
1
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文件鏈接到此程序?如何通過編寫此代碼使保存按鈕工作?

+0

注意:Java與JavaScript沒有任何關係。 –

回答

0

操作偵聽器未添加到保存按鈕。

save.addActionListener(new SaveActionListener()); 
0

DiceFrame()年底補充一點:

save.addActionListener(new SaveActionListener()); 
0

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

好,你必須遵循這種模式,做

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

雖然在現實中,它沒有必要 創建一個命名實例,你可以簡單地做:

save.addActionListener (new SaveActionListener()); 
+0

保存按鈕仍然無法正常工作。當我點擊保存按鈕時沒有發生任何事情? – Alex

+0

它是否進入SaveActionListener? –

+0

當我點擊保存按鈕時沒有任何反應?我不知道你輸入什麼意思? – Alex