導航:首頁 > 編程語言 > 用java編寫的記事本

用java編寫的記事本

發布時間:2022-04-12 15:52:06

㈠ 用java編個簡單的記事本程序

import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;

class Editor extends Frame implements ActionListener,ItemListener
{
// Date date=new Date();
int n1;String str="";int k=0;String st1,st2;
JTextArea ta=new JTextArea(50,50);
Dialog dialog,dialog1;
Choice ce1,ce2,ce3;
Button btn1,btn2,btn3;Panel p1=new Panel();
Panel p2=new Panel();Panel p3=new Panel();Panel p4=new Panel();
public Editor (String s)
{
super ("記事本編輯板");
ImageIcon YouImg = new ImageIcon("iconimage.jpg");
setIconImage(YouImg.getImage());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}

});
setBounds(50,35,700,500);

MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu file=new Menu("文件(F)");Menu edit=new Menu("編輯(E)");Menu help=new Menu("幫助(H)");
Menu pattern=new Menu("格式(P)");Menu time=new Menu("時間(T)");
MenuItem exit=new MenuItem("退出",new MenuShortcut(KeyEvent.VK_Q));
MenuItem tdate=new MenuItem("日期/時間",new MenuShortcut(KeyEvent.VK_D));
MenuItem renew=new MenuItem("新建", new MenuShortcut(KeyEvent.VK_N));
MenuItem save=new MenuItem("保存", new MenuShortcut(KeyEvent.VK_S));
MenuItem open=new MenuItem("打開",new MenuShortcut(KeyEvent.VK_O));
MenuItem =new MenuItem("復制",new MenuShortcut(KeyEvent.VK_C));
MenuItem paste=new MenuItem("粘貼",new MenuShortcut(KeyEvent.VK_V));
MenuItem cut=new MenuItem("剪切",new MenuShortcut(KeyEvent.VK_X));
MenuItem helptopic=new MenuItem("主題",new MenuShortcut(KeyEvent.VK_T));
helptopic.addActionListener(this);
dialog=new Dialog(this, "字體設置");dialog.setSize(300,300);
dialog1=new Dialog(this, "幫助主題");dialog1.setBounds(250,100,300,400);
dialog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dialog.setVisible(false);}
});
dialog1.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dialog1.setVisible(false);}
});
//dialog.setBackground(Color.WHITE);
dialog.setLayout(null);dialog.setBounds(170,150,450,300);
Label L1=new Label("字體(F)");Label L2=new Label("字形(Y)");
Label L3=new Label("大小(S)");TextArea ta1=new TextArea(5,5);
ta1=new TextArea("至於記事本的主題嘛,因為本人的水平有限, 所有不能為大家作過多的指導,望大家見諒!"); //在這里我想加一個文本框用來放幫助信息。

ce1=new Choice();ce2=new Choice();
ce3=new Choice();
btn1=new Button("確定");btn2=new Button("取消");btn1.addActionListener(this);btn2.addActionListener(this);
btn3=new Button("顏色");
btn3.addActionListener(this);

ce1.add("華文行楷");ce1.add("華文中宋");ce1.add("華文新魏");ce1.add("華文細黑");ce1.add("宋體");ce1.add("方正姚體");
ce1.add("幼圓");ce1.add("隸書");ce1.add("楷體-GB2312");ce1.add("華文行楷");ce1.add("華文彩雲");ce1.add("仿宋-GB2312");
ce2.add("粗體");ce2.add("斜體");ce2.add("常規");
for(int n1=0;n1<=100;n1++)
{ce3.add(""+n1);}
dialog.add(p1);p1.setBounds(5,30,440,35);p1.setLayout( null);//p1.setBackground(Color.red);
dialog.add(p2);p2.setBounds(5,65,440,27);dialog.add(p3);p3.setBounds(5,90,440,40);//p4.setBounds(5,120,440,138);
p1.setLayout( null);
p1.add(L1);L1.setBounds(5,15,50,25);p1.add(L2);L2.setBounds(150,15,50,25);
p1.add(L3);L3.setBounds(250,15,50,25);p2.setLayout( null);//p2.setBackground(Color.yellow);
p2.add(ce1);ce1.setBounds(5,0,130,25);p2.add(ce2);ce2.setBounds(160,0,90,25);p2.add(ce3);ce3.setBounds(260,0,75,25);
p2.add(btn1);btn1.setBounds(360,0,75,25);
p3.setLayout( null);p3.add(btn2);btn2.setBounds(360,10,75,25);p3.add(btn3);btn3.setBounds(160,10,75,25);
dialog.add(p4);p4.setBackground(Color.yellow);p4.setBounds(5,120,440,138);
dialog1.add(ta1);
//設置字體的下拉情況
MenuItem Font=new MenuItem("字體");//給字體加監聽器
Font.addActionListener(this);
MenuItem Replace=new MenuItem("替換"); MenuItem Seek=new MenuItem("查找");
//首要添加組件的情況
mb.add(file);mb.add(edit);mb.add(pattern);mb.add(time);mb.add(help);
file.add(renew);file.addSeparator();file.add(open);time.add(tdate);
file.addSeparator(); file.add(exit);file.addSeparator();file.add(save);
edit.add(); edit.addSeparator();edit.add(paste);edit.addSeparator();edit.add(cut);
pattern.add(Font); pattern.add(Replace);
pattern.add(Seek);help.add(helptopic);
//給必要的組件加上監聽器
renew.addActionListener( this);tdate.addActionListener(this);
open.addActionListener(this); save.addActionListener(this);exit.addActionListener(this);
cut.addActionListener(this);.addActionListener(this);paste.addActionListener(this);
ce1.addItemListener(this);ce2.addItemListener(this);ce3.addItemListener(this);
//添加必要的組件
add(ta,"Center");ta.setBackground(new Color(249,255,234));
setSize(700,500);
setVisible(true);
this.validate() ;

}

