您的位置:首页 > 编程语言 > Java开发

Java编程思想 第4版 练习题 / 第22章 图形化用户界面 / 练习28

2010-05-08 05:17 453 查看
/*

* Java编程思想 第4版

* 第22章 图形化用户界面

* 练习28:(7)创建一个骰子类(只是一个类,没有GUI),然后创建五个骰子并重复地掷骰子。

* 画出一条表示每次掷骰子的点数总和的曲线,然后在你掷骰子的次数越来越多时,动态地展开

* 显示这条曲线。

*

* ugi/DiceModel.java只构建骰子类;ugi/ThrowDiceFrame.java完成创建窗口及绘制曲线。

*/

package gui;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextArea;

import static util.SwingConsole.*;

import static gui.DiceModel.*;

class DrawLine extends JPanel{

private ArrayList sumValueList = new ArrayList();

private int totalThrowTimes;

public DrawLine(){

setBackground(new Color(0,47,47));

}

@Override

public void paintComponent(Graphics g){

super.paintComponent(g);

int maxWidth = getWidth();

int maxHeight =getHeight();

double vStep = (double)maxHeight/30;

double hStep = (double)maxWidth/(double)(totalThrowTimes-1);

g.setColor(Color.red);

for(int i = 1;i<sumValueList.size();i++){

int x1 = (int)(hStep*(i-1));

int x2 = (int)(hStep*i);

int y1 = (int)(maxHeight-(Integer)(sumValueList.get(i-1))*vStep);

int y2 = (int)(maxHeight-(Integer)(sumValueList.get(i))*vStep);

g.drawLine(x1,y1,x2,y2);

}

}

public void getLastTimeValue(int newTotalThrowTimes,int SumValue){

totalThrowTimes = newTotalThrowTimes;

sumValueList.add(SumValue);

repaint();

}

}

public class ThrowDiceFrame extends JFrame{

private DrawLine dl = new DrawLine();

private int totalTimes;

private int nextSum;

private JButton throwBut = new JButton("Throw !");

private JTextArea sumFie = new JTextArea(1,1);

private ArrayList<DiceModel> dices = new ArrayList<DiceModel>();

public ThrowDiceFrame(){

for(int i = 0;i<5;i++){

dices.add(new DiceModel());

}

throwBut.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

sumFie.setText(" ");

for(DiceModel dm:dices){

dm.getValue();

nextSum += dm.value;

sumFie.append(""+dm.value+", ");

}

sumFie.append(" SUM: "+nextSum+" ");

++totalTimes;

dl.getLastTimeValue(totalTimes,nextSum);

nextSum = 0;

}

});

add(BorderLayout.SOUTH,throwBut);

add(BorderLayout.NORTH,sumFie);

add(dl);

}

public static void main(String[] args) {

run(new ThrowDiceFrame(),600,300);

}

}

-------------------------------------------------------------------------------

/*
* ugi/DiceModel.java只构建骰子类;
*/

package gui;

import java.util.Random;
import javax.swing.JTextField;

public class DiceModel extends JTextField{
private Random rand = new Random();
public int value;

public void getValue(){
value = rand.nextInt(6)+1;
setText(" "+value);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: