java记事本打印的代码 java在记事本里打完代码如何运行

JAVA中怎么编写打印功能代码

Print.java--打印内容定义 [code] import java.awt.*; import java.awt.event.*; import java.awt.print.*; import java.awt.image.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.event.*; import java.util.*; import java.io.*; public class Print implements Printable{ int m_wPage; int m_hPage; int m_orientation; Printable m_target; int maxNumPage=1; String title="数据表格打印"; Font titleFont=new Font("黑体",Font.BOLD,14); boolean hasTail=true; int tailAlign=0; int headAlign=0; int topSpace=0; int leftSpace=0; int yStart=0; int yEnd=0; int xStart=topSpace; int xEnd=0; int x=0,y=0; String strTemp="打印内容"; public void doPrint(){ try{ m_orientation=PageFormat.PORTRAIT; //设置打印对象,默认纸张 PrinterJob prnJob=PrinterJob.getPrinterJob(); PageFormat pageFormat=prnJob.defaultPage(); pageFormat.setOrientation(m_orientation); m_wPage=(int)(pageFormat.getWidth()); m_hPage=(int)(pageFormat.getHeight()); //将待打印的窗体根据默认纸张设置传入打印对象 prnJob.setPrintable(this,pageFormat); if(!prnJob.printDialog()) return; prnJob.print(); }catch(PrinterException ex){ ex.printStackTrace(); System.err.println("打印错误:"+ex.toString()); } } /** * 初始化打印参数 */ public void initPrintParameter() { } /** *构造打印内容,以送打印机打印 */ public int print(Graphics pg,PageFormat pageFormat, int pageIndex) throws PrinterException{ //初始化打印参数 initPrintParameter(); //将画布设置为页面大小 pg.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY()); int wPage=0; int hPage=0; //根据打印机页面设置调整画布大小 if(pageFormat.getOrientation()==pageFormat.PORTRAIT){ wPage=(int)pageFormat.getImageableWidth(); hPage=(int)pageFormat.getImageableHeight(); } else{ wPage=(int)pageFormat.getImageableWidth(); wPage+=wPage/2; hPage=(int)pageFormat.getImageableHeight(); pg.setClip(0,0,wPage,hPage); } wPage=wPage-2*leftSpace; hPage=hPage-2*topSpace; xStart=leftSpace; xEnd=wPage-2; //为画布设置颜色和字体 int y=topSpace; pg.setFont(titleFont); pg.setColor(Color.black); //画标题,并使其居中 Font fn=pg.getFont(); FontMetrics fm=pg.getFontMetrics(); y+=fm.getAscent(); alignText(title,pg,y,xStart,xEnd,headAlign); y+=30; x=leftSpace+2; Font headerFont=new Font("宋体",Font.BOLD,14); pg.setFont(headerFont); fm=pg.getFontMetrics(); int h=fm.getAscent(); yStart=y-1; y+=h; pg.setFont(headerFont); fm=pg.getFontMetrics(); int header=y; h=fm.getHeight(); //计算行高,每页行数,总行数和指定页码的起始行、结束行 int rowH=Math.max(h,10); int tailH=rowH+30; int rowPerPage=0; int leftPix=0; if(hasTail){ rowPerPage=(hPage-header-tailH)/rowH; leftPix=(hPage-header-tailH)%rowH; yEnd=hPage-leftPix-tailH+2; } else{ rowPerPage=(hPage-header)/rowH; leftPix=(hPage-header)%rowH; yEnd=hPage-leftPix+2; } pg.drawString(strTemp,x,y); //画表格边框 pg.drawLine(xStart,yStart,xStart,yEnd); pg.drawLine(xStart,yStart,xEnd,yStart); pg.drawLine(xEnd,yStart,xEnd,yEnd); pg.drawLine(xStart,yEnd,xEnd,yEnd); //打印页码 if(hasTail){ int pageNumber=pageIndex+1; String s="第"+pageNumber+"页"; alignText(s,pg,yEnd+30,xStart,xEnd,tailAlign); } System.gc(); return PAGE_EXISTS; } /** * 文字排列,坐标在y处,显示范围(start-end) * 0表示居中显示,1表示左对齐,2表示右对齐 */ private void alignText(String s,Graphics pg,int y,int start, int end,int mode){ Font fn=pg.getFont(); FontMetrics fm=pg.getFontMetrics(); int wString=fm.stringWidth(s); int x=start; switch(mode) { case 0: if((end-start-wString)0) x=start+(end-start-wString)/2; break; case 1: break; case 2: if((end-start-wString)0) x=start+(end-start-wString); break; } pg.drawString(s,x,y); } public static void main(String[] args){ Print p=new Print(); p.doPrint(); } } [code] 运行方法: javac -d . Print.java java Print 自己运行一下 from:

创新互联公司长期为上千余家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为柳南企业提供专业的网站设计制作、成都网站建设柳南网站改版等技术服务。拥有十载丰富建站经验和众多成功案例,为您定制开发。

采纳哦

使用记事本编写JAVA程序,并运行输出结果,具体的实现步骤是什么?

1、首先在电脑中新建一个记事本,将记事本的后缀改为“.java”,如下图所示。

2、然后使用记事本的方式打开,输入java程序代码,如下图所示。

3、接着在键盘上按“win+R”快捷键键打开运行,输入“cmd”,如下图所示。

4、在命令行输入“D:”,按“Enter”键进去D盘,再输入“cd Desktop”进去Desktop文件夹,如下图所示。

5、最后再输入“javac Test.java”,按“Enter”键编译java程序,如下图所示就完成了。

Java记事本源代码

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.datatransfer.Clipboard;

import java.awt.datatransfer.DataFlavor;

import java.awt.datatransfer.Transferable;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.FocusEvent;

import java.awt.event.FocusListener;

import java.awt.event.InputEvent;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

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.JPanel;

import javax.swing.JPopupMenu;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.KeyStroke;

import javax.swing.filechooser.FileFilter;

public class Demo extends JFrame {

private static final long serialVersionUID = 1L; //Eclipse自动生成序列号

String name = "无标题";

JPanel menuPanel = new JPanel();

JTextArea text = new TextAreaMenu(); //文本编辑区

JScrollPane jsp = new JScrollPane(text); //可滚动编辑区

JMenuBar mnbMain = new JMenuBar();

JMenu mnServer = new JMenu("文件(F)");

JMenu mnEdit = new JMenu("编辑(E)");

JMenuItem[] mniServers = new JMenuItem[]{

new JMenuItem("新建(N)"),

new JMenuItem("保存(S)"),

new JMenuItem("打开(O)"),

new JMenuItem("退出(X)"),

};

{

menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));

mnbMain.add(mnServer);

menuPanel.add(mnbMain);

mnbMain.setBounds(5, 0, 50, 30);

for (int i = 0; i mniServers.length; i++) {

mnServer.add(mniServers[i]);

}

mniServers[0].addActionListener(new ActionListener() { //定义"新建"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

new Demo(getLocation().x+15,getLocation().y+5);

}

});

mniServers[1].addActionListener(new ActionListener() { //定义"保存"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

chooseToSave();

}

});

mniServers[2].addActionListener(new ActionListener() { //定义"打开"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

chooseToOpen();

}

});