public void itemStateChanged(ItemEvent e) {
if (ce2.getSelectedItem().equals("粗體"))
{ k=1;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
if (ce2.getSelectedItem().equals("斜體"))
{ k=2;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
if (ce2.getSelectedItem().equals("常規"))
{ k=3;st1=ce1.getSelectedItem();st2=ce3.getSelectedItem();}
}

public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("新建"))
{System.out.println("new ");
ta.setText("");}
if(e.getActionCommand().equals("退出"))
{ System.exit(0);}
try
{
if(e.getActionCommand().equals("打開"))
openText();
if(e.getActionCommand().equals("保存"))
saveText();
}catch(IOException e1){}
if(e.getActionCommand().equals("復制"))
{ str=ta.getSelectedText();}
if(e.getActionCommand().equals("粘貼"))
{ ta.insert(str,ta.getCaretPosition());}
if(e.getActionCommand().equals("剪切"))
{str=ta.getSelectedText();ta.replaceRange("",ta.getSelectionStart(),ta.getSelectionEnd());

}
if(e.getActionCommand().equals("字體"))
{dialog.setVisible(true);}
if(e.getActionCommand().equals("主題"))
{dialog1.setVisible(true);}
if(e.getActionCommand().equals("顏色"))
{
Color clr=JColorChooser.showDialog(this,"顏色對話框",null);
ta.setForeground(clr);
}

if(e.getSource()==btn2)
dialog.setVisible(false);
if(e.getSource()==btn1)
{
if(k==1)
{ ta.setFont(new Font(st1,Font.BOLD,Integer.parseInt(st2)));}
if(k==2)
{ ta.setFont(new Font(st1,Font.ITALIC,Integer.parseInt(st2)));}
if(k==3)
{ ta.setFont(new Font(st1,Font.PLAIN,Integer.parseInt(st2)));}
dialog.setVisible(false);
}

//if (e.getActionCommand().equals("日期/時間"))
//ta.setText(ta.getText()+""+date);
if(e.getActionCommand().equals("日期/時間"))
{
Calendar c1 =Calendar.getInstance();
int y = c1.get(Calendar.YEAR);
int m = c1.get(Calendar.MONTH);
int d = c1.get(Calendar.DATE);
int h = c1.get(Calendar.HOUR);
int m1 = c1.get(Calendar.MINUTE);
int m2 = m+1;
ta.setText(ta.getText()+""+(y+"年"+m2+"月"+d+"日"+h+":"+m1));
}

}

public void openText() throws IOException
{
FileDialog fd=new FileDialog(this,"打開文件對話框",FileDialog.LOAD);
fd.setVisible(true);FileInputStream fis=new FileInputStream(fd.getDirectory()+fd.getFile());
ta.setText("");
int n=0;
while((n=fis.read())!=-1)
ta.append(""+(char)n);
fis.close();
}
public void saveText() throws IOException
{
FileDialog fd=new FileDialog(this,"打開文件對話框",FileDialog.SAVE);
fd.setVisible(true);
FileOutputStream out=new FileOutputStream(fd.getDirectory()+fd.getFile()+".txt");
String str=ta.getText();

String str1=ta.getText();
for(int n=0;n<str.length();n++)
out.write((byte)str.charAt(n));
out.close();
}

public static void main(String[] args)
{
Editor f=new Editor(" 記事本程序");
//添加時間代碼
Date date=new Date();
System.out.print(date);
/*Calendar now=Calendar.getInstance();
int year=now.get(Calendar.YEAR);
int month=now.get(Calendar.MONTH)+1;
int day=now.get(Calendar.DATE);
System.out.print(year+"年"+month+"月"+day+"日");

int week=now.get(Calendar.DAY_OF_WEEK);
String str="日一二三四五六";//星期1-7
int i=2*(week-1);
System.out.println("星期"+str.substring(i,i+2));//對應中文的下標*/

}

class dialog extends Dialog
{

public dialog()
{
super(dialog, "字體設置");

class Mycanvas extends Canvas
{
Toolkit tk;
Image img;
Mycanvas()
{
setSize(440,138);
tk=getToolkit();
img=tk.getImage("photo.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,5,120,440,138,this);
}
}
}
}
}

㈡ java編寫簡單記事本

方法/步驟
下載JDK,並安裝成功,CMD測試Java環境安裝成功。出現如下提示則Java環境安裝成功

打開mycelipse進入主界面,點擊左上角file--new---java project,新建一個Java項目,項目名字任意取,這里我取名為note--然後點擊完成,創建Java項目

然後右鍵項目下的src--new---package,新建一個包,包名我定為notetest,然後點擊完成

然後右鍵我們建立好的包notetest--new--class,包名為Note,點擊完成

首先我們想導入工程所需要的包,以便編寫程序時進行調用
package notepad;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;

首先定義好編寫程序時變數,我們設為成員變數方便以後調用
public class Notepad{
//屏幕解析度
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
//窗體
private Frame frm ;

//顯示內容多行文本
private TextArea notetext;
//記事本菜單
private MenuBar mb;
//菜單
private Menu m ;
//菜單項
private MenuItem open,save;

為程序創建組件--Frame--菜單欄目--文本框TextArea
public Notepad(){init();}

private void init(){
frm = new Frame("模擬記事本");

//設置菜單
mb = new MenuBar();
m = new Menu("文件");

//顯示文件的地方
notetext = new TextArea();
notetext.setBounds(30, 50, 750, 500);
frm.add(notetext);
myEvent();

為控制項和按鈕添加監聽事件
private void myEvent() {
//打開菜單的事件處理
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//判斷路徑和文件名是否為空 如果為空結束程序
if(dir == null || name == null)

//如果不為空講路徑名和文件名封裝到File對象里

file = new File(dir,name);

//使用字元緩沖讀取文件

BufferedReader bfr = null;

try {
bfr = new BufferedReader(new FileReader(file));
});
save.addActionListener(new ActionListener(){

//獲取路徑和文件名

String dir =fd.getDirectory();
String name = fd.getFile();
//如果不為空講路徑名和文件名封裝到File對象里
file = new File(dir,name);
}

BufferedWriter bfr= null;
}

});
}
}

