java 实验五截图
JAVA实验-Java语言面向对象编程基础
广州大学学生实验报告
开课学院及实验室:计算机科学与工程实验室
学院
计算机科学与 教育软件学院
年级/专 业/班
姓名
实验课程名称
Java 语言
实验项目名称
Java 语言面向对象编程基础
2014 年 11 月 7 日
学号
成绩 指导 老师
一、实验目的
实验二 数据类型、表达式和输入输出
1. 掌握 java 基本数据类型、变量极其使用。 2. 理解运算符的优先级 3. 掌握运算符与表达式
java实验5图形用户界面设计试验
java实验5图形⽤户界⾯设计试验常⽤布局1)、流布局: FlowLayout 从左到右,⾃上⽽下⽅式在容器中排列,控件的⼤⼩不会随容器⼤⼩变化.容器.setLayout(new FlowLayout(FlowLayout.LEFT));2)、⽹格布局: GridLayout 按照指定⾏数与列数,将容器分成⼤⼩相等的单元格每个单元格放置⼀个控件. 不能将控件放在指定单元格 容器.setLayout(new GridLayout(3,4,10,15));3)、边界布局: BorderLayout 将容器分成东、西、南、北、中五个部分 容器.setLayout(new BorderLayout()); 窗⼝的内容⾯板默认布局就是边界布局。
容器.add(控件,BorderLayout.NORTH);4)、混合布局: 使⽤JPanel,将多个布局组合在⼀起使⽤5)、绝对布局 null: 以坐标定位 容器.setLayout(null); 每个控件在放置在容器之前,必须设置其边界 setBounds(x,y,width,height); btn.setBounds(10,100,30,60);常⽤事件1)、事件源 EventSource:能够触发事件控件如:JButton,JTextField,JFrame,JComboBox,....2)、事件 Event:ActionEvent,KeyEvent,WindowEvent,TextEvent,...3)、事件侦听者Listener(接⼝) ActionListener,WindowListener,...class A implements ActionListener{public void actionPerformed(ActionEvent e){....}}A lis=new A();4)、事件处理函数public void actionPerformed(ActionEvent e){....}事件流程:事件源触发事件-->事件源侦听者接收事件-->⾃动调⽤相应事件处理函数.实践编程1.在应⽤程序窗体中安排1个⽂本框,⼀个标签。
实验五 Java的图形用户界面
实验五Java的图形用户界面
一、实验目的与要求
1.掌握AWT包中常用组件的使用方法。
2.熟悉布局管理器的适用场合,采用布局管理器进行界面的布局。
二、实验内容
1.程序改错
下列程序都有三个错误,按题中的要求,纠正错误并调试程序。
(1)问题描述:下面程序执行时会发生错误,请修改并调试程序。
程序的功能是在屏幕上输出如图5-9所示的图案,图案中每个方格大小是20*20像素。
2、P258实验五程序改错第一题。
3、编程题:设计一个Applet程序sy5_2.java,界面如图5-13所示,其中有两个按钮,当输入完姓名和密码内容后,按“确认”按钮出现图5-14所示界面,当按下“重新输入”按钮,又回到图5-13所示界面。
提示:用两个面板组件,第一个面板放3个标签和两个文本域,第二个面板放两个按钮。
图5-13
图5-14。
攀枝花学院Java实验五 常用类
实验报告附页String s7 = new String("123.678");int n1=Integer.parseInt(s6);//将s6转化成int型数据。
double n2=Double.parseDouble(s7); //将s7转化成double型数据。
double m=n1+n2;System.out.println(m);String s8=String.valueOf(m); //String调用valuOf(int n)方法将m转化为字符串对象position=s8.indexOf(".");String temp=s8.substring(position+1);System.out.println("数字"+m+"有"+temp.length()+"位小数") ;@SuppressWarnings("unused")String s9=new String("ABCDEF");char a[]=s8.toCharArray(); //将s8存放到数组a中。
for(int i=a.length-1;i>=0;i--){System.out.print(" "+a[i]);}}}运行结果:将上面程序按如下要求修改,并运行:(1)程序中的s6改写成String s6=new String(“1a12b”);运行时提示怎样的错误?Exception in thread "main" ng.NumberFormatException: For input string: "1a12b"at ng.NumberFormatException.forInputString(Unknown Source)at ng.Integer.parseInt(Unknown Source)at ng.Integer.parseInt(Unknown Source)at xiti2.xiugai.main(xiugai.java:39)(2)请用数组a的前3个单元创建一个字符串并输出该串。
java截图课程设计
java截图课程设计一、教学目标本课程旨在通过Java编程语言实现截图功能,让学生掌握Java编程的基本语法、面向对象编程思想,以及图形用户界面(GUI)的设计和开发。
具体目标如下:1.知识目标:–掌握Java基本语法和数据结构;–理解面向对象编程的基本概念,如类、对象、封装、继承和多态;–学习Java GUI编程,了解Swing和JavaFX框架;–了解操作系统中截图的基本原理。
2.技能目标:–能够运用Java语言编写简单的程序;–能够使用Java面向对象编程方法解决实际问题;–能够设计和开发图形用户界面,实现截图功能;–能够调试和优化程序,提高代码质量。
3.情感态度价值观目标:–培养学生对编程的兴趣和热情,提高学生解决问题的能力;–培养学生团队合作精神,提高沟通与协作能力;–培养学生勇于探索、不断创新的精神,提高自主学习能力。
二、教学内容本课程的教学内容主要包括以下几个部分:1.Java基本语法和数据结构:字符串、数组、列表、集合、映射、基本数据类型、控制结构、循环、函数等;2.面向对象编程:类、对象、封装、继承、多态、抽象类、接口等;3.Java GUI编程:Swing和JavaFX框架,组件、容器、布局管理器、事件处理等;4.截图功能实现:屏幕分辨率、图像处理、文件存储等;5.编程实践:编写一个简单的截图工具,进行功能测试和优化。
三、教学方法为了提高教学效果,本课程将采用以下教学方法:1.讲授法:讲解Java基本语法、面向对象编程思想和GUI编程基础;2.案例分析法:分析实际截图工具的代码,引导学生掌握编程技巧;3.实验法:让学生动手编写代码,实现截图功能,培养实际操作能力;4.讨论法:分组讨论编程问题,培养学生团队合作和沟通能力。
四、教学资源为了支持本课程的教学,我们将准备以下教学资源:1.教材:《Java编程思想》、《Java GUI编程实战》;2.参考书:《Java核心技术》、《Swing编程指南》;3.多媒体资料:教学PPT、视频教程、在线编程练习平台;4.实验设备:计算机、网络环境、编程软件(如Eclipse、IntelliJIDEA)。
Java实验5
实验5Windows图形程序设计一、实验目的:1、学习使用框架、面板、和简单用户界面UI组件。
2、学习使用布局管理器。
3、学习使用JavaBean组件创建图形用户界面应用程序。
4、理解和学习Windows事件驱动程序。
5、熟悉Java事件委托模式:事件的注册、监听和处理。
6、学习掌握掌握对象数组深复制的方法。
二、实验任务:1、使用Java SDK创建一个Windows图形界面应用程序。
2、实现一个能做算术运算的用户界面。
界面包括标签和文本域Number1、Number2、Result。
Result文本域用于显示Number1和Number2的算术运算的结果。
程序使用四个按钮,它们分别标有Add、Subtract、Multiply和Divide。
程序也创建了完成相同功能运算的菜单。
三、实验步骤:1、首先设置环境变量,保证在任何目录下都可以使用Java SDK编程工具。
如果Java SDK的安装目录为C:\j2sdk1.4.2_09,则在命令提示符状态(从附件中进入)下键入如下命令行设置环境变量:path C:\j2sdk1.4.2_09\bin2、使用Windows写字板编辑应用程序,源代码如下:import java.awt.*;import java.awt.event.*;import javax.swing.*;public class MenuDemo extends JFrame implements ActionListener{// Text fields for Number 1, Number 2, and Resultprivate JTextField jtfNum1, jtfNum2, jtfResult;// Buttons "Add", "Subtract", "Multiply" and "Divide"private JButton jbtAdd, jbtSub, jbtMul, jbtDiv;// Menu items "Add", "Subtract", "Multiply","Divide" and "Close"private JMenuItem jmiAdd, jmiSub, jmiMul, jmiDiv, jmiClose;// Main Methodpublic static void main(String[] args){MenuDemo frame = new MenuDemo();// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);}// Default Constructorpublic MenuDemo(){setTitle("Menu Demo");// Create menu barJMenuBar jmb = new JMenuBar();// Set menu bar to the framesetJMenuBar(jmb);// Add menu "Operation" to menu barJMenu operationMenu = new JMenu("Operation");operationMenu.setMnemonic('O');jmb.add(operationMenu);// Add menu "Exit" in menu barJMenu exitMenu = new JMenu("Exit");exitMenu.setMnemonic('E');jmb.add(exitMenu);// Add menu items with mnemonics to menu "Operation"operationMenu.add(jmiAdd= new JMenuItem("Add", 'A'));operationMenu.add(jmiSub = new JMenuItem("Subtract", 'S'));operationMenu.add(jmiMul = new JMenuItem("Multiply", 'M'));operationMenu.add(jmiDiv = new JMenuItem("Divide", 'D'));exitMenu.add(jmiClose = new JMenuItem("Close", 'C'));// Set keyboard acceleratorsjmiAdd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK));jmiSub.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));jmiMul.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,ActionEvent.CTRL_MASK));jmiDiv.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,ActionEvent.CTRL_MASK));// Panel p1 to hold text fields and labelsJPanel p1 = new JPanel();p1.setLayout(new FlowLayout());p1.add(new JLabel("Number 1"));p1.add(jtfNum1 = new JTextField(3));p1.add(new JLabel("Number 2"));p1.add(jtfNum2 = new JTextField(3));p1.add(new JLabel("Result"));p1.add(jtfResult = new JTextField(4)); jtfResult.setEditable(false);// Panel p2 to hold buttonsJPanel p2 = new JPanel();p2.setLayout(new FlowLayout());p2.add(jbtAdd = new JButton("Add"));p2.add(jbtSub = new JButton("Subtract"));p2.add(jbtMul = new JButton("Multiply"));p2.add(jbtDiv = new JButton("Divide"));// Add panels to the framegetContentPane().setLayout(new BorderLayout()); getContentPane().add(p1, BorderLayout.CENTER); getContentPane().add(p2, BorderLayout.SOUTH); // Register listenersjbtAdd.addActionListener(this);jbtSub.addActionListener(this);jbtMul.addActionListener(this);jbtDiv.addActionListener(this);jmiAdd.addActionListener(this);jmiSub.addActionListener(this);jmiMul.addActionListener(this);jmiDiv.addActionListener(this);jmiClose.addActionListener(this);}// Handle ActionEvent from buttons and menu items public void actionPerformed(ActionEvent e){String actionCommand = e.getActionCommand(); // Handle button eventsif (e.getSource() instanceof JButton){if ("Add".equals(actionCommand))calculate('+');else if ("Subtract".equals(actionCommand))calculate('-');else if ("Multiply".equals(actionCommand))calculate('*');else if ("Divide".equals(actionCommand))calculate('/');}else if (e.getSource() instanceof JMenuItem){// Handle menu item eventsif ("Add".equals(actionCommand))calculate('+');else if ("Subtract".equals(actionCommand))calculate('-');else if ("Multiply".equals(actionCommand))calculate('*');else if ("Divide".equals(actionCommand))calculate('/');else if ("Close".equals(actionCommand))System.exit(0);}}// Calculate and show the result in jtfResultprivate void calculate(char operator){// Obtain Number 1 and Number 2int num1 = (Integer.parseInt(jtfNum1.getText().trim())); int num2 = (Integer.parseInt(jtfNum2.getText().trim())); int result = 0;// Perform selected operationswitch (operator){case '+': result = num1 + num2;break;case '-': result = num1 - num2;break;case '*': result = num1 * num2;break;case '/': result = num1 / num2;}// Set result in jtfResultjtfResult.setText(String.valueOf(result));}}3、把上面编辑的源程序保存成Java源程序文件(扩展名为java),程序文件名分别是MenuDemo .java。
实现屏幕截图的小程序 java课程设计
实现安全工作方针与目标的措施经济与管理学院信息管理与信息系统专业《java实验周》报告(2015/2016学年第一学期)学生姓名:学生班级:学生学号:指导教师:2015年12月25日实现屏幕截图的小程序一、实验题目实现屏幕截图的小程序二、实验要求编程一个应用小程序,能够具有屏幕截图的功能,截图的具体实现有:(1)显示出工作区域,即能够截屏的面积;(2)鼠标可以随意滑动进行截图;(3)将所截取的图片保存在想要保存的位置;(4)程序结束后可以退出整个应用。
三、程序流程图3.1 业务流程图四、技术原理程序的主类是cutScreen,继承自无边框的框架JWindow;cutScreen()是一个定义屏幕尺寸的构造方法;使用方法mousePressed(MouseEvent e)来监听当前鼠标点击的动作;用方法mouseReleased(MouseEvent e)监听鼠标松开时,显示操作窗口;方法mouseDragged(MouseEvent e)监听拖动鼠标;paint(Graphics g)画出指定的工作区域;saveImage()保存图像。
工具栏ToolsWindow类,继承自有边框的框架JFrame;方法init()用来设置布局方式为BorderLayout;run()捕捉屏幕截图。
五、附实验代码import java.awt.*;import java.awt.event.*;import java.awt.image.BufferedImage;import java.awt.image.RescaleOp;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.imageio.ImageIO;import javax.swing.*;import javax.swing.filechooser.FileNameExtensionFilter;import javax.swing.filechooser.FileSystemView;//Jwindow 是一个无边框的框架public class cutScreen extends JWindow {//beginX 开始的横坐标; beginY开始的纵坐标p rivate int beginX, beginY, endX, endY;p rivate BufferedImage image = null;p rivate BufferedImage tempImage = null;p rivate BufferedImage saveImage = null;p rivate ToolsWindow tools = null;//构造方法p ublic cutScreen() throws AWTException, IOException {// 获取屏幕尺寸宽和高int width = Toolkit.getDefaultToolkit().getScreenSize().width;int height = Toolkit.getDefaultToolkit().getScreenSize().height;// 设置窗口大小//(0, 0, width, height)第一个0代表横坐标,第二个代表纵坐标this.setBounds(0, 0, width, height);// 截取屏幕Robot robot = new Robot();//参数Rectangle是代表工作区域image = robot.createScreenCapture(new Rectangle(0, 0, width, height));ImageIO.write(image, "jpg", new File("d:/1"));// 本窗口添加监听(适配器)this.addMouseListener(new MouseAdapter() {@Override//当前鼠标点击动作public void mousePressed(MouseEvent e) {beginX = e.getX();beginY = e.getY();if (tools != null) {tools.setVisible(false);}}@Overridepublic void mouseReleased(MouseEvent e) {// 鼠标松开时,显示操作窗口if (tools == null) {tools = new ToolsWindow(cutScreen.this, e.getX(), e.getY());} else {tools.setLocation(e.getX(), e.getY());}tools.setVisible(true);// 将此窗口置于前端,并可以将其设为焦点 Windowtools.toFront();}});// 监听拖动鼠标this.addMouseMotionListener(new MouseMotionAdapter() {@Overridepublic void mouseDragged(MouseEvent e) {// 鼠标拖动时,记录坐标并重绘窗口endX = e.getX();endY = e.getY();// 临时图像,用于缓冲屏幕区域放置屏幕闪烁Image tempImage2 = createImage(cutScreen.this.getWidth(),cutScreen.this.getHeight());Graphics g = tempImage2.getGraphics();g.drawImage(tempImage, 0, 0, null);int x = Math.min(beginX, endX);int y = Math.min(beginY, endY);int width2 = Math.abs(endX - beginX) + 1;int height2 = Math.abs(endY - beginY) + 1;g.drawRect(x - 1, y - 1, width2 + 1, height2 + 1);// 生成子区域流图片saveImage = image.getSubimage(x, y, width2, height2);//画出图片g.drawImage(saveImage, x, y, null);//绘制当前指定的区域的图片cutScreen.this.getGraphics().drawImage(tempImage2, 0, 0,cutScreen.this);}});}// @Override//画出指定的工作区域p ublic void paint(Graphics g) {//进行逐像素重缩放RescaleOp ro = new RescaleOp(0.8f, 0, null);tempImage = ro.filter(image, null);g.drawImage(tempImage, 0, 0, this);}// 保存图像到文件p ublic void saveImage() throws IOException {JFileChooser jfc = new JFileChooser();jfc.setDialogTitle("保存");// 文件过滤器,用户过滤可选择文件FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG", "jpg");jfc.setFileFilter(filter);// 初始化一个默认文件(此文件会生成到桌面上)// 生成时间SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");String fileName = sdf.format(new Date());File filePath = FileSystemView.getFileSystemView().getHomeDirectory();File defaultFile = new File(filePath + File.separator + fileName + ".jpg");jfc.setSelectedFile(defaultFile);int flag = jfc.showSaveDialog(this);if (flag == JFileChooser.APPROVE_OPTION) {File file = jfc.getSelectedFile();String path = file.getPath();//System.out.println(path);// 检查文件后缀,放置用户忘记输入后缀或者输入不正确的后缀if (!(path.endsWith(".jpg") || path.endsWith(".JPG"))) {path += ".jpg";}// 写入文件ImageIO.write(saveImage, "jpg", new File(path));System.exit(0);}}/** 操作窗口*///ToolsWindow 内部类c lass ToolsWindow extends JFrame {private cutScreen parent;//构造函数(cutScreen,int x, int y)x代表鼠标释放位置的横坐标,public ToolsWindow(cutScreen parent, int x, int y) {this.parent = parent;this.init();this.setLocation(x, y);//让窗口里面的组建确定为最佳大小this.pack();this.setVisible(true);}private void init() {//设置布局方式为BorderLayoutthis.setLayout(new BorderLayout());//工具栏JToolBar toolBar = new JToolBar();// 保存按钮JButton saveButton = new JButton("保存");//匿名内部类添加监听saveButton.addActionListener(new ActionListener() { @Overridepublic void actionPerformed(ActionEvent e) {try {parent.saveImage();} catch (IOException e1) {e1.printStackTrace();}}});toolBar.add(saveButton);// 关闭按钮JButton closeButton = new JButton("关闭");closeButton.addActionListener(new ActionListener() { @Overridepublic void actionPerformed(ActionEvent e) {System.exit(0);}});toolBar.add(closeButton);this.add(toolBar, BorderLayout.CENTER);}}p ublic static void main(String[] args) {EventQueue.invokeLater(new Runnable() {@Overridepublic void run() {try {cutScreen cutScreen = new cutScreen();cutScreen.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}}六、实验结果图6.1 截图图6.2 保存七、个人总结一周的课程设计结束了,刚开始对所要设计的课题完全没有头绪,通过网上查找一些相关资料和同学的帮助,成功设计出能够实现屏幕截图的java程序。
Java截图
源代码:package test;import java.awt.Container;import java.awt.FlowLayout;import java.awt.GraphicsDevice;import java.awt.GraphicsEnvironment;import java.awt.Rectangle;import java.awt.Robot;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.UIManager;import javax.swing.filechooser.FileFilter;import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.AlphaComposite;import java.awt.Graphics2D;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.Toolkit;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.image.BufferedImage;import javax.swing.JTextArea;import javax.swing.JWindow;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Image;import javax.swing.ImageIcon;import javax.swing.JLabel;import javax.swing.JPanel;/**** @author GJ*/class CaptureView extends JWindow implements MouseListener,KeyListener,MouseMotionListener{private static final long serialVersionUID = 1L;private BufferedImage desktopImg;private boolean captured = false ,draging = false , toolPanelAtRight = true;private int x = 0 , y = 0 ,x1 = 0 , y1 = 0 , x2 = 1 , y2 = 1;//坐标原点坐标,选区左上角和右下角坐标private int point_x , point_y;//鼠标点坐标private Color point_color;//鼠标点颜色private DesktopCapture window;//所属截图工具主窗体private ImagePanel toolPanel;//提示整框private final int TOOLPANEL_WIDTH = 200,TOOLPANEL_HEIGHT = 300 , HALF_PICK_IMG = 40;private JTextArea infoArea ;//提示区private ToolImagePanel pickImgPanel;//放大镜CaptureView(DesktopCapture window , BufferedImage img){super(window);this.window = window;this.desktopImg = img;setSize(Toolkit.getDefaultToolkit().getScreenSize());init();setVisible(true);setAlwaysOnTop(true);this.requestFocus();}void init(){this.setContentPane(new BackGroundPanel(desktopImg));setLayout(null);toolPanel = new ImagePanel();toolPanel.setLayout(new BorderLayout());pickImgPanel = new ToolImagePanel();infoArea = new JTextArea();infoArea.setOpaque(false);infoArea.setEditable(false);infoArea.setForeground(Color.BLUE);infoArea.setFont(new Font("楷体" , Font.PLAIN ,11 ));infoArea.setText("");toolPanel.add(pickImgPanel,BorderLayout.CENTER);toolPanel.add(infoArea,BorderLayout.SOUTH);toolPanel.setLocation(getWidth()-TOOLPANEL_WIDTH, 0);toolPanel.setSize(TOOLPANEL_WIDTH,TOOLPANEL_HEIGHT);this.getLayeredPane().add(toolPanel,300);addKeyListener(this);addMouseListener(this);addMouseMotionListener(this);}//桌面屏幕更新public void refreshBackGround(BufferedImage img){this.desktopImg = img;this.setContentPane(new BackGroundPanel(desktopImg));setVisible(true);setAlwaysOnTop(true);this.requestFocus();}public void paint(Graphics g){super.paint(g);g.setColor(Color.BLACK);if(captured == true){if(draging){//截图辅助十字线g.drawLine(point_x, 0, point_x, getHeight());g.drawLine(0, point_y, getWidth(), point_y);}confirmArea();//确定截图选区的左上角坐标(x1,y1)和右下角坐标(x2,y2)if(x1<x2 && y1<y2)g.drawImage(desktopImg.getSubimage(x1, y1, Math.abs(x2-x1), Math.abs(y2-y1)), x1, y1, null);g.drawRect(x1,y1,Math.abs(x2-x1),Math.abs(y2-y1));}else{g.drawLine(point_x, 0, point_x, getHeight());g.drawLine(0, point_y, getWidth(), point_y);}repaintToolPanel();}//确定提示框位置并重画public void repaintToolPanel(){if(toolPanelAtRight == true){if( point_x > (getWidth()- TOOLPANEL_WIDTH -100) && point_y < (TOOLPANEL_HEIGHT + 100)){toolPanel.setLocation(0, 0);toolPanelAtRight = false;}}else{if( point_x < (TOOLPANEL_WIDTH + 100) && point_y < (TOOLPANEL_HEIGHT + 100)){toolPanel.setLocation(getWidth()- TOOLPANEL_WIDTH, 0);toolPanelAtRight = true;}}//计算point的状态point_color = new Color(desktopImg.getRGB(point_x, point_y));refreshInfoText(); //更新提示框内容}//提示框状态信息的刷新public void refreshInfoText(){//文本信息String text = new String(" 1.单击截图------>进入截图\n 2.双击右键------>退出截图\n 3.双击左键------>保存截图\n 4.单击右键------>重新截图");String infoString;int captureWidth,captureHeight;if(captured == true){captureWidth = x2 - x;captureHeight = y2 - y;}else{captureWidth = 0;captureHeight = 0;}infoString = " X,Y : " + point_x + "," + point_y + " W*H : " + captureWidth + "*" + captureHeight +"\n R B G:(" + point_color.getRed() + "," + point_color.getGreen() + "," + point_color.getBlue() + ")\n" + text ;infoArea.setText(infoString);//放大镜信息int pick_x1 , pick_y1 , pick_x2 , pick_y2 , pickImg_x , pickImg_y ;if(point_x - HALF_PICK_IMG < 0){//获得放大图片的捡取左上角和右下角坐标,以及在放大镜中的左上角位置坐标pick_x1 = 0 ;pick_x2 = point_x + HALF_PICK_IMG;pickImg_x = HALF_PICK_IMG - point_x;}else if( point_x + HALF_PICK_IMG > this.getWidth()){pick_x1 = point_x - HALF_PICK_IMG;pick_x2 = this.getWidth();pickImg_x = 0;}else{pick_x1 = point_x - HALF_PICK_IMG;pick_x2 = point_x + HALF_PICK_IMG;pickImg_x = 0;}if(point_y - HALF_PICK_IMG <0){pick_y1 = 0 ;pick_y2 = point_y + HALF_PICK_IMG;pickImg_y = HALF_PICK_IMG - point_y;}else if(point_y + HALF_PICK_IMG > this.getHeight()){pick_y1 = point_y - HALF_PICK_IMG ;pick_y2 = this.getHeight();pickImg_y = 0;}else{pick_y1 = point_y - HALF_PICK_IMG ;pick_y2 = point_y + HALF_PICK_IMG;pickImg_y = 0;}BufferedImage pickImg = newBufferedImage(HALF_PICK_IMG*2,HALF_PICK_IMG*2,BufferedImage.TYPE_INT_RGB);Graphics pickGraphics = pickImg.getGraphics();pickGraphics.drawImage(desktopImg.getSubimage(pick_x1, pick_y1, pick_x2 - pick_x1, pick_y2 - pick_y1), pickImg_x, pickImg_y, Color.black, null);pickImgPanel.refreshImg(pickImg.getScaledInstance(TOOLPANEL_WIDTH, TOOLPANEL_WIDTH, BufferedImage.SCALE_AREA_AVERAGING));toolPanel.validate();}//确定区域的左上点和右下角坐标public void confirmArea(){int temp;//以x,y为截图选区左上角坐标初值,计算左上角x1,y1和右下角x2,y2的坐标x1 = x;y1 = y;if(x2 < x1){//2,3if(y2 < y1){ //2temp = x1;x1 = x2;x2 = temp;temp = y1;y1 = y2;y2 = temp;}else{//4temp = x1;x1 = x2;x2 = temp;}}else{ //1,4if(y2 < y1){ //1temp = y1;y1 = y2;y2 = temp;}}}public void exit(){x = 0;y = 0;x1 = 0;y1 = 0;x2 = 1;y2 = 1;point_x = 0;point_y = 0;captured = false;draging = false;toolPanel.setLocation(getWidth()-TOOLPANEL_WIDTH,0);toolPanelAtRight = true;this.setVisible(false);//this.dispose();}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub//双击左键,确定选择图像选区,保存截图if(e.getButton() == MouseEvent.BUTTON1){if(e.getClickCount() == 2){this.setVisible(false);window.toFront();window.saveCapture(x1, y1, x2, y2);if(!window.iconed)window.setVisible(true);exit();}}else if(e.getClickCount() == 2){if(!window.iconed){window.setVisible(true);window.toFront();}exit();}}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) { // TODO Auto-generated method stub//左键在未选区完毕时单击,确定选区起点if(e.getButton() == MouseEvent.BUTTON1){ if(captured == false){point_x = e.getX();point_y = e.getY();x = point_x;//选区起点坐标y = point_y;draging = true;captured = true;}}}@Overridepublic void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub//左键释放,确定截图选区//右键释放,重新选区if(e.getButton() == MouseEvent.BUTTON1){if(draging == true){point_x = e.getX();point_y = e.getY();x2 = point_x;y2 = point_y;repaint();draging = false;}}else{draging = false;captured = false;point_x = e.getX();point_y = e.getY();repaint();}}@Overridepublic void mouseDragged(MouseEvent e) { // TODO Auto-generated method stub//拖拉截图时画矩形if(draging == true){point_x = e.getX();point_y = e.getY();x2 = point_x;y2 = point_y;repaint();}}@Overridepublic void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub//未决定截图时,画交叉线if(!captured){point_x = e.getX();point_y = e.getY();repaint();}}@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stubif(e.getKeyCode() == KeyEvent.VK_CANCEL){ this.setVisible(false);this.dispose();}}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stubSystem.out.println("aaa");if(e.getKeyCode() == KeyEvent.VK_A){this.setVisible(false);this.dispose();}}@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stubif(e.getKeyCode() == KeyEvent.VK_ESCAPE){this.setVisible(false);this.dispose();}}}class BackGroundPanel extends ImagePanel{private static final long serialVersionUID = 1L;int width , height ;public BackGroundPanel(){super();}public BackGroundPanel(String imgUrl){super(imgUrl);}public BackGroundPanel(Image img){super(img);}public void refreshImg(Image img){this.img = img;width = getWidth();height = getHeight();}public void paintComponent(Graphics g){super.paintComponent(g);Graphics2D g2 = (Graphics2D)g;g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));g2.setColor(Color.BLACK);g2.fillRect(0, 0, img.getWidth(null), img.getHeight(null));}}class ImagePanel extends JPanel{private static final long serialVersionUID = 1L;protected Image img;public ImagePanel(){super();}public ImagePanel(String imgUrl){super();img = new ImageIcon(this.getClass().getClassLoader().getResource(imgUrl)).getImage();Dimension size = new Dimension(img.getWidth(null),img.getHeight(null));setSize(size);setPreferredSize(size);setMinimumSize(size);setMaximumSize(size);setOpaque(false);setLayout(null);}public ImagePanel(Image img){super();this.img = img;Dimension size = new Dimension(img.getWidth(null),img.getHeight(null));setSize(size);setPreferredSize(size);setMinimumSize(size);setMaximumSize(size);setOpaque(false);setLayout(null);}public void refreshImg(Image img){this.img = img;}public void paintComponent(Graphics g ){super.paintComponent(g);g.drawImage(img,0,0,null);}}class ToolImagePanel extends ImagePanel{private static final long serialVersionUID = 1L;int width , height ;int QUANTITY = 1;//实际为奇数,向上取奇public ToolImagePanel(){super();}public ToolImagePanel(String imgUrl){super(imgUrl);}public ToolImagePanel(Image img){super(img);}public void refreshImg(Image img){this.img = img;width = getWidth();height = getHeight();}public void paintComponent(Graphics g){super.paintComponent(g);g.setColor(Color.RED);g.drawLine(width/2 , 0, width/2 , height);g.drawLine(0, height/2 , width, height/2);for(int i=1; i < QUANTITY/2 + 1 ; i++){g.drawLine(width/2 - i, 0, width/2 - i, height);g.drawLine(0, height/2 - i , width, height/2 - i);}for(int i=1; i < QUANTITY/2 + 1 ; i++){g.drawLine(width/2 + i, 0, width/2 + i, height);g.drawLine(0, height/2 + i , width, height/2 + i);}}}class ImageLabel extends JLabel{private static final long serialVersionUID = 1L;public ImageLabel(String imgURL){ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(imgURL));setSize(icon.getImage().getWidth(null),icon.getImage().getHeight(null));setIcon(icon);setIconTextGap(0);setBorder(null);setText(null);setOpaque(false);}public ImageLabel(ImageIcon icon){setSize(icon.getImage().getWidth(null),icon.getImage().getHeight(null));setIcon(icon);setIconTextGap(0);setBorder(null);setText(null);setOpaque(false);}}public class DesktopCapture extends JFrame implements ActionListener{/*** 修改:将放大镜提示框移至左上角和右上角*/private static final long serialVersionUID = 1L;JButton confirm;BufferedImage desktopImg; //具有可访问图像数据缓冲区的ImageCaptureView view;boolean iconed = false;public DesktopCapture(){super("截图");init();pack();setSize(250,150);setLocation(500,300);setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);setResizable(false);setVisible(true);}void init(){Container con = getContentPane();con.setLayout(new BorderLayout());confirm = new JButton("截图");confirm.addActionListener(this);JPanel jp = new JPanel();jp.setLayout(new FlowLayout());jp.setOpaque(false);jp.add(confirm);JTextArea jta = new JTextArea();jta.setOpaque(false);jta.setEditable(false);jta.setForeground(Color.BLACK);jta.setFont(new Font("楷体" , Font.PLAIN ,11 ));jta.setText("\t1.单击截图------->进入截图\n\t2.双击右键------->退出截图\n\t3.双击左键------->保存截图\n\t4.单击右键------->重新截图");con.add(jp,BorderLayout.CENTER);con.add(jta,BorderLayout.SOUTH);}//获得屏幕图片public void captureDesktop() throws Exception{Dimension d = Toolkit.getDefaultToolkit().getScreenSize();Rectangle rect = new Rectangle(d);desktopImg = new BufferedImage((int)d.getWidth(),(int)d.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();GraphicsDevice device = environment.getDefaultScreenDevice();Robot robot = new Robot(device);desktopImg = robot.createScreenCapture(rect);}//截图public void capture(){this.setVisible(false);try {Thread.sleep(200);captureDesktop();} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}if(view == null){view = new CaptureView(this, desktopImg);}else{view.refreshBackGround(desktopImg);}}//保存截图public void saveCapture(int x1 , int y1 ,int x2 , int y2){JFileChooser chooser = new JFileChooser();chooser.setFileFilter(new FileNameExtensionFilter("*.gif", "gif"));chooser.setFileFilter(new FileNameExtensionFilter("*.bmp", "bmp"));chooser.setFileFilter(new FileNameExtensionFilter("*.png", "png"));chooser.setFileFilter(new FileNameExtensionFilter("*.jpg", "jpg"));chooser.setSelectedFile(new File(chooser.getCurrentDirectory(),"截图"));int state = chooser.showSaveDialog(this);if(state == JFileChooser.APPROVE_OPTION){File file = chooser.getSelectedFile();FileFilter filter = chooser.getFileFilter();String descrition = filter.getDescription();String endWith = descrition.substring(2);captureToFile(desktopImg.getSubimage(x1, y1, Math.abs(x2-x1), Math.abs(y2-y1)),endWith,new File(file.getAbsoluteFile() +"."+ endWith));}}//截图输出到文件public void captureToFile(BufferedImage img , String endWith , File file){if(!file.exists()){file.mkdir();}try {ImageIO.write(img, endWith, file);} catch (IOException e) {// TODO Auto-generated catch blockJOptionPane.showMessageDialog(null, "截图保存出错...");e.printStackTrace();}}public static void main(String[] args) {// TODO Auto-generated method stubtry {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());DesktopCapture desk = new DesktopCapture();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void actionPerformed(ActionEvent e) { // TODO Auto-generated method stubif(e.getActionCommand().equals("截图")){capture();}}}。
Java实验
实验一熟悉Java开发环境(验证性2学时)一、实验目的与要求:1 掌握Java Application程序的开发过程并编写第一个Java Application程序*2 掌握Java Applet程序的开发过程并编写第一个Java Applet程序。
*3 练习简单的HTML文件配合Java Applet使用。
4 熟悉jdk的使用二、实验内容:1 编写一个Java Application程序,在屏幕上显示”This is my first java program!”.*2 编写第一个Java Applet 程序,在屏幕上显示”This is my first Java Applet!”三、实验步骤:1、jdk的使用jdk开发工具包可以从网站下载,jdk不是集成编译环境,须手动运用命令行程序进行编译和解释执行1)编辑.java文件可以在记事本或其他纯文本编辑器中编辑,保存时把文件扩展名定为.java即可,当然要注意文件名命名的要求2)编译生成.class文件进入dos系统进行编译(如图1.1所示),格式如javac MyFirstApplication.java,要注意图1.1进入命令行看javac.exe的路径并且MyFirstApplication.java文件路径和javac.exe路径一样。
编译成功后就能在浏览器中看见多了一个MyFirsApplication.class或更多的.class文件。
如图1.2所示图1.2使用jdk编译MyFirstApplication.java文件3)解释执行Application程序:同样是在dos系统下解释执行,格式如java MyFirstApplication,注意.class后缀别加,如图1.3所示。
图1.3解释执行MyFirstApplication.class程序* applet程序进入dos系统进行编译,格式如javac MyFirstApplet.java,要注意看javac.exe的路径并且MyFirstApplet.java文件路径和javac.exe路径一样。
华南农业大学农科Java上机实验
实验1 创建、编译与运行Java程序17268 计算两个整数得与从键盘输入两个整数,计算并输出两个整数得与。
import java、util、Scanner;public class Main {public static void main(String[] args) {int a,b;Scanner input = new Scanner(System、in);a=input、nextInt();b=input、nextInt();int c = a + b;System、out、println(c);}}17269 输出两个整数中得较大得值从键盘输入两个整数,判断并输出两个整数中较大得值。
import java、util、Scanner;public class Main {public static void main(String[] args) {int a,b;Scanner input = new Scanner(System、in);a=input、nextInt();b=input、nextInt();if(a>b)System、out、println(a);elseSystem、out、println(b);}}实验2 基本数据类型、运算与表达式18135 在显示屏上显示指定字符要求编写一个程序,在显示屏上显示如下内容。
注:类名必须为Main(大写M) C:\ABC、TXT is "file"public class Main {public static void main(String[] args) {System、out、print("C:\\ABC、TXT is \"file\"");} }18136 计算圆得面积由键盘输入圆得半径,计算并输出圆得面积,结果保留2位小数。
注:类名必须为Main(大写M)import java、util、Scanner;import java、text、DecimalFormat;public class Main {public static void main(String[] args) {double a,b,c;Scanner input = new Scanner(System、in);a = input、nextDouble();b = 3、14159;c = a*a*b;System、out、println(new DecimalFormat("#、##")、format(c));}}18138 输出三位整数得各位数字从键盘输入一个3位得整数,要求按照:个位、十位与百位得顺序输出三个数字。
java实现截图
* 《p》Company: 《/p》
* @author
* @version 1.0.0
*/
public class ImageChangeSize
{
public static void main ( String [] args )
throws InterruptedException
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
quality = Math.max(0, Math.min(quality, 100));
ImageIO.write(image, “jpg”, new File(path));
}
catch ( Exception e )
{
System.out.println(“Failed to snatch screen 。.. ”);
e.printStackTrace();
}
else
{
thumbWidth = (int) ( thumbHeight * imageRatio );
}
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);
double imageRatio = (double) imageWidth / (double) imageHeight;
实验五
(2)运行结果如图5.5所示。
图5.5
3.This、super和super()的使用
(1)程序功能:说明this、super和super()的用法。程序首先定义Point(点)类,然后创建点的子类Line(线)。最后通过LX3_4类输出线段的长度。
(2)使用this、super和super()的程序文件LX3_4.java,源代码如下图5.6所示。
多态是一种编程技巧它增加论了程序的可扩展性
2.接口有什么作用?如何实现系统接口。
接口的作用就是把使用接口的人和实现接口的人分开,实现接口的人不必要关心谁去使用,而使用接口的人也不用关心谁实现的接口,由接口将他们联系在一起。接口的用处在于整个程序段中相同类型的类有个统一的规范。
3.如何创建一个自定义接口?如何在一个类中实现这个接口?
图5.6
(3)编译并运行程序,结果如图5.7所示。
图5.7
二、类的多态性练习
1.方法的重载
方法的重载是指对同名方法的不同使用方式。
(1)程序功能:对不同的数进行排序输出。在IntSort类中定义3个同名的方法sort,
(1)编写构造方法RunDemo的重载程序文件LX3_12,源代码如下。
(2)编译并运行程序,结果如图5.4所示。
【思考题】
1.说明类的继承和多态用的一种形式,实现这种形式的方法是从现有的类建立新类,新类继承了现有类的方法和属性,同时新类又可以定义自己的方法和属性。软件复用缩自短了开发时间。继承的魅力在于能够添加基类没有的特点从而对基类进行改进。
子类继承后可以重写,也可以不重写,看需要决定。如果重写的话在实例中调用的是新写的方法,如果不重写的话在实例中调用的是父类的方法。
创建接口:public interface myFirstInterface(){
java实现屏幕截图功能毕业设计与实现
java实现屏幕截图功能摘要捕捉图像方式灵活,主要可以捕捉整个屏幕、活动窗口、选定区域、固定区域、选定控件、选定菜单等,图像输出方式多样,主要包括文件、剪贴板、画图。
软件具有捕捉光标、设置捕捉前延时、显示屏幕放大镜、自定义捕捉热键、图像文件自动按时间或模板命名。
捕捉到的图像能够以保存图像文件、复制到剪贴板、等多种方式输出。
图像文件自动命名功能,能够对捕捉到的图片进行自动命名保存,可以设置根据时间或文件名模板自动保存。
捕捉图像预览功能,在捕捉完成后,显示预览窗口。
图像保存目录及格式设置功能,可以为捕捉的图像规定默认保存位置及图像格式,图像格式包括BMP、GIF、JPG、PNG、TIF等。
捕捉层叠菜单功能,在选定菜单捕捉时可以设置是否捕捉层叠(级联)菜单。
可以截取多个图片,分多层界面显示已截图片。
关键词:截图;保存;复制到剪切板Java implementation screenshot functionAbstractCapture the image flexibly, and the main can capture the whole screen, the active window, the selected region, fixed area, the selected control, select menu, image output way diverse, mainly including documents, clipboard, drawing.Software is to capture the cursor, set the delay before capture, display screen magnifier, custom capture hotkey, automatic image file on time or template name.Capture the image to save the image file, copied to the clipboard, a variety of ways, such as the output. Image file named function automatically, to be able to capture the image automatically named save, can be set according to time or template automatically saved in the file name.Capture the image preview function, after completion of the capture, display the preview window.Image save directory and format setting function, can be preserved to capture images of the provisions of the default location and image format, image format, including BMP, GIF, JPG, PNG, TIF, etc.When capture to capture the cascading menu function, the selected menu you can set whether to capture the cascading menu (cascade).Can capture multiple images, multi-layer interface has sectional image display.Key words:capture; Save; Copied to the clipboard目录摘要 (i)Abstract (ii)目录 (1)1 绪论 (1)1.1 选题背景 (1)1.2 课题研究内容 (1)2 开发平台及技术 (3)2.1 Eclipse (3)2.2 Java (3)2.2.1 历史起源 (4)2.2.2 基本组成 (4)2.2.3 主要特性 (4)2.2.4 基本术语 (5)3 可行性分析及开发环境的选择 (7)3.1 可行性分析 (7)3.1.1 技术可行性分析 (7)3.1.2 经济可行性分析 (7)3.1.3 法律可行性分析 (7)3.1.4 开发人员与进程可行性分析 (7)3.1.5 结论意见 (8)3.2 运行环境的选择 (8)3.3 开发工具的选择 (8)4 系统需求分析 (9)4.1 性能需求 (9)4.2 E-R图设计 (9)5 系统设计 (10)5.1 本系统的设计目标 (10)5.2 系统功能整体设计 (10)6 系统设计实现 (11)6.1 系统主界面实现 (11)6.2 系统截图实现 (12)6.2.1 图片的保存路径 (20)6.2.2 图片的保存格式 (22)7 系统测试与性能分析 (25)7.1 软件测试 (25)7.1.1 软件测试概述 (25)7.1.2 系统整体测试步骤 (25)7.2 截图软件系统测试 (26)7.2.1 保存选项测试 (26)7.2.2 复制到粘贴板选项测试 (26)7.3 测试结果评价 (26)总结 (27)参考文献 (28)致谢 (29)外文引用 (30)中文翻译 (37)1 绪论截图是由电脑截取的显示在屏幕或其他显示设备上的可视图像。
Java实验报告(w5-w6)
福建师大福清分校计算机实验报告(W5,W6)院/系:数学与计算机科学系课程名称:Java面向对象程序设计日期:测试报告结果分析注意非法字符2class Letter{char start = 'A';void printLetter(){for(int i = 0;i<25;i++){char c = '0';c = (char)(i+start);System.out.printf("%c ",c);if(i%7==0&&i!=0) System.out.printf("\n");}}}class Letter2{public static void main(String[] args){Letter p = new Letter();p.printLetter();}}3.import java.util.*;public class DengCha3{public static void main(String[] args){DengCha shulie = new DengCha();shulie.setStart(6);shulie.setD(7);System.out.printf("首项为6,公差为7的等差数列的前5项和为%d",shulie.getSum(5));}}class DengCha{int s;int d;int sum ;DengCha(){}void setStart(int s){this.s = s;}void setD(int d){this.d = d;}int getSum(int n){sum = n*s+n*(n-1)*d/2;return sum;}}4.import ng.Math;class SquareEquation{double a;double b;static double c;double x1,x2;SquareEquation(double a,double b,double c){this.a = a;this.b = b;SquareEquation.c = c;}void getRoots(){double temp = b*b-4*a*c;if(temp<0) System.out.println("方程无根\n");else if(temp != 0){x1 = (-b+Math.sqrt(temp))/(2.0*a);x2 = (-b-Math.sqrt(temp))/(2.0*a);System.out.printf("方程有两个不同的实根其中x1=%.2f,x2=%.2f\n",x1,x2);}else{x1 = -b/(2.0*a);System.out.printf("方程有两个相同的实根,值为%f\n",x1);}}}public class SquareEquation4{public static void main(String[] args){SquareEquation yi = new SquareEquation(1,2,3);System.out.println("方程式一为x*x+2x+3=0");yi.getRoots();SquareEquation er = new SquareEquation(4,10,1);System.out.println("方程式二为4x^2+10x=0");er.getRoots();System.out.printf("方程一的常数项为%.2f,方程二的常数项为%.2f",yi.c,er.c);}}5.public class Shiyan_5{public static void main(String args[]){Complex x = new Complex(4.0,2.1);Complex y = new Complex(2.5,5.0);Complex t1 = new Complex( );Complex t2 = new Complex( );t1 =x.add(y);t2 =x.sub(y);t1.print( );t2.print( );}}class Complex{double a;double b;Complex(){}Complex(double a1,double b1){a =a1;b=b1;} Complex add(Complex x){double a1,a2;a1 = a + x.a;a2 = b + x.b;return new Complex(a1,a2);}Complex sub(Complex x){double a1,a2;a1 = a - x.a;a2 = b - x.b;return new Complex(a1,a2);}void print(){System.out.printf("实部%.2f,虚部%.2f\n",a,b);}}说明:系统实施:(程序流程图、重要过程说明、参数设置、变量的说明等)测试报告:(调试输入数据、结果数据或状态。
Java编程实现屏幕截图(截屏)代码总结(转载)
Java编程实现屏幕截图(截屏)代码总结(转载)转载⾃:⽅法⼀:import java.awt.Desktop;import java.awt.Dimension;import java.awt.Rectangle;import java.awt.Robot;import java.awt.Toolkit;import java.awt.image.BufferedImage;import java.io.File;import javax.imageio.ImageIO;public class CaptureScreen {public static void captureScreen(String fileName, String folder) throws Exception {Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();Rectangle screenRectangle = new Rectangle(screenSize);Robot robot = new Robot();BufferedImage image = robot.createScreenCapture(screenRectangle);//保存路径File screenFile = new File(fileName);if (!screenFile.exists()) {screenFile.mkdir();}File f = new File(screenFile, folder);ImageIO.write(image, "png", f);//⾃动打开if (Desktop.isDesktopSupported()&& Desktop.getDesktop().isSupported(Desktop.Action.OPEN))Desktop.getDesktop().open(f);}public static void main(String[] args) {try {captureScreen("e:\\你好","11.png");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}⽅法⼆:package com.qiu.util;import java.io.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.awt.image.*;import javax.imageio.*;/*** ⼀个简单的屏幕抓图***/public class ScreenCapture {// test mainpublic static void main(String[] args) throws Exception {String userdir = System.getProperty("user.dir");File tempFile = new File("d:", "temp.png");ScreenCapture capture = ScreenCapture.getInstance();capture.captureImage();JFrame frame = new JFrame();JPanel panel = new JPanel();panel.setLayout(new BorderLayout());JLabel imagebox = new JLabel();panel.add(BorderLayout.CENTER, imagebox);imagebox.setIcon(capture.getPickedIcon());capture.saveToFile(tempFile);capture.captureImage();imagebox.setIcon(capture.getPickedIcon());frame.setContentPane(panel);frame.setSize(400, 300);frame.show();System.out.println("Over");}private ScreenCapture() {try {robot = new Robot();} catch (AWTException e) {System.err.println("Internal Error: " + e);e.printStackTrace();}JPanel cp = (JPanel) dialog.getContentPane();cp.setLayout(new BorderLayout());labFullScreenImage.addMouseListener(new MouseAdapter() {public void mouseReleased(MouseEvent evn) {isFirstPoint = true;pickedImage = fullScreenImage.getSubimage(recX, recY, recW,recH);dialog.setVisible(false);}});labFullScreenImage.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent evn) {if (isFirstPoint) {x1 = evn.getX();y1 = evn.getY();isFirstPoint = false;} else {x2 = evn.getX();y2 = evn.getY();int maxX = Math.max(x1, x2);int maxY = Math.max(y1, y2);int minX = Math.min(x1, x2);int minY = Math.min(y1, y2);recX = minX;recY = minY;recW = maxX - minX;recH = maxY - minY;labFullScreenImage.drawRectangle(recX, recY, recW, recH);}}public void mouseMoved(MouseEvent e) {labFullScreenImage.drawCross(e.getX(), e.getY());}});cp.add(BorderLayout.CENTER, labFullScreenImage);dialog.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); dialog.setAlwaysOnTop(true);dialog.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize());dialog.setUndecorated(true);dialog.setSize(dialog.getMaximumSize());dialog.setModal(true);}// Singleton Patternpublic static ScreenCapture getInstance() {return defaultCapturer;}/** 捕捉全屏慕 */public Icon captureFullScreen() {fullScreenImage = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));ImageIcon icon = new ImageIcon(fullScreenImage);return icon;}/** 捕捉屏幕的⼀个矫形区域 */public void captureImage() {fullScreenImage = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));ImageIcon icon = new ImageIcon(fullScreenImage);labFullScreenImage.setIcon(icon);dialog.setVisible(true);}/** 得到捕捉后的BufferedImage */public BufferedImage getPickedImage() {return pickedImage;}/** 得到捕捉后的Icon */public ImageIcon getPickedIcon() {return new ImageIcon(getPickedImage());}/*** 储存为⼀个⽂件,为PNG格式** @deprecated replaced by saveAsPNG(File file)**/@Deprecatedpublic void saveToFile(File file) throws IOException {ImageIO.write(getPickedImage(), defaultImageFormater, file);}/** 储存为⼀个⽂件,为PNG格式 */public void saveAsPNG(File file) throws IOException {ImageIO.write(getPickedImage(), "png", file);}/** 储存为⼀个JPEG格式图像⽂件 */public void saveAsJPEG(File file) throws IOException {ImageIO.write(getPickedImage(), "JPEG", file);}/** 写⼊⼀个OutputStream */public void write(OutputStream out) throws IOException {ImageIO.write(getPickedImage(), defaultImageFormater, out);}// singleton design patternprivate static ScreenCapture defaultCapturer = new ScreenCapture();private int x1, y1, x2, y2;private int recX, recY, recH, recW; // 截取的图像private boolean isFirstPoint = true;private BackgroundImage labFullScreenImage = new BackgroundImage();private Robot robot;private BufferedImage fullScreenImage;private BufferedImage pickedImage;private String defaultImageFormater = "png";private JDialog dialog = new JDialog();}/** 显⽰图⽚的Label */class BackgroundImage extends JLabel {public void paintComponent(Graphics g) {super.paintComponent(g);g.drawRect(x, y, w, h);String area = Integer.toString(w) + " * " + Integer.toString(h);g.drawString(area, x + (int) w / 2 - 15, y + (int) h / 2);g.drawLine(lineX, 0, lineX, getHeight());g.drawLine(0, lineY, getWidth(), lineY);}public void drawRectangle(int x, int y, int width, int height) {this.x = x;this.y = y;h = height;w = width;repaint();}public void drawCross(int x, int y) {lineX = x;lineY = y;repaint();}int lineX, lineY;int x, y, h, w;⽅法三:因为有最⼩化到系统托盘,还是需要⼀张名为bg.gif作为托盘图标,图⽚应放在同级⽬录下,否则会空指针异常。
java截取图片示例
java截取图⽚⽰例复制代码代码如下:/****/package com.b510;import java.awt.Rectangle;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Date;import java.util.Iterator;import javax.imageio.ImageIO;import javax.imageio.ImageReadParam;import javax.imageio.ImageReader;import javax.imageio.stream.ImageInputStream;/*** @date 2012-11-26* @author xhw**/public class ImageCut {/*** 源图⽚路径名称如:c:\1.jpg*/private String srcpath = "e:/poool.jpg";/*** 剪切图⽚存放路径名称.如:c:\2.jpg*/private String subpath = "e:/pool_end";/*** jpg图⽚格式*/private static final String IMAGE_FORM_OF_JPG = "jpg";/*** png图⽚格式*/private static final String IMAGE_FORM_OF_PNG = "png";/*** 剪切点x坐标*/private int x;/*** 剪切点y坐标*/private int y;/*** 剪切点宽度*/private int width;/*** 剪切点⾼度*/private int height;public ImageCut() {}public ImageCut(int x, int y, int width, int height) {this.x = x;this.y = y;this.width = width;this.height = height;}public static void main(String[] args) throws Exception {ImageCut imageCut = new ImageCut(134, 0, 366, 366);imageCut.cut(imageCut.getSrcpath(), imageCut.getSubpath());}/*** 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。
java大作业附运行截图及代码
《Java程序设计》上机报告学院通信工程学院专业通信工程学生姓名梁芷馨学生学号150****0045第一次上机报告必做题题目1:课本P53 12;题目1的运行结果截图:题目1的源程序:package ch1;public class Car {public static void main(String args[]){Carinf obj1=new Carinf("本田","黑色",1500,5);System.out.println(obj1.show());}}class Carinf{String name;String color;double weight;int passenger;Carinf(String s,String b,double d,int i) { name=s;color=b;weight=d;passenger=i;}String show(){return"品牌: "+name+" 颜色: "+color+" 自重:"+weight+"公斤搭载的人数: "+passenger;}}题目2:课本P53 15;题目2的运行结果截图:题目2的源程序:package ch1;public class Reverse {public static void main(String args[]){System.out.println("逆序输出");for(int i=args[0].length()-1;i>=0;i--){System.out.println(args[0].charAt(i));}}}选作题题目3:参考下列要求,修改Snowman.java:(1)在图片的右上角添加文本;(2)给雪人增加更多的装饰;(3)给画面添加更多内容,比如云朵,圣诞树,房屋等。
Java实验报告电子稿
(理工类)课程名称: JAVA程序设计专业班级:学生学号:学生姓名:所属院部:指导教师:20 15 ——20 16 学年第 2 学期金陵科技学院教务处制实验项目名称:JAVA编程基础实验学时: 4同组学生姓名:————实验地点: 1514 实验日期: 2016.4.11 实验成绩:批改教师:批改时间:一、实验目的和要求(1)熟练掌握JDK1.7及Eclipse Kepler Service Release 1(下简称Eclipse)编写调试Java应用程序及Java小程序的方法;(2)熟练掌握Java应用程序的结构;(3)了解Java语言的特点,基本语句、运算符及表达式的使用方法;(4)熟练掌握常见数据类型的使用;(5)熟练掌握if-else、switch、while、do-while、for、continue、break、return 语句的使用方法;(6)熟练掌握数组和字符串的使用;(7)调试程序要记录调试过程中出现的问题及解决办法;(8)编写程序要规范、正确,上机调试过程和结果要有记录,不断积累编程及调试经验;(9)做完实验后给出本实验的实验报告。
二、实验仪器和设备奔腾以上计算机,Windows 操作系统,装有JDK1.7和Eclipse软件。
三、实验过程(1)分别使用JDK命令行和Eclipse编译运行Java应用程序。
记录操作过程。
Java应用程序参考如下:思考:1. 适当添加注释信息,通过javadoc生成注释文档;2. 为主方法传递参数“Hello world”字符串,并输出;3. 压缩生成".jar"文件。
(2)分别使用JDK命令行和Eclipse编译Java Applet,并建立HTML文档运行该Applet。
记录操作过程。
Java小应用程序参考如下:HTML文档参考如下:<html><applet code="HelloApplet.class" height=100 width=300></applet></html>(3)输出下列数字形式。