mniServers[3].addActionListener(new ActionListener() { //定义"退出"组件操作

@Override

public void actionPerformed(ActionEvent arg0) {

System.exit(0);

}

});

text.addFocusListener(new FocusListener() {

@Override

public void focusLost(FocusEvent e) {

// TODO Auto-generated method stub

}

@Override

public void focusGained(FocusEvent e) {

}

});

}

public Demo(int x,int y) {

this.setTitle( name +" - 记事本");

this.setBounds(x, y, 600, 400);

this.setLayout(new BorderLayout());

this.add(menuPanel, BorderLayout.NORTH);

this.add(jsp);

jsp.setBounds(5, 30, getWidth()-10, getHeight()-50);

this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

this.setVisible(true);

}

public Demo() {

this(200,200);

}

protected void chooseToSave() {

File file = chooseFile();

if(null==file)return;

if(file.exists()){

int cho = JOptionPane.showConfirmDialog(this, "文件已存在,是否覆盖?");

System.out.println(cho);

if(cho==JOptionPane.OK_OPTION)save(file);

else return;

}

else save(file);

}

private void save(File file) {

name = file.getName();

write(text.getText(),file.getPath());

this.setTitle( name +" - 记事本");

}

protected void chooseToOpen() {

File file = chooseFile();

if(null==file||!file.exists())return;

name = file.getName();

Demo.this.setTitle( name +" - 记事本");

read(text,file);

}