然後創建主方法,開始測試程序,新建一個NoteDemo類
package notepad;

public class NoteDemo {
public static void main(String[] args) {
new Notepad();
}

}

㈢ 用Java語言編寫一個記事本程序

import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JFileChooser; import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JFileChooser;
public class TextEditor extends Frame implements ActionListener{
MenuBar mainmenubar=new MenuBar();
Menu file;
MenuItem nw;
MenuItem op;
MenuItem cl;
MenuItem sf;
MenuItem ex;
TextArea tx;
public TextEditor(String title){
super(title);
CloseHandler handler= new CloseHandler();
this.addWindowListener(handler);
setSize(400,400);
setLocationRelativeTo(null);
menuinit();
tx=new TextArea();
this.add(tx);
setVisible(true);
}
void menuinit(){
mainmenubar =new MenuBar();
file=new Menu("File");
nw=new MenuItem("Great");
op=new MenuItem("Open");
cl=new MenuItem("Close");
sf=new MenuItem("save");
ex=new MenuItem("Exit");
file.add(nw);
file.add(op);
file.add(cl);
file.add(sf);
file.add(ex);
mainmenubar.add(file);
setMenuBar(mainmenubar);
nw.addActionListener(this);
op.addActionListener(this);
cl.addActionListener(this);
sf.addActionListener(this);
ex.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
Object ob=e.getSource();
JFileChooser f =new JFileChooser();
if((ob==nw)||(ob==ex)){
tx.setText("write word in here");
}else if(ob==op){
f.showOpenDialog(this);
try{
StringBuffer s=new StringBuffer();
FileReader in=new FileReader(f.getSelectedFile());
while(true){
int b=in.read();
if(b==-1)
break;
s.append((char)b);
}
String myString=s.toString();
char[] mychar=myString.toCharArray();
String unkeyFile =FileEncry(mychar);
tx.setText(unkeyFile.toString());
in.close();
}catch(Exception ee){
}
}else if(ob==sf){
f.showSaveDialog(this);
try{
FileWriter out =new FileWriter(f.getSelectedFile());
String mystr=tx.getText();
char[] strchar=mystr.toCharArray();
String keyFile =FileEncry(strchar);
out.write(keyFile);
out.close();
}catch (Exception ee){
}
}else if(ob==ex)
System.exit(0);
}
public static void main(String[] args){
new TextEditor("Simple TextEdit");
}
public String FileEncry(char[] encry){
StringBuffer str=new StringBuffer();
char[] encry1 =new char[encry.length];
for(int i=0; i<encry.length;i++){
encry1[i]=(char) (encry[i]^'F');
str.append(encry1[i]);
}
return str.toString();
}
}
class CloseHandler extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}

㈣ 如何用JAVA程序編寫一個記事本

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager;
import java.util.Date;
import java.text.SimpleDateFormat;

public class Notepad extends JFrame {
// 菜單
JMenuBar menub = new JMenuBar();
// 顯示純文本的多行區域
JTextArea text = new JTextArea();
JMenu files = new JMenu("文件(F)");
JMenu edit = new JMenu("編輯(E)");
JMenu formats = new JMenu("格式(O)");
JMenu help = new JMenu("幫助(H)");
JMenuItem newFile = new JMenuItem("新建(N)");
JMenuItem open = new JMenuItem("打開(O)");
JMenuItem save = new JMenuItem("保存(S)");
JMenuItem saveAs = new JMenuItem("另存為(A)");
JMenuItem exit = new JMenuItem("退出(X)");
JMenuItem undo = new JMenuItem("撤銷(U)");
JMenuItem cut = new JMenuItem("剪切(T)");
JMenuItem = new JMenuItem("復制(C)");
JMenuItem paste = new JMenuItem("粘貼(P)");
JMenuItem selectAll = new JMenuItem("全選(A)");
JMenuItem timeDate = new JMenuItem("時間/日期(D)");
JCheckBoxMenuItem lineWrap = new JCheckBoxMenuItem("自動換行(M)");
JMenuItem fonts = new JMenuItem("字體");
JMenuItem about = new JMenuItem("關於記事本(A)");
JFrame th = this;
String name;
String openedPath = null;
boolean opened = false;
boolean reworked = false;
UndoManager undoManager = new UndoManager();

// 初始化窗體
public Notepad(String name) {
super(name);
this.name = name;
int x, y;
// 得到用戶屏幕大小
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
x = (size.width - 600) / 2;
y = (size.height - 400) / 2;
setSize(600, 400);
// 讓程序界面顯示在屏幕中央
setLocation(x, y);
// 將此窗口的最小大小設置為一個常量值。
setMinimumSize(new Dimension(250, 150));
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

// 初始化布局
void init() {
files.setMnemonic('F');
edit.setMnemonic('E');
formats.setMnemonic('O');
help.setMnemonic('H');
newFile.setMnemonic('N');
open.setMnemonic('O');
save.setMnemonic('S');
saveAs.setMnemonic('A');
exit.setMnemonic('X');
undo.setMnemonic('U');
cut.setMnemonic('T');
.setMnemonic('C');
paste.setMnemonic('P');
selectAll.setMnemonic('A');
timeDate.setMnemonic('D');
lineWrap.setMnemonic('M');
about.setMnemonic('A');
// 為控制項添加助記符
newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
InputEvent.CTRL_MASK));
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_MASK));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
InputEvent.CTRL_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
InputEvent.CTRL_MASK));
.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
InputEvent.CTRL_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
InputEvent.CTRL_MASK));
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_MASK));
// 為控制項添加快捷鍵
timeDate.setAccelerator(KeyStroke.getKeyStroke("F5"));

