刚刚看完Swing,决定使用Swing编写一个记事本程序,也算是对之前学习的内容的一个复习和总结吧。下面把遇到的问题给贴出来,查漏补缺。
1,Font的style(字体风格)有四个静态值:
- Font.PLAIN 普通
- Font.BOLD 加粗
- Font.ITALIC 斜体
2,JFrame的setDefaultCloseOperation()是设置用户在此窗体上发起 "close" 时默认执行的操作。必须指定以下选项之一:
- DO_NOTHING_ON_CLOSE(在 WindowConstants 中定义):不执行任何操作;要求程序在已注册的 WindowListener 对象的 windowClosing 方法中处理该操作。
- HIDE_ON_CLOSE(在 WindowConstants 中定义):调用任意已注册的 WindowListener 对象后自动隐藏该窗体。
- DISPOSE_ON_CLOSE(在 WindowConstants 中定义):调用任意已注册 WindowListener 的对象后自动隐藏并释放该窗体。
- EXIT_ON_CLOSE(在 JFrame 中定义):使用 System exit 方法退出应用程序。仅在应用程序中使用。
默认情况下,该值被设置为 HIDE_ON_CLOSE
3,从2的解答可以看出这样设置并不能实现在退出时提示保存的问题,百度后说是在JFrame上添加一个window监听器。
addWindowListener (new WindowAdapter ()
{
@Override
public void windowClosing ( WindowEvent e )
{
int exi = JOptionPane.showConfirmDialog (null, "要退出该程序吗?", "友情提示", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (exi == JOptionPane.YES_OPTION)
{
System.exit (0);
}
else
{
return;
}
}
});
4,JFileChooser怎么指定文件类型。
通过JFileChooser包下的FileFilter可以进行筛选,其中的getDescription()方法可以提供描述。
参考自:[JFileChooser文件类型筛选](http://blog.csdn.net/my_yang/article/details/9105593)
5,java如何关闭某JFrame窗口,而不是退出整个程序
- 通过修改DefaultCloseOperation的参数为DISPOSE_ON_CLOSE,但是我发现这种方法并不能会导致程序无法退出,即使窗口全部关闭,虚拟机依然运行在后台。
- 通过window监听器,检测到关闭窗口时,使用dispose方法释放窗口资源,再判断窗口数量,如窗口数为0,则退出程序。
- window监听器方法的参数作用:
- windowOpened 打开后
- windowClosing 关闭时
- windowClosed 关闭后
- windowActivated 激活时
- windowDeactivated 失去焦点时
- windowIconified 最小化
- windowDeiconified 还原
参考自:[Java事件类型小结](http://blog.sina.com.cn/s/blog_4979ec3e010166xf.html)
6,如何监测JTextArea的变动以判断是否需要保存。
通过textArea.getDocument().addDocumentListener()方法可实现检测JTextArea的改动。
- remove 删除时
- insert 键入时
- change 改变属性时会通知
注:发现还有一个TextEvent用于检测文本改动,应该也可以
7,确认对话框的“是”“否”“取消”的值:0,1,2
关闭窗口按钮返回-1
8,监测窗口大小变化以动态改变组件的大小和位置
通过ComponentListener监测器进行判断
- componentMoved 组件移动时
- componentHidden 组件隐藏时
- **componentResized** 组建缩放时
- componentShown 组件显示时
9,JFileChooser的一些常量:
- mode参数:
- FILES_AND_DIRECTORIES 指示显示文件和目录。
- FILES_ONLY 指示仅显示文件。
- DIRECTORIES_ONLY 指示仅显示目录。
- APPROVE_OPTION 选择确认(yes、ok)后返回该值。
- CANCEL_OPTION 选择 cancel 后的返回该值。
10,System.getProperty("line.separator")用于获取换行符,根据操作系统的不同可以获取不同的换行符
11,快捷键的设置:
使用public void setAccelerator(KeyStroke keyStroke)方法设置快捷键,KeyStroke通过getKeyStroke(int, int)静态方法来获取值。
现在方法一个问题,那就是设置的热键与DocumentListener冲突,不知道怎么解决。最后发现是我加了一个调试节点,唉,鼠标要换了
12,自动换行问题,1,使用void setLineWrap(boolean wrap)设置自动换行。2,菜单栏上的对勾设置,使用JCheckMenuItem。
13,使用CaretListener监测光标的位置以动态改变状态栏的值
就这样吧,已经实现了大部分功能,还有查找,替换,转到,设置没有实现,但除了设置可能会遇到难点外,其他的都是前面代码的重组,就不再花时间去写了。
package com.tonglee.Test14;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;
import javax.security.auth.kerberos.KerberosKey;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager;
public class Notepad extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private static int windowsNum = 0;
private JPanel panelEnd;
private boolean isSaved = true;
private UndoManager undomanager = new UndoManager();
private File file = null;
private JMenuItem jmiCreate, jmiOpen, jmiSave, jmiSaveAs, jmiExit, jmiCut, jmiPaste, jmiCopy, jmiSelectAll,jmiInsertTime, jmiSet,
jmiUndo, jmiRedo, jmiAutoEnter, jmiFont, jmiStatus, jmiTopic, jmiAbout;
private JTextArea ta = new JTextArea();
private JLabel labelTips, labelLine, labelColumn, labelNum;
private JFileChooser chooser = new JFileChooser();
public Notepad() {
// TODO Auto-generated constructor stub
// 设置窗口大小
setSize(800, 600);
// 设置窗体的标题
setTitle("无标题 - 记事本");
// 设置窗口的关闭时的响应,此处设置的是释放本窗口资源但不推出程序
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// 设置窗口位置。null居中
setLocationRelativeTo(null);
// 为chooser添加文件过滤器
setFileFilter();
setJMenuBar(createJMenuBar());
ta.setFont(new Font("", Font.PLAIN, 18));
add(new JScrollPane(ta), BorderLayout.CENTER);
add(createPanel(), BorderLayout.PAGE_END);
// 设置窗口可见
setVisible(true);
// 为JFrame添加组件事件监听器
this.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentResized(ComponentEvent e) {
// TODO Auto-generated method stub
int width = (int) (Notepad.this.getWidth() * 0.67);
labelTips.setPreferredSize(new Dimension(width, 20));
}
@Override
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentHidden(ComponentEvent e) {
// TODO Auto-generated method stub
}
});
// 为JFrame添加窗口状态时间监听器
this.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
windowsNum++;
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
windowsNum--;
if (windowsNum == 0) {
System.exit(0);
}
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
});
// 为文本编辑器添加DocumentListener事件监听器
ta.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
taChange();
// System.out.println("remove");
}
@Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
taChange();
// System.out.println("insert");
}
@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
// 只有改变属性时才会通知
// taChange();
// System.out.println("change");
}
});
ta.getDocument().addUndoableEditListener(new UndoableEditListener() {
@Override
public void undoableEditHappened(UndoableEditEvent e) {
// TODO Auto-generated method stub
undomanager.addEdit(e.getEdit());
changeEnable();
}
});
ta.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
// TODO Auto-generated method stub
try {
int pos = ta.getCaretPosition();
// 获取行数
int line = ta.getLineOfOffset(pos) + 1;
// 获取列数
int col = pos - ta.getLineStartOffset(line - 1) + 1;
labelLine.setText("行数:" + line);
labelColumn.setText("列数:" + col);
labelNum.setText("字数:" + ta.getText().length());
} catch (Exception ex) {
labelTips.setText("无法获得当前光标位置 ");
}
}
});
}
// 改变撤销重做的状态
private void changeEnable() {
jmiUndo.setEnabled(undomanager.canUndo());
jmiRedo.setEnabled(undomanager.canRedo());
}
// 设置文本的状态为未保存
private void taChange() {
// TODO Auto-generated method stub
isSaved = false;
String title = this.getTitle();
if (!title.startsWith("*")) {
title = "*" + title;
}
this.setTitle(title);
}
// 设置文件过滤器
private void setFileFilter() {
// TODO Auto-generated method stub
javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() {
@Override
public String getDescription() {
// TODO Auto-generated method stub
return ".txt";
}
@Override
public boolean accept(File f) {
// TODO Auto-generated method stub
String name = f.getName();
return f.isDirectory() || name.toLowerCase().endsWith(".txt"); // 仅显示目录和txt文件
// ;
}
};
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
}
private JPanel createPanel() {
// TODO Auto-generated method stub
panelEnd = new JPanel();
panelEnd.setPreferredSize(new Dimension(800, 25));
panelEnd.setBackground(Color.LIGHT_GRAY);
panelEnd.setLayout(new FlowLayout(FlowLayout.LEFT));
panelEnd.add(labelTips = new JLabel("按F1以获取帮助"));
panelEnd.add(labelLine = new JLabel("行数:1"));
panelEnd.add(labelColumn = new JLabel("列数:1"));
panelEnd.add(labelNum = new JLabel("字数:0"));
labelTips.setPreferredSize(new Dimension(500, 20));
// labelTips.setBounds(0, 0, 500, 20);
// labelTips.setLayout(new FlowLayout(FlowLayout.LEFT));
return panelEnd;
}
// 创建JMenuBar
private JMenuBar createJMenuBar() {
// TODO Auto-generated method stub
JMenuBar menu = new JMenuBar();
// 设置JMenuBar的大小
menu.setPreferredSize(new Dimension(800, 25));
// 创建菜单
JMenu menuFile = new JMenu("文件(F)"), menuEdit = new JMenu("编辑(E)"), menuFormat = new JMenu("格式(O)"),
menuView = new JMenu("查看(V)"), menuHelp = new JMenu("帮助(H)");
// 设置热键,需使用alt+所设定的字母以选中。
menuFile.setMnemonic('F');
menuEdit.setMnemonic('E');
menuFormat.setMnemonic('O');
menuView.setMnemonic('V');
menuHelp.setMnemonic('H');
// 给文件菜单添加具体选项
menuFile.add(jmiCreate = new JMenuItem("新建"));
jmiCreate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
menuFile.add(jmiOpen = new JMenuItem("打开"));
jmiOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
menuFile.add(jmiSave = new JMenuItem("保存"));
jmiSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
menuFile.add(jmiSaveAs = new JMenuItem("另存为"));
jmiSaveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
menuFile.addSeparator();
menuFile.add(jmiSet = new JMenuItem("设置"));
menuFile.add(jmiExit = new JMenuItem("退出"));
// 给编辑菜单添加具体选项
menuEdit.add(jmiUndo = new JMenuItem("撤销"));
jmiUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
menuEdit.add(jmiRedo = new JMenuItem("重做"));
jmiRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK));
changeEnable(); // 改变撤销重做的状态
menuEdit.addSeparator();
menuEdit.add(jmiCopy = new JMenuItem("复制"));
jmiCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
menuEdit.add(jmiPaste = new JMenuItem("粘贴"));
jmiPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
menuEdit.add(jmiCut = new JMenuItem("剪切"));
jmiCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
menuEdit.addSeparator();
menuEdit.add(jmiSelectAll = new JMenuItem("全选"));
jmiSelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
menuEdit.add(jmiInsertTime = new JMenuItem("时间/日期"));
// menuEdit.addSeparator();
// 格式
menuFormat.add(jmiAutoEnter = new JCheckBoxMenuItem("自动换行", false));
menuFormat.add(jmiFont = new JMenuItem("字体"));
// 查看
menuView.add(jmiStatus = new JCheckBoxMenuItem("状态栏", true));
// 给帮助菜单添加具体选项
menuHelp.add(jmiTopic = new JMenuItem("帮助主题"));
jmiTopic.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
menuHelp.add(jmiAbout = new JMenuItem("关于"));
// 将菜单添加到JMenuBar中
menu.add(menuFile);
menu.add(menuEdit);
menu.add(menuFormat);
menu.add(menuView);
menu.add(menuHelp);
// 给选项添加ActionEvent
addActionListener();
return menu;
}
// 给菜单增加事件监听器
private void addActionListener() {
// TODO Auto-generated method stub
// 文件选项
jmiCreate.addActionListener(this); // 新建
jmiOpen.addActionListener(this); // 打开
jmiSave.addActionListener(this); // 保存
jmiSaveAs.addActionListener(this); // 另存为
jmiSet.addActionListener(this); // 设置
jmiExit.addActionListener(this); // 退出
// 编辑选项
jmiUndo.addActionListener(this); // 撤销
jmiRedo.addActionListener(this); // 重做
jmiCopy.addActionListener(this); // 复制
jmiPaste.addActionListener(this); // 粘贴
jmiCut.addActionListener(this); // 剪切
jmiSelectAll.addActionListener(this); // 全选
jmiInsertTime.addActionListener(this);
// 格式
jmiAutoEnter.addActionListener(this); // 自动换行
jmiFont.addActionListener(this); // 字体
// 查看
jmiStatus.addActionListener(this); // 状态栏
// 帮助
jmiTopic.addActionListener(this); // 帮助主题
jmiAbout.addActionListener(this); // 关于
}
// 监听菜单选项以调用相应方法
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// 打开文件
if (e.getSource() == jmiOpen) {
open();
} else if (e.getSource() == jmiSave) {
// 保存文件
save();
} else if (e.getSource() == jmiExit) {
// 退出当前窗口,如果是最后一个窗口,则退出程序
this.dispose();
windowsNum--;
if (windowsNum == 0) {
System.exit(0);
}
} else if (e.getSource() == jmiCreate) {
// 创建新的窗口
create();
} else if (e.getSource() == jmiSaveAs) {
saveAs();
} else if (e.getSource() == jmiCopy) {
labelTips.setText("复制");
ta.copy();
} else if (e.getSource() == jmiPaste) {
labelTips.setText("粘贴");
ta.paste();
} else if (e.getSource() == jmiCut) {
labelTips.setText("剪切");
ta.cut();
} else if (e.getSource() == jmiAbout) {
// 关于
JOptionPane.showMessageDialog(this, "记事本\n作者:tonglee\n我的blog:http://blog.csdn.net/u014248337\nversion 1.0", "关于记事本", JOptionPane.CLOSED_OPTION);
} else if (e.getSource() == jmiUndo) {
// 撤销操作
try {
undomanager.undo();
labelTips.setText("撤销");
} catch (CannotRedoException cre) {
cre.printStackTrace();
}
changeEnable();
} else if (e.getSource() == jmiRedo) {
try {
undomanager.redo();
labelTips.setText("重做");
} catch (CannotRedoException cre) {
cre.printStackTrace();
}
changeEnable();
} else if (e.getSource() == jmiSet) {
// 设置
set();
} else if (e.getSource() == jmiTopic) {
// 帮助
Help();
} else if (e.getSource() == jmiSelectAll) {
ta.selectAll();
} else if (e.getSource() == jmiAutoEnter) {
if (jmiAutoEnter.isSelected()) {
ta.setLineWrap(true);
labelLine.setVisible(false);
labelColumn.setVisible(false);
} else {
ta.setLineWrap(false);
labelLine.setVisible(true);
labelColumn.setVisible(true);
}
} else if (e.getSource() == jmiStatus) {
if (jmiStatus.isSelected()) {
panelEnd.setVisible(true);
} else {
panelEnd.setVisible(false);
}
} else if (e.getSource() == jmiFont) {
font();
} else if (e.getSource() == jmiInsertTime) {
Calendar rightNow=Calendar.getInstance();
Date date=rightNow.getTime();
ta.insert(date.toString(),ta.getCaretPosition());
}
}
public void font() {
final JDialog fontDialog = new JDialog(this, "字体设置", false);
Container con = fontDialog.getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel fontLabel = new JLabel("字体(F):");
fontLabel.setPreferredSize(new Dimension(100, 20));// 构造一个Dimension,并将其初始化为指定宽度和高度
JLabel styleLabel = new JLabel("字形(Y):");
styleLabel.setPreferredSize(new Dimension(100, 20));
JLabel sizeLabel = new JLabel("大小(S):");
sizeLabel.setPreferredSize(new Dimension(100, 20));
final JLabel sample = new JLabel("李童的记事本-TongLee's Notepad");
// sample.setHorizontalAlignment(SwingConstants.CENTER);
final JTextField fontText = new JTextField(9);
fontText.setPreferredSize(new Dimension(200, 20));
final JTextField styleText = new JTextField(8);
styleText.setPreferredSize(new Dimension(200, 20));
final int style[] = { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD + Font.ITALIC };
final JTextField sizeText = new JTextField(5);
sizeText.setPreferredSize(new Dimension(200, 20));
JButton okButton = new JButton("确定");
JButton cancel = new JButton("取消");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontDialog.dispose();
}
});
Font currentFont = ta.getFont();
fontText.setText(currentFont.getFontName());
fontText.selectAll();
// styleText.setText(currentFont.getStyle());
// styleText.selectAll();
if (currentFont.getStyle() == Font.PLAIN)
styleText.setText("常规");
else if (currentFont.getStyle() == Font.BOLD)
styleText.setText("粗体");
else if (currentFont.getStyle() == Font.ITALIC)
styleText.setText("斜体");
else if (currentFont.getStyle() == (Font.BOLD + Font.ITALIC))
styleText.setText("粗斜体");
styleText.selectAll();
String str = String.valueOf(currentFont.getSize());
sizeText.setText(str);
sizeText.selectAll();
final JList fontList, styleList, sizeList;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final String fontName[] = ge.getAvailableFontFamilyNames();
fontList = new JList(fontName);
fontList.setFixedCellWidth(86);
fontList.setFixedCellHeight(20);
fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final String fontStyle[] = { "常规", "粗体", "斜体", "粗斜体" };
styleList = new JList(fontStyle);
styleList.setFixedCellWidth(86);
styleList.setFixedCellHeight(20);
styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (currentFont.getStyle() == Font.PLAIN)
styleList.setSelectedIndex(0);
else if (currentFont.getStyle() == Font.BOLD)
styleList.setSelectedIndex(1);
else if (currentFont.getStyle() == Font.ITALIC)
styleList.setSelectedIndex(2);
else if (currentFont.getStyle() == (Font.BOLD + Font.ITALIC))
styleList.setSelectedIndex(3);
final String fontSize[] = { "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36",
"48", "72" };
sizeList = new JList(fontSize);
sizeList.setFixedCellWidth(43);
sizeList.setFixedCellHeight(20);
sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
fontText.setText(fontName[fontList.getSelectedIndex()]);
fontText.selectAll();
Font sampleFont1 = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
Integer.parseInt(sizeText.getText()));
sample.setFont(sampleFont1);
}
});
styleList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int s = style[styleList.getSelectedIndex()];
styleText.setText(fontStyle[s]);
styleText.selectAll();
Font sampleFont2 = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
Integer.parseInt(sizeText.getText()));
sample.setFont(sampleFont2);
}
});
sizeList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
sizeText.setText(fontSize[sizeList.getSelectedIndex()]);
// sizeText.requestFocus();
sizeText.selectAll();
Font sampleFont3 = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
Integer.parseInt(sizeText.getText()));
sample.setFont(sampleFont3);
}
});
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Font okFont = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
Integer.parseInt(sizeText.getText()));
ta.setFont(okFont);
fontDialog.dispose();
}
});
JPanel samplePanel = new JPanel();
samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));
// samplePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
samplePanel.add(sample);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
panel2.add(fontText);
panel2.add(styleText);
panel2.add(sizeText);
panel2.add(okButton);
panel3.add(new JScrollPane(fontList));// JList不支持直接滚动,所以要让JList作为JScrollPane的视口视图
panel3.add(new JScrollPane(styleList));
panel3.add(new JScrollPane(sizeList));
panel3.add(cancel);
con.add(panel1);
con.add(panel2);
con.add(panel3);
con.add(samplePanel);
fontDialog.setSize(350, 340);
fontDialog.setLocation(200, 200);
fontDialog.setResizable(false);
fontDialog.setVisible(true);
}
private void Help() {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(this, "基于Java编写的一个简易的记事本程序", "帮助", JOptionPane.CLOSED_OPTION);
}
private void set() {
// TODO Auto-generated method stub
JDialog mySet = new JDialog(this, "页面设置", true);
mySet.setLocationRelativeTo(null);
mySet.setSize(300, 400);
mySet.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
JLabel label = new JLabel("等待填充。");
JButton btnYes = new JButton("确定");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(btnYes);
btnYes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
mySet.dispose();
}
});
mySet.add(label, BorderLayout.PAGE_START);
mySet.add(panel, BorderLayout.PAGE_END);
mySet.setVisible(true);
}
private void saveAs() {
// TODO Auto-generated method stub
chooser.setDialogTitle("保存文件到");
getDirectory();
// save();
String name = file.getAbsolutePath();
if (!name.toLowerCase().endsWith(".txt")) {
name = name + ".txt";
file = new File(name);
}
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] b = ta.getText().getBytes();
out.write(b);
isSaved = true;
labelTips.setText("文件已保存");
// this.setTitle(file.getName() + " - 记事本");
} catch (IOException e) {
labelTips.setText("文件保存失败");
}
}
// 新建窗口
private void create() {
// TODO Auto-generated method stub
new Notepad();
}
// 保存文件
private void save() {
// TODO Auto-generated method stub
if (file == null) {
// chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle("保存文件");
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
labelTips.setText("您取消了保存操作");
return;
}
}
String name = file.getAbsolutePath();
if (!name.toLowerCase().endsWith(".txt")) {
name = name + ".txt";
file = new File(name);
}
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] b = ta.getText().getBytes();
out.write(b);
isSaved = true;
labelTips.setText("文件已保存");
this.setTitle(file.getName() + " - 记事本");
} catch (IOException e) {
labelTips.setText("文件保存失败");
}
}
private void getDirectory() {
// TODO Auto-generated method stub
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
labelTips.setText("您取消了保存操作");
return;
}
}
// 打开,在打开之前先判断是否需要保存之前的文件
private void open() {
// TODO Auto-generated method stub
// 判断是否保存,如果已经保存了,则直接进入打开窗口,如果没有则询问
if (isSaved) {
openTo();
} else {
// 询问是否保存窗口,返回值有0,1,2,,分别表示是,否,取消,如点击关闭按钮则返回-1
int r = JOptionPane.showConfirmDialog(null, "您还没有保存,是否要保存该文件?", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
if (r == 0) {
labelTips.setText("保存文件");
save();
} else if (r == 2 || r == -1) {
labelTips.setText("您没有选中任何文件.");
} else
openTo();
}
}
// 打开文件
private void openTo() {
// 判断点击的是哪一个按钮,APPROVE_OPTION表示确认选择
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogTitle("打开文件");
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try (// 字符缓存输入流
BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line = null;
// ta.requestFocus();
ta.setText("");
// 按行读取file里的字符并
while ((line = bfr.readLine()) != null) {
ta.append(line);
ta.append(System.getProperty("line.separator"));
}
labelTips.setText("打开文件:" + file.getName());
this.setTitle(file.toString() + " - 记事本");
} catch (IOException e) {
// 打开文件失败的提示信息.
labelTips.setText("文件打开错误:" + file.toString());
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// Notepad np = new Notepad();
new Notepad();
}
}
本来准备添加个超链接的,后来嫌麻烦就没添加了,毕竟要想添加超链接就得使用dialog自己设计了。附上方法:
1、 用JLabel里面添加html代码,打开一个超链接和换行,在setText()里面添加html代码,可以识别并运行。
①换行效果: setText("hello~
world~!")
可实现换行效果:
hello~
world~!
②添加链接:
JLabel linklabel = new JLabel("My Blog");
linklabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
Runtime.getRuntime().exec("cmd.exe /c start " + "http://blog.csdn.net/u014248337/");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
//上面的Runtime语句可用此句代替Runtime.getRuntime().exec("explorer+ "http://blog.csdn.net/u014248337/");
2、 用IE浏览器的形式打开,通过Desktop来启动用户默认浏览器来显示指定的 URI:
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI("URL地址"));
3、 用JDIC来打开一个web页面,它可以把一个浏览器页面通过Swing界面包装起来,在面板上面显示web页面,外观是Swing界面,内部是web页面的形式。
这个是需要外部引入JDIC的jar包 和几个本地库文件加载。
WebBrowser browser = new WebBrowser();
try {
browser.setURL(new URL("URL地址"));
BrowserEngineManager engineManager = BrowserEngineManager.instance();
engineManager.setActiveEngine(BrowserEngineManager.IE); //指定IE浏览器
}catch(Exception ex){}
S: jdic.dll和tray.dll放入System32下面,自动加载;然后再引入jar就OK…
下面这个是网上找的一个关于WebBrowser这个控件的详细介绍,可以去了解一下
http://www.cnblogs.com/lemony/archive/2007/11/04/948886.html
参考自:Swing如何打开超链接