欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

JavaGUI程序示例

时间:2023-08-01

Java GUI程序示例

与命令行界面相比,图形界面对于用户来说更为简便易用。图形用户界面(Graphical User Interface,简称 GUI),关于Java图形用户界面,可参见 https://blog.csdn.net/cnds123/article/details/113251233

下面给出几个具体的示例,包括一、 Java猜数字游戏GUI版;二、 JAVA简单画图程序;三、GUI界面人机猜拳小程序;四、简单记事本。源码参考自网络。

一、 Java猜数字游戏GUI版

源码如下:

import javax.swing.Jframe;import javax.swing.JLabel;import javax.swing.SwingConstants;import java.awt.Dimension;import java.awt.Font;import javax.swing.JTextField;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class GuessNumberGUI extends Jframe{ private JTextField txtGuess; private JLabel lblOutput; private JButton btnGuess; private JButton btnPlayAgain; private int theNumber; private int numberOfGames; public void checkGuess() { String guessText = txtGuess.getText(); String message = ""; try { int guess = Integer.parseInt(guessText); if(guess < theNumber) { message = guess + "小了!再猜!还剩" + (numberOfGames-1) + "次机会!"; }else if( guess > theNumber) { message = guess + "大了!再猜!还剩" + (numberOfGames-1) + "次机会!"; }else { message = guess + "猜对啦!再玩儿一次"; btnPlayAgain.setVisible(true); gameOver(); return; } numberOfGames--; if (numberOfGames <= 0){ message = guess + "不太好,没有机会了,正确答案是:" + theNumber; btnPlayAgain.setVisible(true); gameOver(); } } catch (Exception e) { message = "请输入1-100之间的整数!还剩" + numberOfGames + "次机会!"; } finally { lblOutput.setText(message); txtGuess.requestFocus(); txtGuess.selectAll(); } } public void newGame() { theNumber = (int)(Math.random() * 100 + 1); numberOfGames = 7; //第一次执行了一次初始化值为6 btnGuess.setEnabled(true); txtGuess.setEnabled(true); } //游戏结束使猜测按钮和输入框不可选中 public void gameOver(){ btnGuess.setEnabled(false); txtGuess.setEnabled(false); } public GuessNumberGUI() { setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); setTitle("JAVA猜数字小游戏"); getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("JAVA猜数字"); lblNewLabel.setFont(new Font("宋体", Font.BOLD, 15)); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setBounds(159, 27, 116, 18); getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("输入数字范围1-100"); lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT); lblNewLabel_1.setBounds(26, 72, 213, 15); getContentPane().add(lblNewLabel_1); txtGuess = new JTextField(); txtGuess.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { checkGuess(); } }); txtGuess.setBounds(250, 69, 66, 21); getContentPane().add(txtGuess); txtGuess.setColumns(10); btnGuess = new JButton("猜一下!"); btnGuess.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { checkGuess(); } }); btnGuess.setBounds(170, 114, 93, 23); getContentPane().add(btnGuess); lblOutput = new JLabel("请在上面输入框中输入数字并点击猜一下!现在你有7次机会"); lblOutput.setHorizontalAlignment(SwingConstants.CENTER); lblOutput.setBounds(50, 214, 350, 15); getContentPane().add(lblOutput); btnPlayAgain = new JButton("再玩一次!"); btnPlayAgain.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newGame(); txtGuess.setText(""); lblOutput.setText("请在上面输入框中输入数字并点击猜一下!你有7次机会!"); btnPlayAgain.setVisible(false); } }); btnPlayAgain.setBounds(164, 164, 105, 23); btnPlayAgain.setVisible(false); getContentPane().add(btnPlayAgain); } public static void main(String args[]) { GuessNumberGUI theGame = new GuessNumberGUI(); theGame.newGame(); theGame.setSize(new Dimension(450, 300)); theGame.setVisible(true); }}

保存文件名GuessNumberGUI.java(我的保存位置D:JavaTest)

注意 :文件名中点后面的后缀(扩展名)不要错了。用记事本写java源码,如果代码中含有中文字符,编码选用ANSI,否则编译通不过,提示 “错误: 编码 GBK 的不可映射字符”。

编译运行参见下图:

二、 JAVA简单画图程序

此程序由三个文件组成:Draw.java、Paint.java和DrawListener.java,我将它们都保存于D:JavaTest。

Draw.java源码如下:

import java.awt.Color;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.BasicStroke;import javax.swing.JButton;import javax.swing.Jframe;public class Draw extends Jframe{public static void main(String[] args) {//在主函数中,实例化Draw类的对象,调用初始化界面的方法Draw draw = new Draw();draw.ondraw();}private Paint[] array = new Paint[100000];//定义存储图形的数组private int x1, y1, x2, y2;//重写父类的重绘方法public void paint (Graphics g) {super.paint(g);Graphics2D g2d = (Graphics2D) g;g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);// 设置画笔抗锯齿//把存储在数组中的图形数据取出来,重新画一次for (int i=0;i

Paint.java源码如下:

import java.awt.Color;public class Paint {private int x1,y1,x2,y2;private Color color;private String name;private int width;//线条粗细public Paint(int x1, int y1, int x2, int y2, Color color, String name) {super();this.x1 = x1;this.y1 = y1;this.x2 = x2;this.y2 = y2;this.color = color;this.name = name;}public Paint(int x1, int y1, int x2, int y2, Color color, String name, int width) {super();this.x1 = x1;this.y1 = y1;this.x2 = x2;this.y2 = y2;this.color = color;this.name = name;this.width = width;}//可以把方法写在这里,在Draw类和DrawLisyener类中调用public int getX1() {return x1;}public void setX1(int x1) {this.x1 = x1;}public int getY1() {return y1;}public void setY1(int y1) {this.y1 = y1;}public int getX2() {return x2;}public void setX2(int x2) {this.x2 = x2;}public int getY2() {return y2;}public void setY2(int y2) {this.y2 = y2;}public Color getColor() {return color;}public void setColor(Color color) {this.color = color;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}}

DrawListener.java源码如下:

import java.awt.BasicStroke;import java.awt.Color;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.util.Random;import javax.swing.JButton;import javax.swing.Jframe;//定义DrawListener事件处理类,该类继承自MouseListener鼠标事件接口,重写接口中的抽象方法。public class DrawListener implements MouseListener,MouseMotionListener,ActionListener {private int x1,x2,y1,y2;//定义Graphics画笔类的对象属性名private Graphics2D g;public String name = "直线";private Color color = Color.red;private Jframe frame;private Paint[] array;//定义存储图形的数组private int index = 0;public DrawListener(Jframe frame,Paint[] array) {this.frame = frame;this.array = array;}//定义一个带Graphics参数的构造方法public void setG(Graphics g) {this.g = (Graphics2D) g;this.g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);// 设置画笔开启抗锯齿}public void actionPerformed(ActionEvent e) {System.out.println("点击的按钮是:"+e.getActionCommand());if(e.getActionCommand().equals("")) {JButton button = (JButton) e.getSource();//获取事件源对象color = button.getBackground();//获取背景颜色}else {name=e.getActionCommand();//获取按钮信息}}public void mouseDragged(MouseEvent e){//System.out.println("拖动");x2 = e.getX();y2 = e.getY();switch(name) {case "铅笔":g.setStroke(new BasicStroke(2));//设置线条的粗细g.drawLine(x1, y1, x2, y2);//画曲线Paint paint = new Paint(x1,y1,x2,y2,color,name,2);//根据图形的数据实例化Paint对象if(index<1000)array[index++] = paint;//将数组对象存入到数组中x1 = x2;y1 = y2;break;case "刷子":g.setStroke(new BasicStroke(10));//设置线条的粗细g.drawLine(x1, y1, x2, y2);//画曲线Paint pain = new Paint(x1,y1,x2,y2,color,name,10);//根据图形的数据实例化Paint对象if(index<1000)array[index++] = pain;//将数组对象存入到数组中x1 = x2;y1 = y2;break;case "橡皮":color = frame.getContentPane().getBackground(); g.setColor(color); g.setStroke(new BasicStroke(50));g.drawLine(x1, y1, x2, y2);//画曲线Paint pai = new Paint(x1,y1,x2,y2,color,name,50);//根据图形的数据实例化Paint对象if(index<1000)array[index++] = pai;//将数组对象存入到数组中x1 = x2;y1 = y2; break;case "喷枪":Random rand = new Random(); for(int i=0;i<10;i++) { int p = rand.nextInt(10); int q = rand.nextInt(10); g.drawLine(x2+p, y2+q, x2+p, y2+q); Paint pa = new Paint(x2+p, y2+q, x2+p, y2+q,color,name);//根据图形的数据实例化Paint对象 if(index<1000) array[index++] = pa;//将数组对象存入到数组中 }x1 = x2;y1 = y2;break;}}public void mouseMoved(MouseEvent e) { } public void mouseClicked(MouseEvent e) { //System.out.println("点击"); } public void mousePressed(MouseEvent e) { //System.out.println("按下"); //在按下和释放的事件处理方法中获取按下和释放的坐标值 x1 = e.getX(); y1 = e.getY(); g.setColor(color); } public void mouseReleased(MouseEvent e) { //System.out.println("释放"); x2 = e.getX(); y2 = e.getY(); //设置画笔的颜色 //g.setColor(Color.green); //g.setColor(new Color(100, 100, 100)); //根据按下和释放的坐标值,使用Graphics对象进行画图 g.setStroke(new BasicStroke(1));//设置线条的粗细 switch(name) { case "直线": g.drawLine(x1, y1, x2, y2); Paint paint = new Paint(x1,y1,x2,y2,color,name,1);//根据图形的数据实例化Paint对象 if(index<1000) array[index++] = paint;//将图形对象存入到数组中 break; case "矩形": g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2),Math.abs(y1-y2)); Paint k = new Paint(x1,y1,x2,y2,color,name,1);//根据图形的数据实例化Paint对象 if(index<1000) array[index++] = k;//将图形对象存入到数组中 break; case "圆": g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2),Math.abs(y1-y2)); Paint f = new Paint(x1,y1,x2,y2,color,name,1);//根据图形的数据实例化Paint对象 if(index<1000) array[index++] = f;//将图形对象存入到数组中 break; case "文字": g.drawString("这是文字效果", x1, y1); Paint j = new Paint(x1,y1,x2,y2,color,name,1);//根据图形的数据实例化Paint对象 if(index<1000) array[index++] = j;//将图形对象存入到数组中 break; case "长方体": g.setColor(new Color(100, 200, 100)); g.fillRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2),Math.abs(y1-y2)); int a,b,c,d; a=Math.min(x1, x2); b=Math.max(x1, x2); c=Math.min(y1, y2); d=Math.max(y1, y2); int m=(int)((b-a)*Math.cos(Math.PI/4)*Math.sin(Math.PI/4)); int n=(int)((b-a)*Math.cos(Math.PI/4)*Math.sin(Math.PI/4)); //顶面 g.setColor(Color.green); g.fillPolygon(new int[] {a, a+m, b+m,b},new int[] {c,c-n,c-n,c},4); //右侧面 g.setColor(Color.black); g.fillPolygon(new int[] {b, b, b+m,b+m},new int[] {c,d,d-n,c-n},4); Paint h = new Paint(x1,y1,x2,y2,color,name,1);//根据图形的数据实例化Paint对象 if(index<1000) array[index++] = h;//将图形对象存入到数组中 break; } } public void mouseEntered(MouseEvent e) { //System.out.println("进入"); } public void mouseExited(MouseEvent e) { //System.out.println("离开"); }}

编译运行参见下图:

三、GUI界面人机猜拳小程序

 本程序需要四个图像(我的保存位置D:JavaTestimage2)

源码如下:

import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class CaiQuan { public static void main(String[] args) { // 窗口 Jframe caiquan = new Jframe("猜拳"); caiquan.setSize(700, 550); caiquan.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); caiquan.setLocation(650, 250); JTextField jieguo = new JTextField(); JLabel diannao = new JLabel("电脑"); JLabel people = new JLabel("人"); JLabel tishi = new JLabel("请先选择人要出的内容"); JLabel jieguotishi = new JLabel("结果是:"); JLabel bijiao = new JLabel(); //图片 Icon jiandaotu = new ImageIcon("image2\剪刀.jpg"); Icon shitoutu = new ImageIcon("image2\石头.jpg"); Icon butu = new ImageIcon("image2\布.jpg"); Icon kongbai = new ImageIcon("image2\空白.jpg"); // 按钮 JButton wanjia = new JButton("玩家"); JButton dadiannao = new JButton(kongbai); JButton shitou = new JButton("石头"); JButton jiandao = new JButton("剪刀"); JButton bu = new JButton("布"); JButton caipan = new JButton("裁判"); //布局 caiquan.setLayout(null); //电脑和人的文本布局 tishi.setBounds(270, 0, 150, 60); diannao.setBounds(70, 20, 50, 50); people.setBounds(490, 20, 50, 50); //结果提示框 jieguo.setBounds(295, 420, 80, 20); jieguotishi.setBounds(250, 420, 100, 20); //电脑和玩家大按钮布局 dadiannao.setBounds(30, 70, 300, 300); wanjia.setBounds(360, 70, 300, 300); // 石头剪刀布caipan 按钮布局 shitou.setBounds(420, 400, 60, 40); jiandao.setBounds(480, 400, 60, 40); bu.setBounds(540, 400, 60, 40); caipan.setBounds(100, 400, 80, 40);// 最上边提示布局 caiquan.add(tishi);// 电脑和玩家文本提示 caiquan.add(diannao); caiquan.add(people);// 电脑和玩家按钮 caiquan.add(dadiannao); caiquan.add(wanjia);// 石头剪刀布caipan按钮 caiquan.add(caipan); caiquan.add(shitou); caiquan.add(jiandao); caiquan.add(bu); caiquan.setVisible(true);// 添加响应//电脑随机 class MyAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int suiji = (int) (Math.random() * 3 + 1); String a = bijiao.getText(); if (suiji == 1) { dadiannao.setIcon(jiandaotu); if (a.equals("jiandao")) { JOptionPane.showMessageDialog(null, "平局", "结果", JOptionPane.ERROR_MESSAGE); } else if (a.equals("shitou")) { JOptionPane.showMessageDialog(null, "人赢了", "结果", JOptionPane.ERROR_MESSAGE); } else if (a.equals("bu")) { JOptionPane.showMessageDialog(null, "电脑赢了", "结果", JOptionPane.ERROR_MESSAGE); } } if (suiji == 2) { dadiannao.setIcon(shitoutu); if (a.equals("shitou")) { JOptionPane.showMessageDialog(null, "平局", "结果", JOptionPane.ERROR_MESSAGE); } else if (a.equals("bu")) { JOptionPane.showMessageDialog(null, "人赢了", "结果", JOptionPane.ERROR_MESSAGE); } else if (a.equals("jiandao")) { JOptionPane.showMessageDialog(null, "电脑赢了", "结果", JOptionPane.ERROR_MESSAGE); } } if (suiji == 3) { dadiannao.setIcon(butu); if (a.equals("bu")) { JOptionPane.showMessageDialog(null, "平局", "结果", JOptionPane.ERROR_MESSAGE); } else if (a.equals("jiandao")) { JOptionPane.showMessageDialog(null, "人赢了", "结果", JOptionPane.ERROR_MESSAGE); } else if (a.equals("shitou")) { JOptionPane.showMessageDialog(null, "电脑赢了", "结果", JOptionPane.ERROR_MESSAGE); } } } }// 人选择 class PeopleChoose implements ActionListener { @Override public void actionPerformed(ActionEvent b) { if (b.getSource() == jiandao) { wanjia.setIcon(jiandaotu); bijiao.setText("jiandao"); } else if (b.getSource() == shitou) { wanjia.setIcon(shitoutu); bijiao.setText("shitou"); } else if (b.getSource() == bu) { wanjia.setIcon(butu); bijiao.setText("bu"); } } } // 电脑随机监听 MyAction m1 = new MyAction(); caipan.addActionListener(m1); // 人选择监听 PeopleChoose p1 = new PeopleChoose(); jiandao.addActionListener(p1); shitou.addActionListener(p1); bu.addActionListener(p1); }}

保存文件名CaiQuan.java(我的保存位置D:JavaTest)

编译运行参见下图:

四、简单记事本

本程序需要一个图像做标题栏图标(我的保存位置D:JavaTest2image2)

 此程序由两个文件组成:Draw.java、和DrawListener.java,我将它们都保存于D:JavaTest2。

NotepadMain.java源码如下:

public class NotepadMain { public static void main(String[] str) {MyNotePad notePad = new MyNotePad();}}

MyNotePad.java源码如下: 

import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.*;import javax.swing.*;import javax.swing.filechooser.FileNameExtensionFilter; //class MyNotePad extends Jframe implements ActionListener { private Jtextarea jta = null; private JMenuBar jmb = null; private JMenu jm = null; private JMenuItem jmiOpen = null; private JMenuItem jmiSave = null; private JMenuItem jmiExit = null; private JFileChooser jfc = null; public MyNotePad() {// 设置窗口 iconImage icon = Toolkit.getDefaultToolkit().getImage("image/icon1.png");this.setIconImage(icon);jta = new Jtextarea();this.setLayout(new BorderLayout());this.add(jta); jmb = new JMenuBar();jm = new JMenu("文件");jmiOpen = new JMenuItem("打开");jmiOpen.addActionListener(this);jmiOpen.setActionCommand("打开"); jmiSave = new JMenuItem("保存");jmiSave.addActionListener(this);jmiSave.setActionCommand("保存"); jmiExit = new JMenuItem("退出");jmiExit.addActionListener(this);jmiExit.setActionCommand("退出"); jm.add(jmiOpen); jm.add(jmiSave);jm.add(jmiExit);jmb.add(jm);this.setJMenuBar(jmb); this.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);this.setSize(400, 300);this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString str = e.getActionCommand();if (str.equals("打开")) {System.out.println("打开");jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("txt文件", "txt");// 创建文件类型过滤器 jfc.setFileFilter(filter);// 设置选择器的过滤器jfc.setDialogTitle("请选择文件!");jfc.showOpenDialog(null);jfc.setVisible(true); File file = jfc.getSelectedFile();BufferedReader br = null; try {//FileReader fReader = new FileReader(file); //默认编码ANSIInputStreamReader fReader =new InputStreamReader(new FileInputStream(file), "UTF-8"); //br = new BufferedReader(fReader);String readStr = "";String allCode = "";while ((readStr = br.readLine()) != null) {allCode += readStr + "rn";}jta.setText(allCode); } catch (Exception e2) {e2.printStackTrace();// TODO: handle exception} finally {try {br.close();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} } else if (str.equals("保存")) {JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("txt文件", "txt");// 创建文件类型过滤器 jfc.setFileFilter(filter);// 设置选择器的过滤器jfc.setDialogTitle("已保存");jfc.showSaveDialog(null);File file = jfc.getSelectedFile();BufferedWriter bw = null; try {//FileWriter fw = new FileWriter(file); //默认编码ANSIOutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file),"utf-8"); //bw = new BufferedWriter(fw);String jtaStr = jta.getText();bw.write(jtaStr);} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();} finally {try {bw.close();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} } else if (str.equals("退出")) {System.exit(0);} }}

编译运行参见下图:

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。