files.add(newFile);
files.add(open);
files.add(save);
files.add(saveAs);
files.addSeparator();
files.add(exit);
edit.add(undo);
edit.addSeparator();
edit.add(cut);
edit.add();
edit.add(paste);
edit.addSeparator();
edit.add(selectAll);
edit.add(timeDate);
formats.add(lineWrap);
formats.add(fonts);
help.add(about);

menub.add(files);
menub.add(edit);
menub.add(formats);
menub.add(help);
setJMenuBar(menub);
getContentPane().add(new JScrollPane(text));

Listen listen = new Listen();
Listen1 listen1 = new Listen1();
// 為控制項添加事件偵聽器
newFile.addActionListener(listen);
undo.addActionListener(listen);
open.addActionListener(listen);
save.addActionListener(listen);
saveAs.addActionListener(listen);
exit.addActionListener(listen);
cut.addActionListener(listen);
.addActionListener(listen);
paste.addActionListener(listen);
selectAll.addActionListener(listen);
timeDate.addActionListener(listen);
lineWrap.addActionListener(listen);
about.addActionListener(listen);
open.addActionListener(listen1);
save.addActionListener(listen1);
saveAs.addActionListener(listen1);
// 暫時沒有實現的功能 :設置字體
//undo功能沒有實現
fonts.setEnabled(false);

}
class Listen implements ActionListener {
// 實現用於一般操作的事件偵聽器
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == newFile) {
text.setText("");
// 設置標題
th.setTitle(name);
openedPath = null;
opened = false;
} else if (source == exit)
setVisible(false);
else if (source == undo)
try {
//此功能沒有實現 撤銷要用棧?
// undo.setEnabled(undoManager.canUndo());
undoManager.undo();
} catch (CannotRedoException cre) {
cre.printStackTrace();
}
else if (source == selectAll)
text.selectAll();
else if (source == cut)
text.cut();
else if (source == )
text.();
else if (source == paste)
text.paste();
else if (source == lineWrap)
// 設置文本區的換行策略(獲取文本區的換行策略)
text.setLineWrap(!text.getLineWrap());
else if (source == about) {
String message = "--------\n版本:1.0\n作者:時超" +
"\n撤銷功能要用堆棧存貯操作" +
"\n還有字體格式"+
"\n暫時沒有實現" +
"\n\n感謝您的使用";
JOptionPane.showMessageDialog(th, message, "關於",
JOptionPane.PLAIN_MESSAGE);
} else if (source == timeDate) {
Date nowTime = new Date();
SimpleDateFormat times = new SimpleDateFormat(
"HH:mm yyyy-MM-dd");
text.insert(times.format(nowTime), text.getCaretPosition());
}
}
}
class Listen1 implements ActionListener {
// 實現用於對文件進行操作的事件偵聽器
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
// 打開文件事件
if (source == open) {
// 顯示對話窗口 以便選擇文件
FileDialog openFile = new FileDialog(th, "打開文件",
FileDialog.LOAD);
openFile.setVisible(true);
// 獲取文件路徑
String filePath = openFile.getDirectory() + openFile.getFile();
try {
FileInputStream fis = new FileInputStream(filePath);
byte[] content = new byte[fis.available()];
fis.read(content);
text.setText(new String(content));
// 設置 TextComponent 的文本插入符的位置
text.setCaretPosition(0);
if (openFile.getFile() != null) {
th.setTitle(openFile.getFile() + name);
openedPath = filePath;
opened = true;
}
fis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
opened = true;
}
// 保存及另存為事件
else if (source == save || source == saveAs) {
String savePath = openedPath;
if (savePath == null || source == saveAs) {
// 如果 mode 的值為 LOAD,那麼文件對話框將查找要讀取的文件,所顯示的文件是當前目錄中的文件
// 如果 mode 的值為 SAVE,則文件對話框將查找要寫入文件的位置。
FileDialog saveFile = new FileDialog(th, "保存文件",
FileDialog.SAVE);
saveFile.setVisible(true);
savePath = saveFile.getDirectory() + saveFile.getFile();
}
try {
FileOutputStream fos = new FileOutputStream(savePath);
fos.write(text.getText().getBytes());
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if (source == save)
openedPath = savePath;
}
}
}
public static void main(String[] args) {
try {
// 使用當前線程的上下文類載入器載入給定類名稱所指定的 LookAndFeel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Couldn't use the system look and feel:" + e);
}
String name = ("--記事本 版本1.0--");
Notepad note = new Notepad(name);
note.init();
note.setVisible(true);
}
}

㈤ 電腦怎麼用記事本寫Java程序並運行

1. 新建一個記事本,後綴名是  .java  ;然後在裡面寫一段java的代碼,如圖:

2.把寫好的java文件丟進D盤,就是第一步給出的那個class文件;
3. 打開dos界面 開始-〉運行-〉cmd-〉 這個是命令行模式,選擇D盤,如圖:

4.選擇D盤之後,在命令提示符中輸入「javac 文件名.java」,我的文件名為java,所以輸入javac java.java然後回車,等待編譯。這時候你就會發現它提示說javac不是內部文件。接下來就是java環境變數設置的問題了;
5.下載一個jdk執行默認安裝。例如我下的jdk版本是: jdk-6u10-rc2-bin-b32-windows-i586-p-12_sep_2008.exe;
6.配置環境:右擊我的電腦點屬性,進去點高級就能看到環境變數。點進去就能設置你的系統變數了,如圖:

