十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这个是我以前写着玩的一个例子,可以运行起来看看,有保存,撤销,复制,剪切功能,自己研究研究
创新互联公司是一家成都网站设计、成都做网站,提供网页设计,网站设计,网站制作,建网站,按需开发,网站开发公司,成立于2013年是互联行业建设者,服务者。以提升客户品牌价值为核心业务,全程参与项目的网站策划设计制作,前端开发,后台程序制作以及后期项目运营并提出专业建议和思路。
package test;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MyNote {
private JFrame frame = new JFrame("记事本");
private JTextArea text = new JTextArea();
private static boolean flag = false; // 判断是否保存
public MyNote() {
JMenuBar bar = new JMenuBar();
JMenu edit = new JMenu("check");
JMenu check = new JMenu("edit");
JMenu help = new JMenu("help");
JMenuItem term = new JMenuItem("copy");
JMenuItem term1 = new JMenuItem("paste");
JMenuItem term2 = new JMenuItem("cut");
JMenuItem term3 = new JMenuItem("backout");
JMenuItem term4 = new JMenuItem("import");
JMenuItem term5 = new JMenuItem("open");
JMenuItem term6 = new JMenuItem("exit");
JMenuItem term7 = new JMenuItem("save to");
JMenuItem term8 = new JMenuItem("about");
JMenuItem term9 = new JMenuItem("save");
JMenuItem term10 = new JMenuItem("new");
Font font = new Font(null, JFrame.ABORT, 24);
text.setFont(font);
JScrollPane scroll = new JScrollPane(text);
frame.setJMenuBar(bar);
bar.add(edit);
bar.add(check);
bar.add(help);
edit.add(term7);
edit.add(term4);
edit.add(term5);
edit.add(term6);
check.add(term);
check.add(term1);
check.add(term2);
check.add(term3);
help.add(term8);
check.add(term9);
edit.add(term10);
frame.add(scroll);
text.setVisible(false);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setLocation(500, 500);
// 事件注册
MenuListener m = new MenuListener();
term5.addActionListener(m);
NewListener n = new NewListener();
term4.addActionListener(n);
SaveListener s = new SaveListener();
term7.addActionListener(s);
CopyListener c = new CopyListener();
term.addActionListener(c);
PasteListener p = new PasteListener();
term1.addActionListener(p);
CutListener c1 = new CutListener();
term2.addActionListener(c1);
HelpListener h = new HelpListener();
term8.addActionListener(h);
ExitListener e = new ExitListener();
term6.addActionListener(e);
CloseListener c2 = new CloseListener();
frame.addWindowListener(c2);
BackOutListener b = new BackOutListener();
term3.addActionListener(b);
SaveActionListener s1 = new SaveActionListener();
term9.addActionListener(s1);
NewFileListener n1 = new NewFileListener();
term10.addActionListener(n1);
}
private class MenuListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
text.setVisible(true);
}
}
// 打开新文件
private class NewListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
text.setText("");
JFileChooser fileChooser = new JFileChooser();
int r = fileChooser.showOpenDialog(frame);
if (r == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
FileReader fr = new FileReader(file);
char[] buf = new char[1024];
int len = 0;
while ((len = fr.read(buf)) != -1) {
text.append(new String(buf, 0, len));
}
fr.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
// 另存为
private class SaveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser filechoose = new JFileChooser();
int r = filechoose.showSaveDialog(frame);
if (r == JFileChooser.APPROVE_OPTION) {
File file = filechoose.getSelectedFile();
try {
FileWriter writer = new FileWriter(file);
writer.write((String) text.getText());
writer.close();
// 下面方法也可以
/*
* PrintWriter print=new PrintWriter(file);
* print.write(text.getText()); print.close();
*/
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
// 复制
private class CopyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
text.copy();
}
}
// 粘贴
private class PasteListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
text.paste();
}
}
// 剪切
private class CutListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
text.cut();
}
}
// 关于主题
private class HelpListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "汪雄辉的无敌记事本");
}
}
private class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "谢谢!");
try {
Thread.sleep(2000);
System.exit(0);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
private class CloseListener implements WindowListener {
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
// 关闭窗口
public void windowClosing(WindowEvent e) {
StringBuffer sb = new StringBuffer();
try {
FileReader fr = new FileReader("未命名文件.txt");
char[] buf = new char[1024];
int len = 0;
while ((len = fr.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
fr.close();
} catch (Exception e1) {
e1.getStackTrace();
}
String s = sb.toString();
if (flag == false || !(text.getText().equals(s))) {
int r = JOptionPane.showConfirmDialog(frame, "你还没有保存,要保存吗?");
if (r == JOptionPane.OK_OPTION) {
JFileChooser filechoose = new JFileChooser();
int r1 = filechoose.showSaveDialog(frame);
if (r1 == JFileChooser.APPROVE_OPTION) {
File file = filechoose.getSelectedFile();
try {
FileWriter writer = new FileWriter(file);
writer.write((String) text.getText());
writer.close();
System.exit(0);
// 下面方法也可以
/*
* PrintWriter print=new PrintWriter(file);
* print.write(text.getText()); print.close();
*/
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
}
} else if (r == JOptionPane.NO_OPTION) {
System.exit(0);
} else {
}
} else
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
// 撤销
private class BackOutListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (flag == false)
text.setText("");
else {
try {
FileReader fr = new FileReader("未命名文件.txt");
char[] buf = new char[1024];
int len = 0;
while ((len = fr.read(buf)) != -1) {
text.setText(new String(buf, 0, len));
}
fr.close();
} catch (IOException e1) {
e1.getStackTrace();
}
}
}
}
// 保存文件
private class SaveActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
flag = true;
FileWriter writer;
try {
writer = new FileWriter("未命名文件.txt");
writer.write((String) text.getText());
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class NewFileListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
new MyNote();
}
}
public static void main(String[] args) {
new MyNote();
}
}
事实上,如果您想以Java实现网页截图,也就是“输入一段网址,几秒钟过后就能截取一张网页缩略图”的效果。那么,您至少有3种方式可以选择。
1、最直接的方式——使用Robot
方法详解:该方法利用Robat提供的强大桌面操作能力,硬性调用浏览器打开指定网页,并将网页信息保存到本地。
优势:简单易用,不需要任何第三方插件。
缺点:不能同时处理大量数据,技术含量过低,属于应急型技巧。
实现方法:使用如下代码即可。
[java] view plaincopy
public static void main(String[] args) throws MalformedURLException,
IOException, URISyntaxException, AWTException {
//此方法仅适用于JdK1.6及以上版本
Desktop.getDesktop().browse(
new URL("").toURI());
Robot robot = new Robot();
robot.delay(10000);
Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
int width = (int) d.getWidth();
int height = (int) d.getHeight();
//最大化浏览器
robot.keyRelease(KeyEvent.VK_F11);
robot.delay(2000);
Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
height));
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
//保存图片
ImageIO.write(bi, "jpg", new File("google.jpg"));
}
2、最常规的方式——利用JNI,调用第三方C/C++组件
方法详解:目前来讲,Java领域对于网页截图组件的开发明显不足(商机?),当您需要完成此种操作时,算得上碰到了Java的软肋。但是,众所周知Java也拥有强大的JNI能力,可以轻易将C/C++开发的同类组件引为己用。不懂可以扣五七八零二四一四四
优势:实现简单,只需要封装对应的DLL文件,就可以让Java实现同类功能。
劣势:同其他JNI实现一样,在跨平台时存在隐患,而且您的程序将不再属于纯Java应用。
主要是利用java的几个先有的函数,如Robot这个类的一个方法createScreenCapture一个获得一个任意大小的屏幕图像(在这里是全屏图像),而所谓的截图就是在这个图像上画出一个矩形,再利用上面的方法获得这部分的图像,程序中的cf.setAlwaysOnTop(true)是必需的;看起来是在屏幕上截图,其实只是在一个在一个内镶有桌面背景的JFrame中截图。不知道还有没有其他的好方法~
附上代码:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Camera {
/**
* @param args
*/
public static void main(String[] args) {
CameraJFrame cf=new CameraJFrame();
cf.setAlwaysOnTop(true);
cf.setUndecorated(true);
cf.setVisible(true);
}
}
class CameraJFrame extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
Dimension di=Toolkit.getDefaultToolkit().getScreenSize();
public CameraJFrame()
{
setSize(di);
getContentPane().add(new CameraJPanel());
}
class CameraJPanel extends JPanel implements MouseListener,MouseMotionListener
{
/**
* flag主要是用来判别状态。
* 文件的格式名是unname+数字编号,格式是png
*/
private static final long serialVersionUID = 1L;
BufferedImage bi,get;
int startx,starty,endx,endy;
int flag=1;
String filename="unname";
String fileformat="png";
int count=1;
public CameraJPanel()
{
try
{
Robot ro=new Robot();
bi=ro.createScreenCapture(new Rectangle(0,0,di.width,di.height));
}
catch(Exception e)
{
e.printStackTrace();
}
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
g.drawImage(bi,0,0,di.width,di.height,this);
g.setColor(Color.red);
g.drawRect(startx, starty, endx-startx, endy-starty);
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton()==MouseEvent.BUTTON3)
{
System.exit(0);
}
else if(e.getClickCount()==2)
{
try
{
Robot ro=new Robot();
get=ro.createScreenCapture(new Rectangle(startx,starty,endx-startx,endy-starty));
String name=filename+String.valueOf(count++)+"."+fileformat;
File f=new File(name);
ImageIO.write(get, fileformat, f);
}
catch(Exception ex)
{
ex.printStackTrace();
}
flag=1; //置flag为1,以便重新开始截图。
startx=starty=endx=endy=0;
repaint();
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
if(flag==1)
{
startx=e.getX();
starty=e.getY();
}
}
public void mouseReleased(MouseEvent e) {
flag=0;
}
public void mouseDragged(MouseEvent e) {
flag=1;
endx=e.getX();
endy=e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {}
}
}
下面给你介绍将全屏幕截图保存到指定目录下的代码,希望能对你有帮助:
核心代码为:snapShot方法中的相关逻辑
package Jietu;
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 CameraTest {
private String filePreStr; // 默认前缀(选择存储路径例如: D:\\)
private String defName = "cameraImg"; // 默认截图名称
static int serialNum = 0; //截图名称后面的数字累加
private String imageFormat; // 图像文件的格式
private String defaultImageFormat = "png"; //截图后缀
Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); //获取全屏幕的宽高尺寸等数据
public CameraTest() {
filePreStr = defName;
imageFormat = defaultImageFormat;
}
public CameraTest(String s, String format) {
filePreStr = s;
imageFormat = format;
}
public void snapShot() {
try {
// *** 核心代码 *** 拷贝屏幕到一个BufferedImage对象screenshot
BufferedImage screenshot = (new Robot()).createScreenCapture(new Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight()));
serialNum++;
// 根据文件前缀变量和文件格式变量,自动生成文件名
String name = filePreStr + String.valueOf(serialNum) + "." + imageFormat;
File f = new File(name);
System.out.print("Save File " + name);
// 将screenshot对象写入图像文件
ImageIO.write(screenshot, imageFormat, f);
System.out.print("..Finished!\n");
} catch (Exception ex) {
System.out.println(ex);
}
}
// 运行之后,即可将全屏幕截图保存到指定的目录下面br // 配合前端页面上面的选择尺寸等逻辑,传到后台,即可实现自由选择截图区域和大小的截图br
public static void main(String[] args) {
CameraTest cam = new CameraTest("d:\\Hello", "png");//
cam.snapShot();
}
}
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class Test95 {
// 图片源
private static final String SRC_FILE = "c://1.jpg";
// 目标图片
private static final String DEST_FILE = "c://2.jpg";
public void readUsingImageReader() throws Exception{
// 取得图片读入器
Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
System.out.println(readers);
ImageReader reader = (ImageReader) readers.next();
System.out.println(reader);
// 取得图片读入流
InputStream source = new FileInputStream(SRC_FILE);
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
// 图片参数
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(100, 200, 300, 150);//100,200是左上起始位置,300就是取宽度为300的,就是从100开始取300宽,就是横向100~400,同理纵向200~350的区域就取高度150
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
ImageIO.write(bi, "jpg", new File(DEST_FILE));
}
public static void main(String[] args) throws Exception{ //main方法测试用
Test95 t =new Test95();
t.readUsingImageReader();
}
}
package guxi.test;
import java.util.ArrayList;
import java.util.List;
public class Stu {
public static void main(String[] args) {
ListStu 学校 = new ArrayListStu();
// 测试学生
学校.add(new Stu("张三", "No.1"));
学校.add(new Stu("李四", "No.2"));
学校.add(new Stu("王五", "No.3"));
学校.add(new Stu("赵六", "No.4"));
学校.add(new Stu("孙七", "No.5"));
for (int i = 0; i 学校.size(); i++) {
Stu stu = 学校.get(i);
if (i % 2 == 0) {
stu.上课();
} else {
stu.考试();
}
stu.study();
}
}
private static int 学生人数;
private String 学号;
private String 姓名;
private String 性别;
private String 年龄;
private String 专业;
private String 电子邮箱;
private String QQ;
private String 住址;
public Stu(String 姓名, String 学号) {
this.姓名 = 姓名;
this.学号 = 学号;
学生人数++;
System.out.println(姓名 + " 入学,学号:" + 学号 + " 当前学生人数:" + 学生人数);
}
public void 上课() {
System.out.println(姓名 + " 在上课");
}
public void 考试() {
System.out.println(姓名 + " 在考试");
}
public void study() {
System.out.println(姓名 + ",你要好好学习,天天向上");
}
public String get学号() {
return 学号;
}
public void set学号(String 学号) {
this.学号 = 学号;
}
public String get姓名() {
return 姓名;
}
public void set姓名(String 姓名) {
this.姓名 = 姓名;
}
public String get性别() {
return 性别;
}
public void set性别(String 性别) {
this.性别 = 性别;
}
public String get年龄() {
return 年龄;
}
public void set年龄(String 年龄) {
this.年龄 = 年龄;
}
public String get专业() {
return 专业;
}
public void set专业(String 专业) {
this.专业 = 专业;
}
public String get电子邮箱() {
return 电子邮箱;
}
public void set电子邮箱(String 电子邮箱) {
this.电子邮箱 = 电子邮箱;
}
public String getQQ() {
return QQ;
}
public void setQQ(String qQ) {
QQ = qQ;
}
public String get住址() {
return 住址;
}
public void set住址(String 住址) {
this.住址 = 住址;
}
public static int get学生人数() {
return 学生人数;
}
}