求基础级java代码,150-200行,自己写的
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求基础级java代码,150-200行,自己写的相关的知识,希望对你有一定的参考价值。
求基础级java代码,150-200行,每行附注释
具体项目随便,但必须有一定功能(猜数字等弱智功能就免了),游戏和其他项目皆可.
最重要的是要自己写的,网上随便一搜就搜到的就不要了,我怕与别人的一样。
要有源代码,设计文档,使用方法说明。编个小游戏也行。
有的请看我的百度中心联系方式,那里有邮箱,请发到那.
如果找不到,留下联系方式我会尝试联系你.
好的追加50分
谢谢delong2008的补充,不过该程序太难了,而且长度远远超出要求.
请提供一些基础性较强的,谢谢
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
* 我的计算器。MyCalculator 继承于 JFrame,是计算器的界面
*/
public class Calculator extends JFrame
/**
*
*/
private static final long serialVersionUID = 1L;
private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener()
public void actionPerformed(ActionEvent e)
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
;
public Calculator(String title) throws HeadlessException
super(title); // 调用父类构造方法
setupFrame(); // 调整窗体属性
setupControls(); // 创建控件
private void setupControls()
setupDisplayPanel(); // 创建文本面板
setupButtonsPanel(); // 创建按钮面板
// 创建按钮面板并添加按钮
private void setupButtonsPanel()
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]
"7", "8", "9", "+", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "", // 空字符串表示这个位置没有按钮
"0", ".", "=", "/", ""
);
this.add(panel, BorderLayout.CENTER);
/**
* 在指定的面板上创建按钮
*
* @param panel 要创建按钮的面板
* @param labels 按钮文字
*/
private void createButtons(JPanel panel, String[] labels)
for (String label : labels)
// 如果 label 为空,则表示创建一个空面板。否则创建一个按钮。
if (label.equals(""))
panel.add(new JPanel());
else
JButton b = new JButton(label);
b.addActionListener(listener); // 为按钮添加侦听器
panel.add(b);
// 设置显示面板,用一个文本框来作为计算器的显示部分。
private void setupDisplayPanel()
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
// 调整文本框
private void setupTextbox()
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右对齐
textbox.setEditable(false); // 文本框只读
textbox.setBackground(Color.white); // 文本框背景色为白色
// 调整窗体
private void setupFrame()
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 当窗体关闭时程序结束
this.setLocation(100, 50); // 设置窗体显示在桌面上的位置
this.setSize(300, 200); // 设置窗体大小
this.setResizable(false); // 窗体大小固定
// 程序入口
public static void main(String[] args) throws Exception
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Calculator frame = new Calculator("我的计算器");
frame.setVisible(true); // 在桌面上显示窗体
/**
* 计算器核心逻辑。这个逻辑只能处理 1~2 个数的运算。
*/
class CalculatorCore
private String displayText = "0"; // 要显示的文本
boolean reset = true;
int MaxLen = 30;
private BigDecimal number1, number2;
private String operator;
private HashMap<String, Operator> operators = new HashMap<String, Operator>();
private HashMap<String, Processor> processors = new HashMap<String, Processor>();
CalculatorCore()
setupOperators();
setupProcessors();
// 为每种命令添加处理方式
private void setupProcessors()
processors.put("[0-9]", new Processor()
public void calculate(String command)
numberClicked(command);
);
processors.put("\\.", new Processor()
public void calculate(String command)
dotClicked();
);
processors.put("=", new Processor()
public void calculate(String command)
equalsClicked();
);
processors.put("[+\\-*/]", new Processor()
public void calculate(String command)
operatorClicked(command);
);
processors.put("C", new Processor()
public void calculate(String command)
clearClicked();
);
processors.put("CE", new Processor()
public void calculate(String command)
clearErrorClicked();
);
// 为每种 operator 添加处理方式
private void setupOperators()
operators.put("+", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.add(number2);
);
operators.put("-", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.subtract(number2);
);
operators.put("*", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.multiply(number2);
);
operators.put("/", new Operator()
public BigDecimal process(BigDecimal number1, BigDecimal number2)
return number1.divide(number2, 30, RoundingMode.HALF_UP);
);
// 根据命令处理。这里的命令实际上就是按钮文本。
public String process(String command)
for (String pattern : processors.keySet())
if (command.matches(pattern))
processors.get(pattern).calculate(command);
break;
return displayText;
// 当按下 CE 时
private void clearErrorClicked()
if (operator == null)
number1 = null;
else
number2 = null;
displayText = "0";
reset = true;
// 当按下 C 时,将计算器置为初始状态。
private void clearClicked()
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
// 当按下 = 时
private void equalsClicked()
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
// 计算结果
/**
*
*/
private void calculateResult()
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null)
try
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
catch (RuntimeException e)
clearClicked();//将计算器置为初始状态
JOptionPane.showMessageDialog(null,"不能用零作除数","出错了",JOptionPane.OK_OPTION);
//e.printStackTrace();
// 当按下 +-*/ 时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command)
if (operator != null)
calculateResult();
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
// 当按下 . 时
private void dotClicked()
if (displayText.indexOf(".") == -1)
displayText += ".";
else if (reset)
displayText = "0.";
reset = false;
// 当按下 0-9 时
private void numberClicked(String command)
if (reset)
displayText = command;
else
if(displayText.length()< MaxLen)
displayText += command;
else
JOptionPane.showMessageDialog(null,"输入的数字太长了","出错了",JOptionPane.OK_OPTION);
reset = false;
// 运算符处理接口
interface Operator
BigDecimal process(BigDecimal number1, BigDecimal number2);
// 按钮处理接口
interface Processor
void calculate(String command);
参考技术A import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ReferInfo implements ActionListener
private TextField userName;
private TextField userPassword;
private TextField affirmPassword;
private TextField userCheck;
private MyDialog subDialog;
public void setUserName(TextField userName)
this.userName=userName;
public void setUserPassword(TextField userPassword)
this.userPassword=userPassword;
public void setAffirmPassword(TextField affirmPassword)
this.affirmPassword=affirmPassword;
public void setUserCheck(TextField userCheck)
this.userCheck=userCheck;
public void setSubDialog(MyDialog subDialog)
this.subDialog=subDialog;
private AchieveInfo achieveInfo=new AchieveInfo();
private static ReferInfo referInfo=new ReferInfo();
public static void main(String []args)
int lengthSize=260;
int widthSize=180;
Frame frame=new SubFrame("窗口");
inputInfo(frame);
referInfo.subDialog=new MyDialog(frame,"Error",true);
frame.setBackground(Color.pink);
frame.setSize(lengthSize,widthSize);
frame.setVisible(true);
public static void inputInfo(Frame frame)
int rows=5;
int columns=2;
String buttonValue="提交";
String validateValue="看不清,换一张!";
String validateCode=CheckNumber();
Button validateButton=new Button(validateValue);
validateButton.setBackground(Color.pink);
TextField labelRandomNumber=new TextField(validateCode);
validateButton.addActionListener(new MyActionListener(labelRandomNumber));
Panel panelUp=new Panel();
Panel panelDown=new Panel();
Label labelName=new Label("姓名");
Label labelPass=new Label("密码");
Label labelAffirmPass=new Label("确认密码");
Label labelCheck=new Label("请输入验正码");
panelUp.setLayout(new GridLayout(rows,columns));
referInfo.setUserName(new TextField());
referInfo.setUserPassword(new TextField());
referInfo.setAffirmPassword(new TextField());
referInfo.setUserCheck(new TextField());
panelUp.add(labelName);
panelUp.add(referInfo.userName);
panelUp.add(labelPass);
panelUp.add(referInfo.userPassword);
panelUp.add(labelAffirmPass);
panelUp.add(referInfo.affirmPassword);
panelUp.add(validateButton);
panelUp.add(labelRandomNumber);
panelUp.add(labelCheck);
panelUp.add(referInfo.userCheck);
Button button=new Button(buttonValue);
button.addActionListener(referInfo);
button.setBackground(Color.lightGray);
panelDown.add(button);
frame.add("Center",panelUp);
frame.add("South",panelDown);
public static String CheckNumber()
int charLength=12;
char charName[]=new char[charLength];
for(int i=0;i<charName.length;)
char min='0';
char max='9';
char lowerNumberMin='a';
char lowerNumberMax='z';
char upperNumberMin='A';
char upperNumberMax='Z';
char roundVar=(char)(Math.random()*256);
boolean isSuccess=(roundVar>=min&&roundVar<=max)||
(roundVar>=lowerNumberMin&&roundVar<=lowerNumberMax)||
(roundVar>=upperNumberMin&&roundVar<=upperNumberMax);
if(isSuccess)
charName[i]=roundVar;
i++;
String inceptNumber=new String(charName);
return inceptNumber;
public void actionPerformed(ActionEvent e)
boolean isSuccessPass=!(affirmPassword.getText()).equals(userPassword.getText());
boolean isSuccessValidate=(userCheck.getText()).equals(userCheck.getText());
if(isSuccessPass||isSuccessValidate)
subDialog.setVisible(true);
else
achieveInfo.setNamep(userName.getText());
achieveInfo.setPassp(userPassword.getText());
achieveInfo.setDefoult(affirmPassword.getText());
System.out.println(achieveInfo);
;
class AchieveInfo
private String personName;
private String personPassword;
private String affirmPassword;
private String affirmValidate;
public void setNamep(String name)
this.personName=name;
public void setPassp(String password)
this.personPassword=password;
public void setDefoult(String defoult)
this.affirmPassword=defoult;
public void setValidate(String affirmValidate)
this.affirmValidate=affirmValidate;
public String toString()
String returnMenu=" 提交信息如下 ";
String returnInfo="\n姓名: "+personName+"\n密码: "+personPassword
+"\n确认密码:"+affirmPassword+"\n验证码:"+affirmValidate;
return returnMenu+returnInfo;
;
class MyDialog extends Dialog//提示错误框
private int widthSize=200;
private int lengthSize=60;
private static final long serialVersionUID =2L;
public MyDialog(Frame owner,String title,boolean modal)
super(owner,title,modal);
setSize(widthSize,lengthSize);
setBackground(Color.yellow);
add(new Label("输入的密码或验证码不对!"));
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
setVisible(false);
System.exit(0);
);
;
class MyActionListener implements ActionListener
private String validate;
private TextField labelRandomNumber;
MyActionListener(TextField labelRandomNumber )
this.labelRandomNumber=labelRandomNumber;
public void actionPerformed(ActionEvent arg0)
String validate=ReferInfo.CheckNumber();
labelRandomNumber.setText(validate);
public String getValidate()
return validate;
class SubFrame extends Frame//Frame窗口关闭事件
private static final long serialVersionUID =1L;
public SubFrame(String name)
super(name);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
setVisible(false);
System.exit(0);
);
; 参考技术B 读取文件
import java.awt.Toolkit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Dimension;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class Reader
boolean packFrame = false;
/**
* Construct and show the application.
*/
public Reader()
readframe frame = new readframe();
// Validate frames that have preset sizes
// Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame)
frame.pack();
else
frame.validate();
// Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height)
frameSize.height = screenSize.height;
if (frameSize.width > screenSize.width)
frameSize.width = screenSize.width;
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
/**
* Application entry point.
*
* @param args String[]
*/
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
public void run()
try
UIManager.setLookAndFeel(UIManager.
getSystemLookAndFeelClassName());
catch (Exception exception)
exception.printStackTrace();
new Reader();
);
package read;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class readframe extends JFrame
JPanel contentPane;
String path;
JTextArea txtShow = new JTextArea();
JTextField txtPath = new JTextField();
JButton butLj = new JButton();
JLabel jLabel1 = new JLabel();
JButton jButton2 = new JButton();
public readframe()
try
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
catch (Exception exception)
exception.printStackTrace();
/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(459, 430));
setTitle("读取");
txtShow.setText("");
txtShow.setBounds(new Rectangle(26, 31, 404, 250));
txtShow.setLineWrap(true);
txtPath.setText("");
txtPath.setBounds(new Rectangle(73, 298, 249, 33));
butLj.setBounds(new Rectangle(334, 299, 90, 32));
butLj.setText("浏览");
butLj.addActionListener(new readframe_butLj_actionAdapter(this));
jLabel1.setText("路径");
jLabel1.setBounds(new Rectangle(14, 299, 55, 37));
jButton2.setBounds(new Rectangle(103, 349, 249, 39));
jButton2.setActionCommand("butOK");
jButton2.setText("读取");
jButton2.addActionListener(new readframe_jButton2_actionAdapter(this));
contentPane.add(txtShow);
contentPane.add(txtPath);
contentPane.add(butLj);
contentPane.add(jLabel1);
contentPane.add(jButton2);
public void butLj_actionPerformed(ActionEvent e)
JFileChooser lj=new JFileChooser();
lj.showOpenDialog(this);
File a=new File(lj.getSelectedFile().getPath());
path=a.toString();
txtPath.setText(path);
public void jButton2_actionPerformed(ActionEvent e)
try
FileReader fr=new FileReader(path);
BufferedReader dr=new BufferedReader(fr);
String line=dr.readLine();
while(line!=null)
txtShow.append(line+'\n');
line=dr.readLine();
catch(IOException ee)
class readframe_butLj_actionAdapter implements ActionListener
private readframe adaptee;
readframe_butLj_actionAdapter(readframe adaptee)
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e)
adaptee.butLj_actionPerformed(e);
class readframe_jButton2_actionAdapter implements ActionListener
private readframe adaptee;
readframe_jButton2_actionAdapter(readframe adaptee)
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e)
adaptee.jButton2_actionPerformed(e);
参考技术C 150-200 行做不出游戏的啊,我是Java程序员,你加我的q 695520848 需要什么代码,我给你现写。呵呵本回答被提问者采纳
求:用java写的记事本的代码...
是要能编辑文字的那一部分... 谢谢
参考技术A color.addActionListener(new ActionListener()public void actionPerformed(ActionEvent e)
JColorChooser jColor = new JColorChooser(); // 调用颜色面板,设置前景就可更改字体颜色
Color fcolor = ja.getForeground(); //得到前景色
ja.setForeground(jColor.showDialog(ja, "选择字体颜色", fcolor)); //设置前景色
);
cancel.addActionListener(new ActionListener() //为取消按钮添加临听器
public void actionPerformed(ActionEvent e)
fontMain.setVisible(false); //当事件触发,把fontMain设为隐藏
);
ok.addActionListener(new ActionListener() //为确定按钮添加临听器
public void actionPerformed(ActionEvent e)
fontMain.setVisible(false); //当事件触发,把fontMain设为隐藏
);
font.addActionListener(new ActionListener() //为font按钮添加临听器
public void actionPerformed(ActionEvent e)
fontJd.setLocationRelativeTo(NewProgram.this); //设定fontJd的位置
fontJd.setVisible(true); //使fontJd为可见
int style = 0;
if (fontShape.getSelectedItem().equals("常规") == true) //以下为设置字体的代码
style = Font.PLAIN; // 将style设置为常规字形保存
if (fontShape.getSelectedItem().equals("斜体") == true)
style = Font.ITALIC;
if (fontShape.getSelectedItem().equals("粗体") == true)
style = Font.BOLD;
if (fontShape.getSelectedItem().equals("粗斜体") == true)
style = Font.BOLD + Font.ITALIC;
// 设置字体大小的 //字号
String[] size = "1", "2", "3", "4", "5", "6", "7", "8", "9",
"10" ;
for (int i = 0; i < size.length; i++)
if (sizeList.getSelectedItem().equals(size[i]) == true) //设置字体字号
ja.setFont(new Font(String.valueOf(fontList
.getSelectedItem()), style, (10 - i) * 10));
fontJd.dispose();
;
请参考 参考技术B 我只知道李刚的java讲义里有这个例子
,伱百度一下肯定有 参考技术C 什么意思 参考技术D import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.BorderFactory;
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.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
public class JNotePadUI extends JFrame
private JMenuItem menuOpen;
private JMenuItem menuSave;
private JMenuItem menuSaveAs;
private JMenuItem menuClose;
private JMenu editMenu;
private JMenuItem menuCut;
private JMenuItem menuCopy;
private JMenuItem menuPaste;
private JMenuItem menuAbout;
private JTextArea textArea;
private JLabel stateBar;
private JFileChooser fileChooser;
private JPopupMenu popUpMenu;
public JNotePadUI()
super("新建文本文件");
setUpUIComponent();
setUpEventListener();
setVisible(true);
private void setUpUIComponent()
setSize(640, 480);
// 菜单栏
JMenuBar menuBar = new JMenuBar();
// 设置「文件」菜单
JMenu fileMenu = new JMenu("文件");
menuOpen = new JMenuItem("打开");
// 快捷键设置
menuOpen.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_O,
InputEvent.CTRL_MASK));
menuSave = new JMenuItem("保存");
menuSave.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_S,
InputEvent.CTRL_MASK));
menuSaveAs = new JMenuItem("另存为");
menuClose = new JMenuItem("关闭");
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);
// 设置「编辑」菜单
JMenu editMenu = new JMenu("编辑");
menuCut = new JMenuItem("剪切");
menuCut.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_X,
InputEvent.CTRL_MASK));
menuCopy = new JMenuItem("复制");
menuCopy.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_C,
InputEvent.CTRL_MASK));
menuPaste = new JMenuItem("粘贴");
menuPaste.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_V,
InputEvent.CTRL_MASK));
editMenu.add(menuCut);
editMenu.add(menuCopy);
editMenu.add(menuPaste);
// 设置「关于」菜单
JMenu aboutMenu = new JMenu("关于");
menuAbout = new JMenuItem("关于JNotePad");
aboutMenu.add(menuAbout);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
setJMenuBar(menuBar);
// 文字编辑区域
textArea = new JTextArea();
textArea.setFont(new Font("宋体", Font.PLAIN, 16));
textArea.setLineWrap(true);
JScrollPane panel = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
Container contentPane = getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
// 状态栏
stateBar = new JLabel("未修改");
stateBar.setHorizontalAlignment(SwingConstants.LEFT);
stateBar.setBorder(
BorderFactory.createEtchedBorder());
contentPane.add(stateBar, BorderLayout.SOUTH);
popUpMenu = editMenu.getPopupMenu();
fileChooser = new JFileChooser();
private void setUpEventListener()
// 按下窗口关闭钮事件处理
addWindowListener(
new WindowAdapter()
public void windowClosing(WindowEvent e)
closeFile();
);
// 菜单 - 打开
menuOpen.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
openFile();
);
// 菜单 - 保存
menuSave.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
saveFile();
);
// 菜单 - 另存为
menuSaveAs.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
saveFileAs();
);
// 菜单 - 关闭文件
menuClose.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
closeFile();
);
// 菜单 - 剪切
menuCut.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
cut();
);
// 菜单 - 复制
menuCopy.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
copy();
);
// 菜单 - 粘贴
menuPaste.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
paste();
);
// 菜单 - 关于
menuAbout.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent e)
// 显示对话框
JOptionPane.showOptionDialog(null,
"程序名称:\n JNotePad \n" +
"程序设计:\n \n" +
"简介:\n 一个简单的文字编辑器\n" +
" 可作为验收Java的实现对象\n" +
" 欢迎网友下载研究交流\n\n" +
" /",
"关于JNotePad",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null, null, null);
);
// 编辑区键盘事件
textArea.addKeyListener(
new KeyAdapter()
public void keyTyped(KeyEvent e)
processTextArea();
);
// 编辑区鼠标事件
textArea.addMouseListener(
new MouseAdapter()
public void mouseReleased(MouseEvent e)
if(e.getButton() == MouseEvent.BUTTON3)
popUpMenu.show(editMenu, e.getX(), e.getY());
public void mouseClicked(MouseEvent e)
if(e.getButton() == MouseEvent.BUTTON1)
popUpMenu.setVisible(false);
);
private void openFile()
if(isCurrentFileSaved()) // 文件是否为保存状态
open(); // 打开
else
// 显示对话框
int option = JOptionPane.showConfirmDialog(
null, "文件已修改,是否保存?",
"保存文件?", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null);
switch(option)
// 确认文件保存
case JOptionPane.YES_OPTION:
saveFile(); // 保存文件
break;
// 放弃文件保存
case JOptionPane.NO_OPTION:
open();
break;
private boolean isCurrentFileSaved()
if(stateBar.getText().equals("未修改"))
return false;
else
return true;
private void open()
// fileChooser 是 JFileChooser 的实例
// 显示文件选取的对话框
int option = fileChooser.showDialog(null, null);
// 使用者按下确认键
if(option == JFileChooser.APPROVE_OPTION)
try
// 开启选取的文件
BufferedReader buf =
new BufferedReader(
new FileReader(
fileChooser.getSelectedFile()));
// 设定文件标题
setTitle(fileChooser.getSelectedFile().toString());
// 清除前一次文件
textArea.setText("");
// 设定状态栏
stateBar.setText("未修改");
// 取得系统相依的换行字符
String lineSeparator = System.getProperty("line.separator");
// 读取文件并附加至文字编辑区
String text;
while((text = buf.readLine()) != null)
textArea.append(text);
textArea.append(lineSeparator);
buf.close();
catch(IOException e)
JOptionPane.showMessageDialog(null, e.toString(),
"开启文件失败", JOptionPane.ERROR_MESSAGE);
private void saveFile()
// 从标题栏取得文件名称
File file = new File(getTitle());
// 若指定的文件不存在
if(!file.exists())
// 执行另存为
saveFileAs();
else
try
// 开启指定的文件
BufferedWriter buf =
new BufferedWriter(
new FileWriter(file));
// 将文字编辑区的文字写入文件
buf.write(textArea.getText());
buf.close();
// 设定状态栏为未修改
stateBar.setText("未修改");
catch(IOException e)
JOptionPane.showMessageDialog(null, e.toString(),
"写入文件失败", JOptionPane.ERROR_MESSAGE);
private void saveFileAs()
// 显示文件对话框
int option = fileChooser.showSaveDialog(null);
// 如果确认选取文件
if(option == JFileChooser.APPROVE_OPTION)
// 取得选择的文件
File file = fileChooser.getSelectedFile();
// 在标题栏上设定文件名称
setTitle(file.toString());
try
// 建立文件
file.createNewFile();
// 进行文件保存
saveFile();
catch(IOException e)
JOptionPane.showMessageDialog(null, e.toString(),
"无法建立新文件", JOptionPane.ERROR_MESSAGE);
private void closeFile()
// 是否已保存文件
if(isCurrentFileSaved())
// 释放窗口资源,而后关闭程序
dispose();
else
int option = JOptionPane.showConfirmDialog(
null, "文件已修改,是否保存?",
"保存文件?", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null);
switch(option)
case JOptionPane.YES_OPTION:
saveFile();
break;
case JOptionPane.NO_OPTION:
dispose();
private void cut()
textArea.cut();
stateBar.setText("已修改");
popUpMenu.setVisible(false);
private void copy()
textArea.copy();
popUpMenu.setVisible(false);
private void paste()
textArea.paste();
stateBar.setText("已修改");
popUpMenu.setVisible(false);
private void processTextArea()
stateBar.setText("已修改");
public static void main(String[] args)
new JNotePadUI();
本回答被提问者采纳
以上是关于求基础级java代码,150-200行,自己写的的主要内容,如果未能解决你的问题,请参考以下文章