6-1。變數名:classpath    變數值:(.;C:\Program Files\Java\jdk1.6.0_10\lib;)括弧裡面都是 (主要我們在編譯運行程序的時候通過classpath可以幫助我們找到一些需要的系統類,「.」號是表示當前路徑;「;」號是用來隔開多個變數值,如果你的系統裡面已經有classpath環 境變數,就不用新建了,直接加「;」號,在後面加新值);如圖所示

㈥ 使用記事本編寫JAVA程序,並運行輸出結果,具體的實現步驟是什麼

1、首先在電腦中新建一個記事本,將記事本的後綴改為「.java」,如下圖所示。

㈦ 用Java編寫簡易記事本源代碼

importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.Font;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.InputEvent;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjavax.swing.BorderFactory;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPopupMenu;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;importjavax.swing.KeyStroke;importjavax.swing.ScrollPaneConstants;importjavax.swing.SwingConstants;{privateJMenuItemmenuOpen;privateJMenuItemmenuSave;privateJMenuItemmenuSaveAs;privateJMenuItemmenuClose;privateJMenueditMenu;privateJMenuItemmenuCut;privateJMenuItemmenuCopy;privateJMenuItemmenuPaste;privateJMenuItemmenuAbout;privateJTextAreatextArea;privateJLabelstateBar;;privateJPopupMenupopUpMenu;publicJNotePadUI(){super("新建文本文件");setUpUIComponent();setUpEventListener();setVisible(true);}privatevoidsetUpUIComponent(){setSize(640,480);//菜單欄JMenuBarmenuBar=newJMenuBar();//設置「文件」菜單JMenufileMenu=newJMenu("文件");menuOpen=newJMenuItem("打開");//快捷鍵設置menuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));menuSave=newJMenuItem("保存");menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));menuSaveAs=newJMenuItem("另存為");menuClose=newJMenuItem("關閉");menuClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));fileMenu.add(menuOpen);fileMenu.addSeparator();//分隔線fileMenu.add(menuSave);fileMenu.add(menuSaveAs);fileMenu.addSeparator();//分隔線fileMenu.add(menuClose);//設置「編輯」菜單JMenueditMenu=newJMenu("編輯");menuCut=newJMenuItem("剪切");menuCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));menuCopy=newJMenuItem("復制");menuCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));menuPaste=newJMenuItem("粘貼");menuPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));editMenu.add(menuCut);editMenu.add(menuCopy);editMenu.add(menuPaste);//設置「關於」菜單JMenuaboutMenu=newJMenu("關於");menuAbout=newJMenuItem("關於JNotePad");aboutMenu.add(menuAbout);menuBar.add(fileMenu);menuBar.add(editMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//文字編輯區域textArea=newJTextArea();textArea.setFont(newFont("宋體",Font.PLAIN,16));textArea.setLineWrap(true);JScrollPanepanel=newJScrollPane(textArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);ContainercontentPane=getContentPane();contentPane.add(panel,BorderLayout.CENTER);//狀態欄stateBar=newJLabel("未修改");stateBar.setHorizontalAlignment(SwingConstants.LEFT);stateBar.setBorder(BorderFactory.createEtchedBorder());contentPane.add(stateBar,BorderLayout.SOUTH);popUpMenu=editMenu.getPopupMenu();fileChooser=newJFileChooser();}privatevoidsetUpEventListener(){//按下窗口關閉鈕事件處理addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){closeFile();}});//菜單-打開menuOpen.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){openFile();}});//菜單-保存menuSave.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFile();}});//菜單-另存為menuSaveAs.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFileAs();}});//菜單-關閉文件menuClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){closeFile();}});//菜單-剪切menuCut.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){cut();}});//菜單-復制menuCopy.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){();}});//菜單-粘貼menuPaste.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){paste();}});//菜單-關於menuAbout.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){//顯示對話框JOptionPane.showOptionDialog(null,"程序名稱:\nJNotePad\n"+"程序設計:\n\n"+"簡介:\n一個簡單的文字編輯器\n"+"可作為驗收Java的實現對象\n"+"歡迎網友下載研究交流\n\n"+"/","關於JNotePad",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,null,null);}});//編輯區鍵盤事件textArea.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){processTextArea();}});//編輯區滑鼠事件textArea.addMouseListener(newMouseAdapter(){publicvoidmouseReleased(MouseEvente){if(e.getButton()==MouseEvent.BUTTON3)popUpMenu.show(editMenu,e.getX(),e.getY());}publicvoidmouseClicked(MouseEvente){if(e.getButton()==MouseEvent.BUTTON1)popUpMenu.setVisible(false);}});}privatevoidopenFile(){if(isCurrentFileSaved()){//文件是否為保存狀態open();//打開}else{//顯示對話框intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){//確認文件保存caseJOptionPane.YES_OPTION:saveFile();//保存文件break;//放棄文件保存caseJOptionPane.NO_OPTION:open();break;}}}(){if(stateBar.getText().equals("未修改")){returnfalse;}else{returntrue;}}privatevoidopen(){//fileChooser是JFileChooser的實例//顯示文件選取的對話框intoption=fileChooser.showDialog(null,null);//使用者按下確認鍵if(option==JFileChooser.APPROVE_OPTION){try{//開啟選取的文件BufferedReaderbuf=newBufferedReader(newFileReader(fileChooser.getSelectedFile()));//設定文件標題setTitle(fileChooser.getSelectedFile().toString());//清除前一次文件textArea.setText("");//設定狀態欄stateBar.setText("未修改");//取得系統相依的換行字元StringlineSeparator=System.getProperty("line.separator");//讀取文件並附加至文字編輯區Stringtext;while((text=buf.readLine())!=null){textArea.append(text);textArea.append(lineSeparator);}buf.close();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"開啟文件失敗",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFile(){//從標題欄取得文件名稱Filefile=newFile(getTitle());//若指定的文件不存在if(!file.exists()){//執行另存為saveFileAs();}else{try{//開啟指定的文件BufferedWriterbuf=newBufferedWriter(newFileWriter(file));//將文字編輯區的文字寫入文件buf.write(textArea.getText());buf.close();//設定狀態欄為未修改stateBar.setText("未修改");}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"寫入文件失敗",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFileAs(){//顯示文件對話框intoption=fileChooser.showSaveDialog(null);//如果確認選取文件if(option==JFileChooser.APPROVE_OPTION){//取得選擇的文件Filefile=fileChooser.getSelectedFile();//在標題欄上設定文件名稱setTitle(file.toString());try{//建立文件file.createNewFile();//進行文件保存saveFile();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"無法建立新文件",JOptionPane.ERROR_MESSAGE);}}}privatevoidcloseFile(){//是否已保存文件if(isCurrentFileSaved()){//釋放窗口資源,而後關閉程序dispose();}else{intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){caseJOptionPane.YES_OPTION:saveFile();break;caseJOptionPane.NO_OPTION:dispose();}}}privatevoidcut(){textArea.cut();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoid(){textArea.();popUpMenu.setVisible(false);}privatevoidpaste(){textArea.paste();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidprocessTextArea(){stateBar.setText("已修改");}publicstaticvoidmain(String[]args){newJNotePadUI();}}

㈧ 如何用JAVA編寫簡單的記事本程序

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.datatransfer.*;public class NewEdit
{
public static void main(String args[])
{
MyFrame EditFrame=new MyFrame();
EditFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EditFrame.setVisible(true);
}
}class MyFrame extends JFrame
{
public MyFrame()
{ Dimension screenSize=toolKit.getScreenSize();
int screenHeight=screenSize.height;
int screenWidth=screenSize.width;

setSize(screenWidth/2,screenHeight/2);
setLocation(screenWidth/4,screenHeight/4);

Image img=toolKit.getImage("icon.gif");
setIconImage(img);
setTitle("MyEdit");

JMenuBar menuBar=new JMenuBar();
setJMenuBar(menuBar);

JMenu fileMenu=new JMenu("文件");
JMenu editMenu=new JMenu("編輯");
JMenu helpMenu=new JMenu("幫助");
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);

JMenuItem newItem=new JMenuItem("新建");
newItem.addActionListener(new NewListener());

JMenuItem openItem=new JMenuItem("打開");
openItem.addActionListener(new OpenListener());

JMenuItem saveItem=new JMenuItem("保存");
saveItem.addActionListener(new SaveListener());

JMenuItem escItem=new JMenuItem("退出");
escItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent myE)
{
System.exit(0);
}
});

fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(escItem);

JMenuItem allItem=new JMenuItem("全選");
//JMenuItem Item=new JMenuItem("復制");
//CopyAction Action=new CopyAction();
//Item.addActionListener(Action);

JMenuItem cutItem=new JMenuItem("剪切");
//JMenuItem pasteItem=new JMenuItem("粘貼");
//Action pasteAction=new PasteAction();
//pasteItem.addActionListener(pasteAction);

editMenu.add(allItem);
allItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent myE)
{
textArea.selectAll();
}
});

CopyAction Action=new CopyAction("剪切");
editMenu.add(Action);

CutAction cutAction=new CutAction("復制");
editMenu.add(cutAction);

Action pasteAction=new PasteAction("粘貼");
editMenu.add(pasteAction);

popup=new JPopupMenu();
popup.add(Action);
popup.add(pasteAction);
popup.add(cutAction);

textArea = new JTextArea();
textArea.add(popup);

textArea.addMouseListener(new
MouseListener(){
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)
{
popup.show(textArea, e.getX(), e.getY());
}
} public void mouseReleased(MouseEvent e) {} });//可嘗試用MouseAdapter,代碼可能更簡單
JScrollPane scroller = new JScrollPane(textArea);
add(scroller);
//OR--this.getContentPane().add(scroller)
//scroller.setComponentPopupMenu(popup);
//textArea.setInheritsPopupMenu(true);
//scroller.addMouseListener(new MouseAdapter(){});

}

public void writeFile(String fileName)
{
try
{
File file = new File(fileName);
FileWriter write = new FileWriter(file);
write.write(textArea.getText());
write.close();
}
catch(Exception e){
System.out.println("Error closing file!");
}
}

public void openFile(String fileName)
{
try
{
File file = new File(fileName);
FileReader readIn = new FileReader(file);
int size = (int)file.length();
int charsRead = 0;
char[] content = new char[size];
while(readIn.ready())
charsRead += readIn.read(content,charsRead,size-charsRead);
readIn.close();
textArea.setText(new String(content,0,charsRead));
}
catch(IOException e)
{
System.out.println("Error opening file!");
}
}

private class NewListener implements ActionListener
{
public void actionPerformed(ActionEvent myE)
{
textArea.setText("");
}
}

private class OpenListener implements ActionListener
{
public void actionPerformed(ActionEvent myE)
{
openFileDialog.setVisible(true);
fileName = openFileDialog.getDirectory()+openFileDialog.getFile();
if(fileName != null)
{
openFile(fileName);
}
}
}

private class SaveListener implements ActionListener
{
public void actionPerformed(ActionEvent myE)
{
saveFileDialog.setVisible(true);
fileName = saveFileDialog.getDirectory()+saveFileDialog.getFile();
if(fileName !=null)
{
writeFile(fileName);
}
}
}

private class CutAction extends AbstractAction
{
public CutAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
String text = textArea.getSelectedText();
StringSelection selection = new StringSelection(text);

clipboard.setContents(selection,null);
textArea.replaceRange("",textArea.getSelectionStart(),
textArea.getSelectionEnd());
}
}