/*********************************************MAIN**************************************************/

public static void main(String[] args) {

new Demo();

}

private File chooseFile(){

JFileChooser chooser = new JFileChooser(); //构建文件选择器

chooser.setFileFilter(new FileFilter() {

@Override

public String getDescription() {

return "文本文件";

}

@Override

public boolean accept(File f) {

String name = f.getName().toLowerCase();

return f.isDirectory() || name.endsWith(".txt")

||name.endsWith(".c") || name.endsWith(".java")

||name.endsWith(".cpp"); //可识别文件

}

});

int result = chooser.showDialog(null, "确定");

if (result==JFileChooser.APPROVE_OPTION) {

File file = chooser.getSelectedFile();

System.out.println(file.getAbsolutePath());

} else {

System.out.println("未选择文件");

}

return chooser.getSelectedFile();

}

public static void read(JTextArea text,File file){ //定义读取文件操作

FileReader fr;

try {

fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

String string = null;

while((string = br.readLine()) != null){

text.append(string+"\n");

}

br.close();

fr.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void write(String txt,String fileName){

FileWriter fw;

try {

fw = new FileWriter(fileName);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(txt);

bw.flush();

bw.close();

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

class TextAreaMenu extends JTextArea implements MouseListener {

private static final long serialVersionUID = -2308615404205560110L;

private JPopupMenu pop = null; // 弹出菜单

private JMenuItem selectAll = null,copy = null, paste = null, cut = null, cancel=null; // 功能菜单

public TextAreaMenu() {

super();

init();

}

private void init() {

this.addMouseListener(this);

this.setSelectedTextColor(Color.red);

pop = new JPopupMenu();

pop.add(selectAll = new JMenuItem("全选"));

pop.add(copy = new JMenuItem("复制"));

pop.add(paste = new JMenuItem("粘贴"));

pop.add(cut = new JMenuItem("剪切"));

pop.add(cancel = new JMenuItem("撤销"));

selectAll.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_MASK));

copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));

paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));

cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));

cancel.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_MASK));

copy.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

action(e);

}

});

paste.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

action(e);

}

});

cut.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

action(e);

}

});

this.add(pop);

}

/**

* 菜单动作

* @param e

*/

public void action(ActionEvent e) {

String str = e.getActionCommand();

if (str.equals(selectAll.getText())) { // 全选

this.selectAll();

}

else if (str.equals(copy.getText())) { // 复制

this.copy();

} else if (str.equals(paste.getText())) { // 粘贴

this.paste();

} else if (str.equals(cut.getText())) { // 剪切

this.cut();

}

else if (str.equals(cancel.getText())) { //撤销

this.cut();

}

}

public JPopupMenu getPop() {

return pop;

}

public void setPop(JPopupMenu pop) {

this.pop = pop;

}

/**

* 剪切板中是否有文本数据可供粘贴

*

* @return true为有文本数据

*/

public boolean isClipboardString() {

boolean b = false;

Clipboard clipboard = this.getToolkit().getSystemClipboard();

Transferable content = clipboard.getContents(this);

try {

if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {

b = true;

}

} catch (Exception e) {

}

return b;

}

/**

* 文本组件中是否具备复制的条件

*

* @return true为具备

*/

public boolean isCanCopy() {

boolean b = false;

int start = this.getSelectionStart();

int end = this.getSelectionEnd();

if (start != end)

b = true;

return b;

}

public void mouseClicked(MouseEvent e) {

}

public void mouseEntered(MouseEvent e) {

}

public void mouseExited(MouseEvent e) {

}

public void mousePressed(MouseEvent e) {

if (e.getButton() == MouseEvent.BUTTON3) {

copy.setEnabled(isCanCopy());

paste.setEnabled(isClipboardString());

cut.setEnabled(isCanCopy());

pop.show(this, e.getX(), e.getY());

}

}

public void mouseReleased(MouseEvent e) {

}

}


网站题目:java记事本打印的代码 java在记事本里打完代码如何运行
文章来源:http://azwzsj.com/article/hihjij.html