Javalab4
实验4 Java Swing图形用户界面1、相关知识点GUI相关的类组件的属性及功能事件源、监视器、处理事件的接口2、实验目的学习掌握事件处理3、实验要求按以下需求可扩充设计并完成一个能运行的且界面美观的小软件。提交可运行软件程序主要针对小学生的算术计算。1、可以自定义计算的难度此项可根据功能进行扩展2、随机获取不一样的题目能通过按键触发确定填写输入的答案是否正确。3、计算满足 - * /(可扩展4、操作数可以是整数、小数、分数等等可扩展代码实现ArithmeticFrame.javaimport javax.swing.;import java.awt.;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Random;public class ArithmeticFrame extends JFrame implements ActionListener {private JComboBox difficultyBox;private JLabel questionLabel;private JTextField answerField;private JButton checkBtn, nextBtn;private JLabel tipLabel, scoreLabel;private Random rand new Random(); private double rightAnswer; private int score 0; public ArithmeticFrame() { setTitle(小学生算术练习软件); setSize(450, 280); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setLayout(new BorderLayout(10, 10)); setResizable(false); JPanel topPanel new JPanel(); topPanel.add(new JLabel(选择难度)); String[] diffs {简单(0~10整数), 中等(0~100整数), 困难(小数运算)}; difficultyBox new JComboBox(diffs); topPanel.add(difficultyBox); add(topPanel, BorderLayout.NORTH); JPanel midPanel new JPanel(); midPanel.setLayout(new GridLayout(3,1,5,5)); questionLabel new JLabel(题目, SwingConstants.CENTER); questionLabel.setFont(new Font(宋体, Font.PLAIN, 20)); midPanel.add(questionLabel); JPanel inputPanel new JPanel(); inputPanel.add(new JLabel(你的答案)); answerField new JTextField(12); inputPanel.add(answerField); midPanel.add(inputPanel); tipLabel new JLabel(请作答, SwingConstants.CENTER); midPanel.add(tipLabel); add(midPanel, BorderLayout.CENTER); JPanel btnPanel new JPanel(); checkBtn new JButton(确认答案); nextBtn new JButton(下一题); checkBtn.addActionListener(this); nextBtn.addActionListener(this); btnPanel.add(checkBtn); btnPanel.add(nextBtn); add(btnPanel, BorderLayout.SOUTH); scoreLabel new JLabel(当前得分0, SwingConstants.RIGHT); add(scoreLabel, BorderLayout.EAST); createNewQuestion(); } private void createNewQuestion() { int level difficultyBox.getSelectedIndex(); double a, b; char op; String ops -*/; if (level 0) { a rand.nextInt(11); b rand.nextInt(11); } else if (level 1) { a rand.nextInt(101); b rand.nextInt(101); } else { a Math.round(rand.nextDouble() * 100) / 100.0; b Math.round(rand.nextDouble() * 100) / 100.0; } op ops.charAt(rand.nextInt(4)); switch(op){ case : rightAnswer a b; break; case -: rightAnswer a - b; break; case *: rightAnswer a * b; break; case /: if(b 0) b 1; rightAnswer a / b; break; } String qStr; if(level 1){ qStr String.format(%.0f %c %.0f ?, a, op, b); }else{ qStr String.format(%.2f %c %.2f ?, a, op, b); } questionLabel.setText(qStr); answerField.setText(); tipLabel.setText(请输入答案); } Override public void actionPerformed(ActionEvent e) { if(e.getSource() checkBtn){ try { double userAns Double.parseDouble(answerField.getText()); if(Math.abs(userAns - rightAnswer) 0.001){ tipLabel.setText( 回答正确); score; }else{ tipLabel.setText( 答错了正确答案 String.format(%.2f, rightAnswer)); } scoreLabel.setText(当前得分 score); } catch (Exception ex) { tipLabel.setText( 请输入合法数字); } }else if(e.getSource() nextBtn){ createNewQuestion(); } } public static void main(String[] args) { SwingUtilities.invokeLater(() - { new ArithmeticFrame().setVisible(true); }); }}代码运行结果实验2选做可AI终端**扫雷、射击。。。游戏1、良好的界面实现2、可调节难度3、计时与计步功能4、保存/读取游戏进度5、。。。。可扩展代码实现import javax.swing.;import java.awt.;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.io.*;import java.util.Random;public class MineSweeper extends JFrame {private int rows 9;private int cols 9;private int mineCount 10;private JButton[][] buttons;private boolean[][] isMine;private boolean[][] opened;private boolean[][] marked;private JLabel timeLabel; private JLabel stepLabel; private Timer timer; private int time 0; private int step 0; private boolean gameOver false; private JPanel topPanel; public MineSweeper() { setTitle(扫雷游戏); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new BorderLayout()); topPanel new JPanel(); JButton easy new JButton(简单); JButton mid new JButton(中等); JButton hard new JButton(困难); JButton save new JButton(保存进度); JButton load new JButton(读取进度); timeLabel new JLabel(时间0); stepLabel new JLabel(步数0); topPanel.add(easy); topPanel.add(mid); topPanel.add(hard); topPanel.add(save); topPanel.add(load); topPanel.add(timeLabel); topPanel.add(stepLabel); add(topPanel, BorderLayout.NORTH); easy.addActionListener(e - initGame(9,9,10)); mid.addActionListener(e - initGame(16,16,40)); hard.addActionListener(e - initGame(16,30,99)); save.addActionListener(e - saveGame()); load.addActionListener(e - loadGame()); timer new Timer(1000, e - { time; timeLabel.setText(时间 time); }); initGame(9,9,10); pack(); setLocationRelativeTo(null); } private void initGame(int r, int c, int m) { rows r; cols c; mineCount m; time 0; step 0; gameOver false; if(timer.isRunning()) timer.stop(); timeLabel.setText(时间0); stepLabel.setText(步数0); JPanel gamePanel new JPanel(new GridLayout(rows, cols)); getContentPane().removeAll(); getContentPane().add(topPanel, BorderLayout.NORTH); buttons new JButton[rows][cols]; isMine new boolean[rows][cols]; opened new boolean[rows][cols]; marked new boolean[rows][cols]; Random ran new Random(); int count 0; while(count mineCount){ int x ran.nextInt(rows); int y ran.nextInt(cols); if(!isMine[x][y]){ isMine[x][y] true; count; } } for(int i0;irows;i){ for(int j0;jcols;j){ JButton btn new JButton(); btn.setPreferredSize(new Dimension(30,30)); final int x i, y j; btn.addMouseListener(new MouseAdapter(){ Override public void mousePressed(MouseEvent e) { if(gameOver) return; if(SwingUtilities.isLeftMouseButton(e)){ if(!timer.isRunning()) timer.start(); step; stepLabel.setText(步数step); open(x,y); checkWin(); }else if(SwingUtilities.isRightMouseButton(e)){ if(opened[x][y]) return; marked[x][y] !marked[x][y]; btn.setText(marked[x][y] ? : ); } } }); buttons[i][j] btn; gamePanel.add(btn); } } add(gamePanel, BorderLayout.CENTER); pack(); } private void open(int x, int y) { if(x0||xrows||y0||ycols) return; if(opened[x][y] || marked[x][y]) return; opened[x][y] true; if(isMine[x][y]){ gameOver true; timer.stop(); JOptionPane.showMessageDialog(this, 踩到地雷游戏结束); for(int i0;irows;i){ for(int j0;jcols;j){ if(isMine[i][j]) buttons[i][j].setText(); } } return; } int num getMineNum(x,y); if(num0){ buttons[x][y].setText(String.valueOf(num)); }else{ for(int dx-1;dx1;dx){ for(int dy-1;dy1;dy){ open(xdx,ydy); } } } } private int getMineNum(int x, int y){ int n 0; for(int dx-1;dx1;dx){ for(int dy-1;dy1;dy){ int nx xdx, ny ydy; if(nx0nxrowsny0nycolsisMine[nx][ny]) n; } } return n; } private void checkWin(){ int openCnt 0; for(int i0;irows;i) for(int j0;jcols;j) if(opened[i][j]) openCnt; if(openCnt rows*cols - mineCount){ gameOver true; timer.stop(); JOptionPane.showMessageDialog(this, 恭喜扫雷成功); } } private void saveGame(){ try(ObjectOutputStream oos new ObjectOutputStream(new FileOutputStream(mine.dat))){ oos.writeInt(rows); oos.writeInt(cols); oos.writeObject(isMine); oos.writeObject(opened); oos.writeObject(marked); oos.writeInt(time); oos.writeInt(step); JOptionPane.showMessageDialog(this,保存成功); }catch (Exception e){ e.printStackTrace(); JOptionPane.showMessageDialog(this,保存失败); } } private void loadGame(){ File f new File(mine.dat); if(!f.exists()){ JOptionPane.showMessageDialog(this,无存档文件); return; } try(ObjectInputStream ois new ObjectInputStream(new FileInputStream(f))){ int saveRow ois.readInt(); int saveCol ois.readInt(); if(saveRow ! rows || saveCol ! cols){ JOptionPane.showMessageDialog(this, 存档尺寸不匹配当前rows×cols\n存档saveRow×saveCol\n请切换对应难度再读档); ois.close(); return; } isMine (boolean[][]) ois.readObject(); opened (boolean[][]) ois.readObject(); marked (boolean[][]) ois.readObject(); time ois.readInt(); step ois.readInt(); timeLabel.setText(时间time); stepLabel.setText(步数step); if(!timer.isRunning()) timer.start(); for(int i0; irows iisMine.length; i){ for(int j0; jcols jisMine[i].length; j){ if(marked[i][j]){ buttons[i][j].setText(); }else if(opened[i][j]){ int n getMineNum(i,j); buttons[i][j].setText(n0 ? String.valueOf(n) : ); }else{ buttons[i][j].setText(); } } } }catch (Exception e){ e.printStackTrace(); JOptionPane.showMessageDialog(this,读取存档出错); } } public static void main(String[] args) { SwingUtilities.invokeLater(()-{ new MineSweeper().setVisible(true); }); }}运行结果

相关新闻