private class CopyAction extends AbstractAction
{
public CopyAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
String text = textArea.getSelectedText();
StringSelection selection= new StringSelection(text);

clipboard.setContents(selection,null);
}
}

private class PasteAction extends AbstractAction
{
public PasteAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
Transferable contents = clipboard.getContents(this);
if(contents==null)
return;
String text;
text="";
try
{
text = (String)contents.getTransferData(DataFlavor.stringFlavor);
}
catch(Exception ex){}
textArea.replaceRange(text,
textArea.getSelectionStart(),textArea.getSelectionEnd());
}
}

private JTextArea textArea;
private JPopupMenu popup;

private String fileName="";

private FileDialog openFileDialog=new FileDialog(this,"OpenFile",FileDialog.LOAD); private FileDialog saveFileDialog=new FileDialog(this,"SaveFile",FileDialog.SAVE);

Toolkit toolKit = Toolkit.getDefaultToolkit();
private Clipboard clipboard = toolKit.getSystemClipboard();}

㈨ 如何用java的GUI編寫一個記事本

很久之前寫過的,湊合著看吧,

package個人練習;

importjava.awt.FileDialog;
importjava.awt.Menu;
importjava.awt.MenuBar;
importjava.awt.MenuItem;
importjava.awt.TextArea;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
importjava.awt.event.WindowListener;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.io.PrintWriter;
importjava.io.Writer;
importjava.sql.Savepoint;

importjavax.swing.JFrame;
/**
*創建一個類似記事本的程序
*該程序擁有自己的書寫窗口
*可以自定義保存地址
*@authorAdministrator
*
*/
/*
*創建記事本類
*實現ActionListener介面
*重寫它的actionPerformed方法
*
*/
{
//擁有自己的窗口
JFrameframe=newJFrame("記事本程序");
//菜單欄
MenuBarmenubar=newMenuBar();
//創建下拉菜單
Menuwenjian=newMenu("文件");
//創建保存按鈕
MenuItemdakai=newMenuItem("打開文件");
MenuItembaochun=newMenuItem("保存");
MenuItemxinjian=newMenuItem("新建");
//創建可以顯示文本的多行區域
TextAreawenben=newTextArea();
//顯示一個對話窗口,用戶選擇一個文件,如果模式是SAVE,則尋找一個地方去寫入一個文件
FileDialogfd;
Filefile=null;
/*
*創建jishiben的構造函數
*/

publicJiShiBen(){
frame.setMenuBar(menubar);//將菜單欄關聯到窗口
menubar.add(wenjian);//將下拉菜單添加到菜單欄
wenjian.add(xinjian);
wenjian.add(dakai);//將保存按鈕添加到下拉菜單
wenjian.add(baochun);

dakai.addActionListener(this);//由baochuan按鈕接受處理操作事件
baochun.addActionListener(this);
xinjian.addActionListener(this);
frame.add(wenben);//將文本區域添加到窗口
//設置窗口的屬性
frame.setSize(600,480);
frame.setLocation(200,200);
frame.setVisible(true);
/*
*
*用於接收窗口事件的偵聽器介面。
*旨在處理窗口事件的類要麼實現此介面(及其包含的所有方法),
*要麼擴展抽象類WindowAdapter(僅重寫所需的方法)。
*然後使用窗口的addWindowListener方法將從該類所創建
*的偵聽器對象向該Window注冊。
*當通過打開、關閉、激活或停用、
*圖標化或取消圖標化而改變了窗口狀態時,
*將調用該偵聽器對象中的相關方法,
*並將WindowEvent傳遞給該方法。
*windowClosing(WindowEvente)
用戶試圖從窗口的系統菜單中關閉窗口時調用。
*
*/

frame.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
System.exit(0);//終止當前運行的java虛擬機
}
});
}

/*
*實現ActionListener介面中的方法
*(non-Javadoc)
*@seejava.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==baochun){
//publicObjectgetSource()最初發生Event的對象。返回,最初發生Event的對象。
fd=newFileDialog(frame,"保存文本文件",FileDialog.SAVE);
/*
*FileDialog(Dialogparent,Stringtitle,intmode)
創建一個具有指定標題的文件對話框窗口,用於載入或保存文件。

staticintLOAD
此常量值指示文件對話框窗口的作用是查找要讀取的文件。
staticintSAVE
此常量值指示文件對話框窗口的作用是查找要寫入的文件。

*/
fd.setVisible(true);
//文件的存放位置是通過fd獲取的位置,文件名是通過fd獲取的文件名
file=newFile(fd.getDirectory(),fd.getFile()+".txt");
save(file);
}
if(e.getSource()==dakai){
fd=newFileDialog(frame,"打開文件",FileDialog.LOAD);
fd.setVisible(true);
/*
*StringgetFile()
獲取此文件對話框的選定文件。
StringgetDirectory()
獲取此文件對話框的目錄。
*/
file=newFile(fd.getDirectory()+fd.getFile());
System.out.println(fd.getFile());
System.out.println(fd.getDirectory());
open(file);
}
if(e.getSource()==xinjian){
wenben.setText("");
}
}

/*
*創建save方法
*/
publicvoidsave(Filefile){
try{
PrintWriterpw=newPrintWriter(file);
pw.write(wenben.getText());//wenben.getText()返迴文本區域的文本
pw.close();
}catch(Exceptione){
}
}
//創建open方法
publicvoidopen(Filefile){
try{
FileInputStreamfis=newFileInputStream(file);
InputStreamReaderisr=newInputStreamReader(fis);
BufferedReaderbr=newBufferedReader(isr);
Stringline=null;
while((line=br.readLine())!=null){
wenben.append(line+" ");
}
br.close();

}catch(Exceptione){

}
}
publicstaticvoidmain(String[]args){
newJiShiBen();
}


}

