Java GUI程序示例

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<array.length;i++) {
			Paint p = array[i];//获取数组中指定下标位置的图形对象
			if(p!=null) {
				x1=p.getX1();
				x2=p.getX2();
				y1=p.getY1();
				y2=p.getY2();
				
				g.setColor(p.getColor());
				if(p.getName().equals("直线")) {
					g.drawLine(x1, y1, x2, y2);	
				} else if(p.getName().equals("矩形")) {
					g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2),Math.abs(y1-y2));
				} else if(p.getName().equals("圆")) {
					g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2),Math.abs(y1-y2));
				} else if(p.getName().equals("文字")) {
					g.drawString("这是文字效果", x1, y1);
				} else if(p.getName().equals("铅笔")||p.getName().equals("刷子")||p.getName().equals("橡皮")) {
					g2d.setStroke(new BasicStroke(p.getWidth()));
					g2d.drawLine(x1, y1, x2, y2);
				} else if(p.getName().equals("喷枪")) {
		    		g.drawLine(x1,y1,x2,y2);	
				} else if(p.getName().equals("长方体")) {
					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(new Color(100, 200, 100));
		        	g.fillRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2),Math.abs(y1-y2));
		        	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);
				}
				else
					break;
				
			}
		}
	}
	
	public void Ondraw() {
		
		//在初始化界面的方法中,实例化JFrame窗体容器组件类的对象
		//JFrame frame = new JFrame();
		//设置窗体容器组件对象的属性值:标题、大小、显示位置、关闭操作、可见。
		this.setTitle("画板");
		this.setSize(700,700);
		this.setDefaultCloseOperation(3);
		this.setLocationRelativeTo(null);
		
		//实例化FlowLayout流式布局类的对象,设置对齐方式
		FlowLayout fl = new FlowLayout(FlowLayout.CENTER);
		this.setLayout(fl);
		
		//在实例化DrawListener类的对象时将获取的画笔对象传递过去
		DrawListener dl = new DrawListener(this,array);
		
		String[] typeArray = {"直线","矩形","圆","文字","铅笔","刷子","橡皮","喷枪","长方体"};
		for(int i=0;i<typeArray.length;i++) {
			JButton button = new JButton(typeArray[i]);
			button.setPreferredSize(new Dimension(80,30));
			this.add(button);
			button.addActionListener(dl);//添加动作监听方法
		}
		
		Color[] colorArray = {Color.red,Color.green,Color.blue};
		for(int i=0;i<colorArray.length;i++) {
			JButton button = new JButton();
			button.setBackground(colorArray[i]);
			button.setPreferredSize(new Dimension(30,30));
			this.add(button);
			button.addActionListener(dl);//添加动作监听方法
		}
		
		this.setVisible(true);
		
		//获取窗体上的画笔对象
		Graphics g = this.getGraphics();
		
		//给窗体添加鼠标事件监听方法,指定事件的处理类的对象dl;
		dl.setG(g);//设置方法将画笔g传到DrawListener
		this.addMouseListener(dl);	
		this.addMouseMotionListener(dl);
	}
}

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:\JavaTest\image2)

源码如下:

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:\JavaTest2\image2)

 此程序由两个文件组成: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() {
	// 设置窗口 icon
	Image 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 stub
	String 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); //默认编码ANSI
			InputStreamReader fReader =new InputStreamReader(new FileInputStream(file), "UTF-8"); //
			br = new BufferedReader(fReader);
			String readStr = "";
			String allCode = "";
			while ((readStr = br.readLine()) != null) {
				allCode += readStr + "\r\n";
			}
			jta.setText(allCode);
    		} catch (Exception e2) {
			e2.printStackTrace();
			// TODO: handle exception
		} finally {
			try {
				br.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.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); //默认编码ANSI
			OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file),"utf-8"); //
			bw = new BufferedWriter(fw);
			String jtaStr = jta.getText();
			bw.write(jtaStr);
		} catch (Exception e2) {
			// TODO: handle exception
			e2.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
    	} else if (str.equals("退出")) {
		System.exit(0);
	}
  }
}

编译运行参见下图:

  • 8
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值