java图形界面写个小桌面,内置简单小软件
Posted zhenhong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java图形界面写个小桌面,内置简单小软件相关的知识,希望对你有一定的参考价值。
一、做个这样的效果,双击图标打开相应的应用
二、主界面类,使用JavaSwing的JDesktopPane类创建这个桌面
package com.swing; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDesktopPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import com.swing.plane.PanelGame; import com.swing.sunModel.SunModel; /** * 获取文件的图标 FileSystemView fileSystemView = FileSystemView.getFileSystemView(); ImageIcon icon = (ImageIcon) fileSystemView.getSystemIcon(file); BufferedImage i = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); i.getGraphics().drawImage(icon.getImage(), 0, 0, null); File out = new File("src/lib/hello.png"); try { ImageIO.write(i, "png", out); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } * @author may * */ public class Desktop extends JFrame { private static final long serialVersionUID = 3899092629742973479L; private JDesktopPane desktop = null;//定义桌面面板 private JLabel backgroundImage = null;//定义桌面背景 private MouseOption mouseOption = new MouseOption();//鼠标监听对象 public Desktop(String title) { super(title); Toolkit toolkit = Toolkit.getDefaultToolkit(); //得到系统屏幕的大小 Dimension dimension = toolkit.getScreenSize(); //设置布局管理为BorderLayout this.setLayout(new BorderLayout()); int width = (int)dimension.getWidth(); int height = (int)dimension.getHeight() - 100; this.setSize(width, height); desktop = new JDesktopPane(); backgroundImage = new JLabel(); //创建一个空的的图片 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); BufferedImage ad = null; try { //读取背景图 ad = ImageIO.read(this.getClass().getResource("/lib/rapeFlower.jpg")); } catch (IOException e) { e.printStackTrace(); } //将背景图按比例缩放重新画到之前创建的空图片 g.drawImage(ad, 0, 0, width, height, null); //转化为Icon类图片 ImageIcon img = new ImageIcon(image); backgroundImage.setIcon(img); //设置存放背景图的背景标签的位置和大小 backgroundImage.setBounds(new Rectangle(0, 0, width, height)); //创建按钮 JButton myCompute = new JButton(); myCompute.setIcon(new ImageIcon(this.getClass().getResource("/lib/computer.png"))); myCompute.setBounds(20, 20, 48, 48); //设置按钮为透明 myCompute.setContentAreaFilled(false); //除去边框 myCompute.setBorderPainted(false); //添加事件监听 myCompute.addMouseListener(mouseOption ); //设置它的文本标识 myCompute.setText("compute"); //添加到桌面,并且比设置它的层次,比背景图更高一个层次,否侧会被背景图遮住,看不见 desktop.add(myCompute, Integer.MIN_VALUE + 1); JButton myNotebook= new JButton(); myNotebook.setIcon(new ImageIcon(this.getClass().getResource("/lib/notebook.png"))); myNotebook.setBounds(20, 88, 48, 48); myNotebook.setContentAreaFilled(false); myNotebook.setBorderPainted(false); myNotebook.addMouseListener(mouseOption); myNotebook.setText("notebook"); desktop.add(myNotebook, Integer.MIN_VALUE + 1); JButton myPanel= new JButton(); myPanel.setIcon(new ImageIcon(this.getClass().getResource("/lib/paper_plane.png"))); myPanel.setBounds(20, 156, 48, 48); myPanel.setContentAreaFilled(false); myPanel.setBorderPainted(false); myPanel.addMouseListener(mouseOption); myPanel.setText("panel"); desktop.add(myPanel, Integer.MIN_VALUE + 1); JButton mySunModel = new JButton(); mySunModel.setIcon(new ImageIcon(this.getClass().getResource("/lib/earth.net.png"))); mySunModel.setBounds(20, 224, 48, 48); mySunModel.setContentAreaFilled(false); mySunModel.setBorderPainted(false); mySunModel.addMouseListener(mouseOption); mySunModel.setText("sunModel"); desktop.add(mySunModel, Integer.MIN_VALUE + 1); desktop.add(backgroundImage, new Integer(Integer.MIN_VALUE)); this.getContentPane().add(desktop, BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private class MouseOption extends MouseAdapter { private int count; private Timer timer = new Timer(); private String str = null; private class MyTimerTask extends TimerTask { JButton button = null; public MyTimerTask(JButton button) { this.button = button; } @Override public void run() { //超过0.4s且点击了一次 if(count == 1) { count = 0; } //在0.4s内点击两次 if(count == 2) { //JDK7.0以上支持switch字符串 switch(str) { case "fileChooser" : JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.showOpenDialog(Desktop.this); File file = fileChooser.getSelectedFile(); if(file != null) { System.out.println(file.getAbsolutePath()); } break; case "notebook" : //调用windows系统自带的notepad /*try { Runtime.getRuntime().exec("notepad"); } catch (IOException e) { e.printStackTrace(); }*/ //调用自个写的一个特简易的记事本程序 Notepad notepad = new Notepad(); desktop.add(notepad); notepad.toFront(); break; case "compute" : //打开windows的文件管理器 try { java.awt.Desktop.getDesktop().open(new File(System.getProperty("user.home"))); } catch (IOException e) { e.printStackTrace(); } break; case "panel" : //启动飞机大战游戏 new PanelGame(); break; case "sunModel" : //启动太阳系模型,虽然没啥用,用来装B new SunModel(); break; } button.setContentAreaFilled(false); count = 0; } } } /** * 添加鼠标点击事件 */ @Override public void mouseClicked(MouseEvent e) { JButton button = (JButton) e.getSource(); button.setContentAreaFilled(true); str = button.getText(); count ++;//用于记录点击次数 //定制双击事件,使用定时器,每次点击后,延时0.4 timer.schedule(new MyTimerTask(button), 400); } } public static void main(String[] args) { new Desktop("桌面"); } }
三、Notepad简易小程序
1、效果图
2、Notepad.java的代码
package com.swing; import java.awt.Desktop; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * 简易笔记本 * @author may * */ public class Notepad extends JInternalFrame { private static final long serialVersionUID = -6148113299360403243L; private JMenuBar menuBar = null;//菜单栏 private JTextArea textArea = null;//输入框 private JScrollPane scrollPane = null;//带滚动条的面板 private MyAction myAction = new MyAction();//事件对象 private String dir = null;//保存打开过或者保存过文件的文件夹 private String fileDir = null;//保存你打开文件的文件夹 private boolean ctrlClick = false;//用于检测当前,你是否按下了Ctrl键 private boolean sClick = false;//用于检测当前,你是否按下了s键 public Notepad() { super("notepad"); this.setSize(600, 500);//窗口的大小 menuBar = new JMenuBar();//创建菜单栏 JMenu menu1 = new JMenu("文件");//创建菜单 JMenuItem menuItem2 = new JMenuItem("打开");//创建菜单项 JMenuItem menuItem4 = new JMenuItem("保存");//创建菜单项 menuItem4.addActionListener(myAction);//绑定事件 menuItem2.addActionListener(myAction);//绑定事件 JMenuItem menuItem3 = new JMenuItem("打开文件所在目录"); menuItem3.addActionListener(myAction); menu1.add(menuItem2); menu1.add(menuItem3); menu1.add(menuItem4); JMenu menu2 = new JMenu("版本信息"); menu2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { //定义弹窗后的按钮的文字 String[] options = {"确定"}; //创建一个弹窗 JOptionPane.showOptionDialog(Notepad.this, "version:0.1-snapshoot", "关于", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "确定"); } }); menuBar.add(menu1); menuBar.add(menu2); this.setJMenuBar(menuBar); textArea = new JTextArea(); //添加键盘检测事件 textArea.addKeyListener(new keyOption()); // this.getContentPane().add(menuBar, BorderLayout.NORTH); //设置字体 textArea.setFont(new Font("微软雅黑", Font.PLAIN, 18)); scrollPane = new JScrollPane(textArea); //当文本水平溢出时出现滚动条 scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //当文本垂直溢出时出现滚动条 scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); this.getContentPane().add(scrollPane); //居中显示 //this.setLocationRelativeTo(null); //最小化 this.setIconifiable(true); //可关闭 this.setClosable(true); //可改变大小 this.setResizable(true); //销毁窗口 this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setVisible(true); } /** * 打开文件选择和保存对话框 * @param flag */ public void openChooseDialog(String flag) { BufferedReader reader = null; JFileChooser fileChooser = new JFileChooser(); if(dir != null) { //定位上次打开和保存过文件的位置 fileChooser.setCurrentDirectory(new File(dir)); } switch(flag) { case "打开" : //指定它的父窗口 fileChooser.showOpenDialog(Notepad.this); //定义文件选择模式 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); File file = fileChooser.getSelectedFile(); if(file != null) { try { //得到选择文件的路径 dir = file.getAbsolutePath(); fileDir = dir; dir = dir.substring(0, dir.lastIndexOf("\\\\") + 1); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); String str = reader.readLine(); textArea.setText(""); //读取文件内容 while(str != null) { textArea.append(str + "\\n"); str = reader.readLine(); } } catch (Exception ex) { ex.printStackTrace(); } finally { if(reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } break; case "保存" : //打开保存文件的对话框 fileChooser.showSaveDialog(Notepad.this); //得到保存文件后的文件对象 File saveFile = fileChooser.getSelectedFile(); if(saveFile != null) { //得到保存文件的路径 String absolutePath = saveFile.getAbsolutePath(); fileDir = absolutePath; FileOutputStream out = null; BufferedWriter buffOut = null; dir = absolutePath.substring(0, absolutePath.lastIndexOf("\\\\") + 1); //保存文件 try { out = new FileOutputStream(absolutePath); buffOut = new BufferedWriter(new OutputStreamWriter(out)); String text = textArea.getText(); if(text != null) { buffOut.write(text); } buffOut.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(out != null) { out.close(); } if(buffOut != null) { buffOut.close(); } } catch (IOException e1) { e1.printStackTrace(); } } } break; case "打开文件所在目录": if(dir != null) { try { //打开文件目录 Desktop.getDesktop().open(new File(dir)); } catch (IOException e) { e.printStackTrace(); } } break; } } /** * 事件监听类 * @author may * */ private class MyAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JMenuItem item = (JMenuItem) e.getSource(); String flag = item.getText(); switch (flag) { case "打开": openChooseDialog(flag); break; case "保存": openChooseDialog(flag); break; case "打开文件所在目录": openChooseDialog(flag); break; } } } /** * 键盘监听内部类 * @author may * */ private class keyOption extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(17 == keyCode) { ctrlClick = true; } else if(83 == keyCode) { sClick = true; } //判断Ctrl与s键是否按下,按下就开始保存 if(ctrlClick && sClick) { FileOutputStream out = null; BufferedWriter buffOut = null; try { if(fileDir != null) { out = new FileOutputStream(fileDir); buffOut = new BufferedWriter(new OutputStreamWriter(out)); String text = textArea.getText(); if(text != null) { buffOut.write(text); } buffOut.flush(); } else { openChooseDialog("保存"); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if(out != null) { out.close(); } if(buffOut != null) { buffOut.close(); } } catch (IOException e1) { e1.printStackTrace(); } } } } @Override public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if(17 == keyCode) { ctrlClick = false; } else if(83 == keyCode) { sClick = false; } } } }
四、飞机大战简易小游戏
1、效果图
2、代码
(1)主类PanelGame.java
package com.swing.plane; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.swing.util.ImageLoadUtil; /** * 主类 * @author may * */ public class PanelGame extends Frame { private static final long serialVersionUID = 6719627071124599012L; //我方飞机场 private List<Panel> Goodpanels = new ArrayList<Panel>(); //敌军飞机场 private List<Panel> panels = new ArrayList<Panel>(); //公共的子弹工厂 private List<Shell> shells = new ArrayList<Shell>(); //随机 private Random random = new Random(); //战场背景 private static Image image = ImageLoadUtil.loadImage("/lib/bg.jpg"); //缓冲图 private BufferedImage buffImage = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); //爆炸 private List<Explode> explodes = new ArrayList<Explode>(); //杀敌数 public int killEnemyCount = 0; //死亡次数 public int deadCount = 0; public PanelGame() { this.setSize(500,500); this.setLocation(300, 100); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { PanelGame.this.dispose(); } }); //在显示(画窗口前new出来,否则会报空指针异常) //panel = new Panel(100,100, false); this.addKeyListener(new keyCtrl()); this.createGoodPanels(1); this.setVisible(true); new Thread(new MyThread()).start(); } public void createPanels(int num) { for(int i = 0; i < num; i++) { panels.add(new Panel(this, true)); } } public void createGoodPanels(int num) { if(Goodpanels.size() <= 0) { for(int i = 0; i < num; i++) { Goodpanels.add(new Panel(452, 250, false, this)); } } } public List<Explode> getExplodes() { return explodes; } public List<Shell> getShells() { return shells; } public List<Panel> getPanels() { return panels; } public List<Panel> getGoodpanels() { return Goodpanels; } @Override public void paint(Graphics g) { g.drawImage(buffImage, 0, 0, null); } @Override public void以上是关于java图形界面写个小桌面,内置简单小软件的主要内容,如果未能解决你的问题,请参考以下文章