1、首先在電腦中新建一個(gè)記事本,將記事本的后綴改為“.java”,如下圖所示。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專(zhuān)注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、重慶小程序開(kāi)發(fā)公司、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了樺甸免費(fèi)建站歡迎大家使用!
2、然后使用記事本的方式打開(kāi),輸入java程序代碼,如下圖所示。
3、接著在鍵盤(pán)上按“win+R”快捷鍵鍵打開(kāi)運(yùn)行,輸入“cmd”,如下圖所示。
4、在命令行輸入“D:”,按“Enter”鍵進(jìn)去D盤(pán),再輸入“cd Desktop”進(jìn)去Desktop文件夾,如下圖所示。
5、最后再輸入“javac Test.java”,按“Enter”鍵編譯java程序,如下圖所示就完成了。
方法/步驟
下載JDK,并安裝成功,CMD測(cè)試Java環(huán)境安裝成功。出現(xiàn)如下提示則Java環(huán)境安裝成功
打開(kāi)mycelipse進(jìn)入主界面,點(diǎn)擊左上角file--new---java project,新建一個(gè)Java項(xiàng)目,項(xiàng)目名字任意取,這里我取名為note--然后點(diǎn)擊完成,創(chuàng)建Java項(xiàng)目
然后右鍵項(xiàng)目下的src--new---package,新建一個(gè)包,包名我定為notetest,然后點(diǎn)擊完成
然后右鍵我們建立好的包notetest--new--class,包名為Note,點(diǎn)擊完成
首先我們想導(dǎo)入工程所需要的包,以便編寫(xiě)程序時(shí)進(jìn)行調(diào)用
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;
首先定義好編寫(xiě)程序時(shí)變量,我們?cè)O(shè)為成員變量方便以后調(diào)用
public class Notepad{
//屏幕分辨率
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
//窗體
private Frame frm ;
//顯示內(nèi)容多行文本
private TextArea notetext;
//記事本菜單
private MenuBar mb;
//菜單
private Menu m ;
//菜單項(xiàng)
private MenuItem open,save;
為程序創(chuàng)建組件--Frame--菜單欄目--文本框TextArea
public Notepad(){init();}
private void init(){
frm = new Frame("模擬記事本");
//設(shè)置菜單
mb = new MenuBar();
m = new Menu("文件");
//顯示文件的地方
notetext = new TextArea();
notetext.setBounds(30, 50, 750, 500);
frm.add(notetext);
myEvent();
為控件和按鈕添加監(jiān)聽(tīng)事件
private void myEvent() {
//打開(kāi)菜單的事件處理
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//判斷路徑和文件名是否為空 如果為空結(jié)束程序
if(dir == null || name == null)
//如果不為空講路徑名和文件名封裝到File對(duì)象里
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對(duì)象里
file = new File(dir,name);
}
BufferedWriter bfr= null;
}
});
}
}
然后創(chuàng)建主方法,開(kāi)始測(cè)試程序,新建一個(gè)NoteDemo類(lèi)
package notepad;
public class NoteDemo {
public static void main(String[] args) {
new Notepad();
}
}
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;publicclassJNotePadUIextendsJFrame{privateJMenuItemmenuOpen;privateJMenuItemmenuSave;privateJMenuItemmenuSaveAs;privateJMenuItemmenuClose;privateJMenueditMenu;privateJMenuItemmenuCut;privateJMenuItemmenuCopy;privateJMenuItemmenuPaste;privateJMenuItemmenuAbout;privateJTextAreatextArea;privateJLabelstateBar;privateJFileChooserfileChooser;privateJPopupMenupopUpMenu;publicJNotePadUI(){super("新建文本文件");setUpUIComponent();setUpEventListener();setVisible(true);}privatevoidsetUpUIComponent(){setSize(640,480);//菜單欄JMenuBarmenuBar=newJMenuBar();//設(shè)置「文件」菜單JMenufileMenu=newJMenu("文件");menuOpen=newJMenuItem("打開(kāi)");//快捷鍵設(shè)置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("關(guān)閉");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);//設(shè)置「編輯」菜單JMenueditMenu=newJMenu("編輯");menuCut=newJMenuItem("剪切");menuCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));menuCopy=newJMenuItem("復(fù)制");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);//設(shè)置「關(guān)于」菜單JMenuaboutMenu=newJMenu("關(guān)于");menuAbout=newJMenuItem("關(guān)于JNotePad");aboutMenu.add(menuAbout);menuBar.add(fileMenu);menuBar.add(editMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//文字編輯區(qū)域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);//狀態(tài)欄stateBar=newJLabel("未修改");stateBar.setHorizontalAlignment(SwingConstants.LEFT);stateBar.setBorder(BorderFactory.createEtchedBorder());contentPane.add(stateBar,BorderLayout.SOUTH);popUpMenu=editMenu.getPopupMenu();fileChooser=newJFileChooser();}privatevoidsetUpEventListener(){//按下窗口關(guān)閉鈕事件處理addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){closeFile();}});//菜單-打開(kāi)menuOpen.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){openFile();}});//菜單-保存menuSave.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFile();}});//菜單-另存為menuSaveAs.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFileAs();}});//菜單-關(guān)閉文件menuClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){closeFile();}});//菜單-剪切menuCut.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){cut();}});//菜單-復(fù)制menuCopy.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){copy();}});//菜單-粘貼menuPaste.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){paste();}});//菜單-關(guān)于menuAbout.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){//顯示對(duì)話框JOptionPane.showOptionDialog(null,"程序名稱:\nJNotePad\n"+"程序設(shè)計(jì):\n\n"+"簡(jiǎn)介:\n一個(gè)簡(jiǎn)單的文字編輯器\n"+"可作為驗(yàn)收J(rèn)ava的實(shí)現(xiàn)對(duì)象\n"+"歡迎網(wǎng)友下載研究交流\n\n"+"/","關(guān)于JNotePad",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,null,null);}});//編輯區(qū)鍵盤(pán)事件textArea.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){processTextArea();}});//編輯區(qū)鼠標(biāo)事件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()){//文件是否為保存狀態(tài)open();//打開(kāi)}else{//顯示對(duì)話框intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){//確認(rèn)文件保存caseJOptionPane.YES_OPTION:saveFile();//保存文件break;//放棄文件保存caseJOptionPane.NO_OPTION:open();break;}}}privatebooleanisCurrentFileSaved(){if(stateBar.getText().equals("未修改")){returnfalse;}else{returntrue;}}privatevoidopen(){//fileChooser是JFileChooser的實(shí)例//顯示文件選取的對(duì)話框intoption=fileChooser.showDialog(null,null);//使用者按下確認(rèn)鍵if(option==JFileChooser.APPROVE_OPTION){try{//開(kāi)啟選取的文件BufferedReaderbuf=newBufferedReader(newFileReader(fileChooser.getSelectedFile()));//設(shè)定文件標(biāo)題setTitle(fileChooser.getSelectedFile().toString());//清除前一次文件textArea.setText("");//設(shè)定狀態(tài)欄stateBar.setText("未修改");//取得系統(tǒng)相依的換行字符StringlineSeparator=System.getProperty("line.separator");//讀取文件并附加至文字編輯區(qū)Stringtext;while((text=buf.readLine())!=null){textArea.append(text);textArea.append(lineSeparator);}buf.close();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"開(kāi)啟文件失敗",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFile(){//從標(biāo)題欄取得文件名稱Filefile=newFile(getTitle());//若指定的文件不存在if(!file.exists()){//執(zhí)行另存為saveFileAs();}else{try{//開(kāi)啟指定的文件BufferedWriterbuf=newBufferedWriter(newFileWriter(file));//將文字編輯區(qū)的文字寫(xiě)入文件buf.write(textArea.getText());buf.close();//設(shè)定狀態(tài)欄為未修改stateBar.setText("未修改");}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"寫(xiě)入文件失敗",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFileAs(){//顯示文件對(duì)話框intoption=fileChooser.showSaveDialog(null);//如果確認(rèn)選取文件if(option==JFileChooser.APPROVE_OPTION){//取得選擇的文件Filefile=fileChooser.getSelectedFile();//在標(biāo)題欄上設(shè)定文件名稱setTitle(file.toString());try{//建立文件file.createNewFile();//進(jìn)行文件保存saveFile();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"無(wú)法建立新文件",JOptionPane.ERROR_MESSAGE);}}}privatevoidcloseFile(){//是否已保存文件if(isCurrentFileSaved()){//釋放窗口資源,而后關(guān)閉程序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);}privatevoidcopy(){textArea.copy();popUpMenu.setVisible(false);}privatevoidpaste(){textArea.paste();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidprocessTextArea(){stateBar.setText("已修改");}publicstaticvoidmain(String[]args){newJNotePadUI();}}
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("打開(kāi)");
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 copyItem=new JMenuItem("復(fù)制");
//CopyAction copyAction=new CopyAction();
//copyItem.addActionListener(copyAction);
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 copyAction=new CopyAction("剪切");
editMenu.add(copyAction);
CutAction cutAction=new CutAction("復(fù)制");
editMenu.add(cutAction);
Action pasteAction=new PasteAction("粘貼");
editMenu.add(pasteAction);
popup=new JPopupMenu();
popup.add(copyAction);
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,代碼可能更簡(jiǎn)單
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();}