㈩ 怎樣用java編寫一個記事本 ,具體步驟!

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;

public class TextEditorFrame extends JFrame {
File file = null;
Color color = Color.red;

TextEditorFrame() {
initTextPane();
initAboutDialog();
initToolBar();
initMenu();
}

void initTextPane() {
getContentPane().add(new JScrollPane(text));
}

JTextPane text = new JTextPane(); // 這是用來做文本框的
JFileChooser filechooser = new JFileChooser(); // 文件選擇框
JColorChooser colorchooser = new JColorChooser();//
JDialog about = new JDialog(this); // 關於對話框
JMenuBar menubar = new JMenuBar();// 菜單

JMenu[] menus = new JMenu[] { new JMenu("文件"), new JMenu("編輯"),
new JMenu("幫助") };

JMenuItem menuitems[][] = new JMenuItem[][] {
{ new JMenuItem("新建"), new JMenuItem("打開"), new JMenuItem("保存"), new JMenuItem("退出") },
{new JMenuItem("復制"), new JMenuItem("剪切"), new JMenuItem("粘貼"), new JMenuItem("顏色") }, { new JMenuItem("關於") } };

void initMenu() {

for (int i = 0; i < menus.length; i++) {
menubar.add(menus[i]);
for (int j = 0; j < menuitems[i].length; j++) {
menus[i].add(menuitems[i][j]);
menuitems[i][j].addActionListener(action);
}
}
this.setJMenuBar(menubar);
}

ActionListener action = new ActionListener() { // when here have not wrong:
public void actionPerformed(ActionEvent e) {
JMenuItem mi = (JMenuItem) e.getSource();
String id = mi.getText();
if (id.equals("新建")) {
text.setText("");
file = null;
} else if (id.equals("打開")) {
if (file != null)
filechooser.setSelectedFile(file);
int returnVal = filechooser
.showOpenDialog(TextEditorFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {

file = filechooser.getSelectedFile();
openFile();
}

} else if (id.equals("保存")) {
if (file != null)
filechooser.setSelectedFile(file);
int returnVal = filechooser
.showSaveDialog(TextEditorFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
saveFile();
}

} else if (id.equals("退出")) {
TextEditorFrame f = new TextEditorFrame();
int s = JOptionPane.showConfirmDialog(f, "你真的要結束嗎", "結束程序",
JOptionPane.YES_NO_CANCEL_OPTION);
if (s == JOptionPane.YES_OPTION)
System.exit(0);
} else if (id.equals("剪切")) {
text.cut();
} else if (id.equals("復制")) {
text.();
} else if (id.equals("粘貼")) {
text.paste();
} else if (id.equals("color")) {
color = JColorChooser.showDialog(TextEditorFrame.this, "",
color);
text.setForeground(color);

} else if (id.equals("關於")) {
about.setSize(200, 150);
about.show();
}

}

};

void saveFile() {
try {
FileWriter fw = new FileWriter(file);
fw.write(text.getText());
fw.close();
} catch (Exception e) {
e.printStackTrace();
}

}

void openFile() {
try {
FileReader fr = new FileReader(file);
int len = (int) file.length();
char[] buffer = new char[len];
fr.read(buffer, 0, len);
fr.close();
text.setText(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
}

}

void initAboutDialog() {
about.getContentPane().add(new JLabel("作者-覃樹新:記事本Q1.0版本"));
about.setModal(true);
about.setSize(200, 100);
}

JToolBar toolbar = new JToolBar();// 我來加上工具條
JButton[] buttons = new JButton[] {
new JButton("", new ImageIcon("qin.jpg")),
new JButton("", new ImageIcon("shu.jpg")),
new JButton("", new ImageIcon("xin.jpg")) };

void initToolBar() {
for (int i = 0; i < buttons.length; i++)
toolbar.add(buttons[i]);
buttons[0].setToolTipText("復制");
buttons[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
text.();
}
});
buttons[1].setToolTipText("剪切");
buttons[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
text.cut();
}
});

buttons[2].setToolTipText("粘貼");
buttons[2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
text.paste();
}
});

this.getContentPane().add(toolbar, BorderLayout.NORTH);
}

public static void main(String args[]) {

TextEditorFrame f = new TextEditorFrame();

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)

{
TextEditorFrame f = new TextEditorFrame();
int s = JOptionPane.showConfirmDialog(f, "你真的要結束嗎", "結束程序",
JOptionPane.YES_NO_OPTION);
if (s == JOptionPane.YES_OPTION)
System.exit(0);
}
});

f.setTitle("簡單的記事本");
f.setSize(800, 600);
f.setVisible(true);
}
}

以前看到的一個程序

閱讀全文

與用java編寫的記事本相關的資料

熱點內容
360pdf閱讀器下載 瀏覽:751
百戰程序員標簽管理視頻 瀏覽:380
朗讀者app會員怎麼下載 瀏覽:269
java讀取單詞 瀏覽:547
android查看網關 瀏覽:419
下載的主題在文件夾中找不到 瀏覽:16
在線攻擊伺服器什麼意思 瀏覽:229
ce怎麼改安卓系統 瀏覽:12
php分頁顯示代碼 瀏覽:911
吃甜的東西緩解壓力 瀏覽:171
有什麼手勢舞app 瀏覽:89
固定收益pdf 瀏覽:409
java排序comparator 瀏覽:500
如何只輸入伺服器上的ip 瀏覽:490
單片機稱號 瀏覽:194
phpsocket並發多少 瀏覽:578
tomcat安裝php 瀏覽:78
clay黏土伺服器怎麼加黏土 瀏覽:765
androidsetcolor 瀏覽:174
手機如何登陸主機伺服器 瀏覽:531