如何在JLabel中换行?

xueruini 2002-12-26 04:40:19
有时希望在JLabel中实现换行,但\n不行
请问怎么解决?
...全文
634 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
longaway 2002-12-26
  • 打赏
  • 举报
回复
As of Swing 1.1.1 Beta 1, JLabel supports multiple lines, multiple fonts, and a whole lot more because you can specify a label's text using HTML.

也就是没有太直截了当的方法
longaway 2002-12-26
  • 打赏
  • 举报
回复
http://java.sun.com/docs/books/tutorial/uiswing/components/label.html
高仿QQ聊天 登录界面 import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.UIManager; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; public class Test extends JFrame { private JScrollPane scrollPane = null; // 滚动 private JTextPane text = null; private Box box = null; // 放输入组件的容器 private JButton b_insert = null, b_remove = null, b_icon = null; // 插入按钮;清除按钮;插入图片按钮 private JTextField addText = null; // 文字输入框 // 字体名称;字号大小;文字样式;文字颜色;文字背景颜色 private JComboBox fontName = null, fontSize = null, fontStyle = null, fontColor = null, fontBackColor = null; private StyledDocument doc = null; // 非常重要插入文字样式就靠它了 public Test() { super("JTextPane Test"); try { // 使用Windows的界面风格 UIManager.setLookAndFeel ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } text = new JTextPane(); text.setEditable(false); // 不可录入 doc = text.getStyledDocument(); // 获得JTextPane的Document scrollPane = new JScrollPane(text); addText = new JTextField(18); String[] str_name = { "宋体", "黑体", "Dialog", "Gulim" }; String[] str_Size = { "12", "14", "18", "22", "30", "40" }; String[] str_Style = { "常规", "斜体", "粗体", "粗斜体" }; String[] str_Color = { "黑色", "红色", "蓝色", "黄色", "绿色" }; String[] str_BackColor = { "无色", "灰色", "淡红", "淡蓝", "淡黄", "淡绿" }; fontName = new JComboBox(str_name); // 字体名称 fontSize = new JComboBox(str_Size); // 字号 fontStyle = new JComboBox(str_Style); // 样式 fontColor = new JComboBox(str_Color); // 颜色 fontBackColor = new JComboBox(str_BackColor); // 背景颜色 b_insert = new JButton("插入"); // 插入 b_remove = new JButton("清空"); // 清除 b_icon = new JButton("图片"); // 插入图片 b_insert.addActionListener(new ActionListener() { // 插入文字的事件 public void actionPerformed(ActionEvent e) { insert(getFontAttrib()); addText.setText(""); } }); b_remove.addActionListener(new ActionListener() { // 清除事件 public void actionPerformed(ActionEvent e) { text.setText(""); } }); b_icon.addActionListener(new ActionListener() { // 插入图片事件 public void actionPerformed(ActionEvent arg0) { JFileChooser f = new JFileChooser(); // 查找文件 f.showOpenDialog(null); insertIcon(f.getSelectedFile()); // 插入图片 } }); box = Box.createVerticalBox(); // 竖结构 Box box_1 = Box.createHorizontalBox(); // 横结构 Box box_2 = Box.createHorizontalBox(); // 横结构 box.add(box_1); box.add(Box.createVerticalStrut(8)); // 两行的间距 box.add(box_2); box.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); // 8个的边距 // 开始将所需组件加入容器 box_1.add(new JLabel("字体:")); // 加入标签 box_1.add(fontName); // 加入组件 box_1.add(Box.createHorizontalStrut(8)); // 间距 box_1.add(new JLabel("样式:")); box_1.add(fontStyle); box_1.add(Box.createHorizontalStrut(8)); box_1.add(new JLabel("字号:")); box_1.add(fontSize); box_1.add(Box.createHorizontalStrut(8)); box_1.add(new JLabel("颜色:")); box_1.add(fontColor); box_1.add(Box.createHorizontalStrut(8)); box_1.add(new JLabel("背景:")); box_1.add(fontBackColor); box_1.add(Box.createHorizontalStrut(8)); box_1.add(b_icon); box_2.add(addText); box_2.add(Box.createHorizontalStrut(8)); box_2.add(b_insert); box_2.add(Box.createHorizontalStrut(8)); box_2.add(b_remove); this.getRootPane().setDefaultButton(b_insert); // 默认回车按钮 this.getContentPane().add(scrollPane); this.getContentPane().add(box, BorderLayout.SOUTH); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(600, 400); this.setLocationRelativeTo(null); this.setVisible(true); addText.requestFocus(); } /** * 插入图片 * * @param icon */ private void insertIcon(File file) { text.setCaretPosition(doc.getLength()); // 设置插入位置 text.insertIcon(new ImageIcon(file.getPath())); // 插入图片 insert(new FontAttrib()); // 这样做可以换行 } /** * 将文本插入JTextPane * * @param attrib */ private void insert(FontAttrib attrib) { try { // 插入文本 doc.insertString(doc.getLength(), attrib.getText() + "\n", attrib.getAttrSet()); } catch (BadLocationException e) { e.printStackTrace(); } } /** * 获取所需要的文字设置 * * @return FontAttrib */ private FontAttrib getFontAttrib() { FontAttrib att = new FontAttrib(); att.setText(addText.getText()); att.setName((String) fontName.getSelectedItem()); att.setSize(Integer.parseInt((String) fontSize.getSelectedItem())); String temp_style = (String) fontStyle.getSelectedItem(); if (temp_style.equals("常规")) { att.setStyle(FontAttrib.GENERAL); } else if (temp_style.equals("粗体")) { att.setStyle(FontAttrib.BOLD); } else if (temp_style.equals("斜体")) { att.setStyle(FontAttrib.ITALIC); } else if (temp_style.equals("粗斜体")) { att.setStyle(FontAttrib.BOLD_ITALIC); } String temp_color = (String) fontColor.getSelectedItem(); if (temp_color.equals("黑色")) { att.setColor(new Color(0, 0, 0)); } else if (temp_color.equals("红色")) { att.setColor(new Color(255, 0, 0)); } else if (temp_color.equals("蓝色")) { att.setColor(new Color(0, 0, 255)); } else if (temp_color.equals("黄色")) { att.setColor(new Color(255, 255, 0)); } else if (temp_color.equals("绿色")) { att.setColor(new Color(0, 255, 0)); } String temp_backColor = (String) fontBackColor.getSelectedItem(); if (!temp_backColor.equals("无色")) { if (temp_backColor.equals("灰色")) { att.setBackColor(new Color(200, 200, 200)); } else if (temp_backColor.equals("淡红")) { att.setBackColor(new Color(255, 200, 200)); } else if (temp_backColor.equals("淡蓝")) { att.setBackColor(new Color(200, 200, 255)); } else if (temp_backColor.equals("淡黄")) { att.setBackColor(new Color(255, 255, 200)); } else if (temp_backColor.equals("淡绿")) { att.setBackColor(new Color(200, 255, 200)); } } return att; } public static void main(String args[]) { new Test(); } /** * 字体的属性类 */ private class FontAttrib { public static final int GENERAL = 0; // 常规 public static final int BOLD = 1; // 粗体 public static final int ITALIC = 2; // 斜体 public static final int BOLD_ITALIC = 3; // 粗斜体 private SimpleAttributeSet attrSet = null; // 属性集 private String text = null, name = null; // 要输入的文本和字体名称 private int style = 0, size = 0; // 样式和字号 private Color color = null, backColor = null; // 文字颜色和背景颜色 /** * 一个空的构造(可当做换行使用) */ public FontAttrib() { } /** * 返回属性集 * * @return */ public SimpleAttributeSet getAttrSet() { attrSet = new SimpleAttributeSet(); if (name != null) StyleConstants.setFontFamily(attrSet, name); if (style == FontAttrib.GENERAL) { StyleConstants.setBold(attrSet, false); StyleConstants.setItalic(attrSet, false); } else if (style == FontAttrib.BOLD) { StyleConstants.setBold(attrSet, true); StyleConstants.setItalic(attrSet, false); } else if (style == FontAttrib.ITALIC) { StyleConstants.setBold(attrSet, false); StyleConstants.setItalic(attrSet, true); } else if (style == FontAttrib.BOLD_ITALIC) { StyleConstants.setBold(attrSet, true); StyleConstants.setItalic(attrSet, true); } StyleConstants.setFontSize(attrSet, size); if (color != null) StyleConstants.setForeground(attrSet, color); if (backColor != null) StyleConstants.setBackground(attrSet, backColor); return attrSet; } /** * 设置属性集 * * @param attrSet */ public void setAttrSet(SimpleAttributeSet attrSet) { this.attrSet = attrSet; } /* 后面的注释就不写了,一看就明白 */ public String getText() { return text; } public void setText(String text) { this.text = text; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public Color getBackColor() { return backColor; } public void setBackColor(Color backColor) { this.backColor = backColor; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getStyle() { return style; } public void setStyle(int style) { this.style = style; } } }
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; public class NotePad { public static void main(String[] args){ myfr fr=new myfr("猪猪java记事本"); fr.setLocation(100,100); fr.setSize(750,650); } } ///////////////////////////myfr主窗体类////////////////////////////////////// class myfr extends JFrame implements ActionListener{ String str,strnext,path,fname; //部分变量的声明 JPanel mainpane; JFileChooser choose = new JFileChooser(); //文件对话框 Dialog find,replace; //find为查找对话框,replace对话框 JTextField findtxt,repltxt; //find为查找对话框的输入文本区,replace对话框的输入文本区 Font newfont; JButton findenter,replb; //find为查找对话框,replace对话框的确定按钮 JLabel state=new JLabel(" 猪猪java记事本------"); //状态栏 JTextArea txt1; //主输入文本区 File newfiles; JPopupMenu popm; //弹出菜单声明 JMenu m1,m2,m3,m4,m5,m6; //各菜单项 JMenuItem m61,m62,m26,m271,m34,m51,m52,m53,m54,p_copy,p_cut,p_paste,p_del; int startp,endp,nexttemp,newstartp,newendp; //查找替换时所用的临时变量 JToolBar toolbar = new JToolBar(); //工具条 JButton newf=new JButton(new ImageIcon("9.jpg")); //图标在PIC下 JButton open=new JButton(new ImageIcon("2.jpg")); JButton save=new JButton(new ImageIcon("3.jpg")); JButton copy=new JButton(new ImageIcon("6.jpg")); JButton cut=new JButton(new ImageIcon("7.jpg")); JButton pp=new JButton(new ImageIcon("8.jpg")); JButton del=new JButton(new ImageIcon("pic/del.gif")); JButton findc=new JButton(new ImageIcon("9.jpg")); JButton color=new JButton(new ImageIcon("10.jpg")); JButton help=new JButton(new ImageIcon("pic/help.gif")); JButton exit=new JButton(new ImageIcon("pic/exit.gif")); myfr(String sss){ /////构造函数开始 super(sss); JMenuBar mb=new JMenuBar(); fname=null; //初始文件名为空 findenter=new JButton("确定"); findenter.addActionListener(this); //声明对话框上确定按钮,并注册事件 replb=new JButton("确定"); replb.addActionListener(this); mainpane=(JPanel)this.getContentPane(); mainpane.setLayout(new BorderLayout()); txt1=new JTextArea("",13,61); txt1.addMouseListener(new handlemouse(this));//注册鼠标右击事件 txt1.setFont(new Font("宋体",Font.PLAIN,18)); mainpane.add(txt1, BorderLayout.CENTER); mainpane.add("North",toolbar); mainpane.add("South",state); JScrollPane sll = new JScrollPane(); //创建滚动条 mainpane.add("Center", sll); ; sll.getViewport().add(txt1); //将滚动条装入文本区 //文本栏的浮动条 popm=new JPopupMenu(); ////POPMeun 开始 p_copy=new JMenuItem("复制 "); p_copy.addActionListener(this); KeyStroke keycopyp=KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK); p_copy.setAccelerator(keycopyp); p_cut=new JMenuItem("剪切 "); p_cut.addActionListener(this); KeyStroke keycutp=KeyStroke.getKeyStroke(KeyEvent.VK_X,Event.CTRL_MASK); p_cut.setAccelerator(keycutp); p_paste=new JMenuItem("粘贴 "); p_paste.addActionListener(this); KeyStroke keypp=KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK); p_paste.setAccelerator(keypp); p_del=new JMenuItem("删除 "); p_del.addActionListener(this); KeyStroke keydelp=KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0); p_del.setAccelerator(keydelp); popm.add(p_copy); popm.add(p_cut); popm.add(p_paste); popm.add(p_del); txt1.add(popm); ////POPMenu 结束 m1=new JMenu("文件(F)"); m1.setMnemonic('F'); //定义快捷方式 JMenuItem m10=new JMenuItem("新建 "); m10.addActionListener(this); //注册事件监听器 KeyStroke keynew=KeyStroke.getKeyStroke(KeyEvent.VK_N,Event.CTRL_MASK); //定义快捷键 m10.setAccelerator(keynew); JMenuItem m11=new JMenuItem("打开 "); m11.addActionListener(this); KeyStroke keyopen=KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK); m11.setAccelerator(keyopen); JMenuItem m12=new JMenuItem("保存 "); m12.addActionListener(this); KeyStroke keysave=KeyStroke.getKeyStroke(KeyEvent.VK_S,Event.CTRL_MASK); m12.setAccelerator(keysave); JMenuItem m13=new JMenuItem("另保存为 "); m13.addActionListener(this); JMenuItem m14=new JMenuItem("退出 "); m14.addActionListener(this); KeyStroke keyexit=KeyStroke.getKeyStroke(KeyEvent.VK_F4,Event.ALT_MASK); m14.setAccelerator(keyexit); //////////////////////////////////////////// m2=new JMenu("编辑(E)"); m2.setMnemonic('E'); JMenuItem m21=new JMenuItem("复制 "); m21.addActionListener(this); KeyStroke keycopy=KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK); m21.setAccelerator(keycopy); JMenuItem m22=new JMenuItem("剪切 "); m22.addActionListener(this); KeyStroke keycut=KeyStroke.getKeyStroke(KeyEvent.VK_X,Event.CTRL_MASK); m22.setAccelerator(keycut); JMenuItem m23=new JMenuItem("粘贴 "); m23.addActionListener(this); KeyStroke keyp=KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK); m23.setAccelerator(keyp); JMenuItem m24=new JMenuItem("删除 "); m24.addActionListener(this); KeyStroke keydel=KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0); m24.setAccelerator(keydel); JMenuItem m25=new JMenuItem("查找 "); m25.addActionListener(this); KeyStroke keyfind=KeyStroke.getKeyStroke(KeyEvent.VK_F,Event.CTRL_MASK); m25.setAccelerator(keyfind); m26=new JMenuItem("查找下一个 "); m26.addActionListener(this); KeyStroke keyfn=KeyStroke.getKeyStroke(KeyEvent.VK_F3,0); m26.setAccelerator(keyfn); m26.setEnabled(false); JMenuItem m27=new JMenuItem("替换 "); m27.addActionListener(this); KeyStroke keyrepl=KeyStroke.getKeyStroke(KeyEvent.VK_H,Event.CTRL_MASK); m27.setAccelerator(keyrepl); m271=new JMenuItem("替换下一个"); m271.setEnabled(false); m271.addActionListener(this); KeyStroke keyrepn=KeyStroke.getKeyStroke(KeyEvent.VK_F6,0); m271.setAccelerator(keyrepn); JMenuItem m28=new JMenuItem("全选 "); m28.addActionListener(this); KeyStroke keyall=KeyStroke.getKeyStroke(KeyEvent.VK_A,Event.CTRL_MASK); m28.setAccelerator(keyall); JMenuItem m29=new JMenuItem("日期/时间 "); m29.addActionListener(this); m3=new JMenu("格式(O)"); m3.setMnemonic('O'); JMenu m31=new JMenu("字体样式 "); JMenuItem m311=new JMenuItem("正常 "); m311.addActionListener(this); JMenuItem m312=new JMenuItem("粗体 "); m312.addActionListener(this); JMenuItem m313=new JMenuItem("斜体 "); m313.addActionListener(this); JMenu m32=new JMenu("字体大小 "); JMenuItem m321=new JMenuItem("最大 "); m321.addActionListener(this); JMenuItem m322=new JMenuItem("较大 "); m322.addActionListener(this); JMenuItem m323=new JMenuItem("适 "); m323.addActionListener(this); JMenuItem m324=new JMenuItem("较小 "); m324.addActionListener(this); JMenuItem m325=new JMenuItem("最小 "); m325.addActionListener(this); JMenuItem m33=new JMenuItem("字体颜色 "); m33.addActionListener(this); m34=new JMenuItem("自动换行 "); m34.addActionListener(this); m5=new JMenu("视图风格(V)"); m5.setMnemonic('V'); //m51=new JMenuItem("系统风格 "); //m51.addActionListener(this); m52=new JMenuItem("MOTIF风格 "); m52.addActionListener(this); m53=new JMenuItem("默认风格 "); m53.addActionListener(this); m54=new JMenuItem("状态栏 "); m54.addActionListener(this); m6=new JMenu("帮助(H)"); m6.setMnemonic('H'); m61=new JMenuItem("帮助主题 "); m61.addActionListener(this); m62=new JMenuItem("关于 "); m62.addActionListener(this); //添加各项 m1.add(m10); m1.add(m11); m1.add(m12); m1.add(m13); m1.addSeparator(); m1.add(m14); m2.add(m21); m2.add(m22); m2.add(m23); m2.add(m24); m2.addSeparator(); m2.add(m25); m2.add(m26); m2.add(m27); m2.add(m271); m2.addSeparator(); m2.add(m28); m2.add(m29); m3.add(m31); m31.add(m311); m31.add(m312); m31.add(m313); m3.add(m32); m32.add(m321); m32.add(m322); m32.add(m323); m32.add(m324); m32.add(m325); m3.add(m33); m3.addSeparator(); m3.add(m34); //m5.add(m51); m5.add(m52); m5.add(m53); m5.addSeparator(); m5.add(m54); m6.add(m61); m6.addSeparator(); m6.add(m62); mb.add(m1); mb.add(m2); mb.add(m3); mb.add(m5); mb.add(m6); this.setJMenuBar(mb); //设置菜单栏 toolbar.add(newf); //工具栏各按钮 newf.setToolTipText("新建"); newf.addActionListener(this); //toolbar.add(open); //open.setToolTipText("打开"); //open.addActionListener(this); //toolbar.add(save); //save.setToolTipText("保存"); //save.addActionListener(this); //toolbar.addSeparator(); toolbar.add(copy); copy.setToolTipText("复制"); copy.addActionListener(this); toolbar.add(cut); cut.setToolTipText("剪切"); cut.addActionListener(this); toolbar.add(pp); pp.setToolTipText("粘贴"); pp.addActionListener(this); //toolbar.add(del); //del.setToolTipText("删除"); //del.addActionListener(this); toolbar.addSeparator(); //toolbar.add(findc); //findc.setToolTipText("查找"); //findc.addActionListener(this); toolbar.add(color); color.setToolTipText("字体颜色"); color.addActionListener(this); toolbar.addSeparator(); //toolbar.add(help); //help.setToolTipText("帮助主题"); //help.addActionListener(this); //toolbar.add(exit); //exit.setToolTipText("退出"); //exit.addActionListener(this); setVisible(true); pack(); show(); this.addWindowListener(new xxx(this)); }///构造函数结束/// ////////////////事件处理///////////////////////////////////// public void actionPerformed(ActionEvent p){ if(p.getActionCommand()=="新建 "||p.getSource()==newf){ //响应菜单及工具栏事件 fname=null; //置文件名为空,便于判断文件是否保存过 txt1.setText(""); state.setText(" 猪猪java记事本------"); } if(p.getActionCommand()=="打开 "||p.getSource()==open){ try { if(this.choose.APPROVE_OPTION==this.choose.showOpenDialog(this)){ path=this.choose.getSelectedFile().getPath(); fname=this.choose.getSelectedFile().getName(); File file=new File(path); int flength=(int)file.length(); FileReader fReader=new FileReader(file); char[] data=new char[flength]; fReader.read(data,0,flength); txt1.setText(new String(data)); state.setText(" 猪猪java记事本------"+path+" 共"+flength+"字节");//状态栏统计文件字节数 txt1.setCaretPosition(0); } }catch(IOException e){} } if(p.getActionCommand()=="保存 "||p.getSource()==save){ if(fname==null){ othersave(); } //如果文件名为空,说明文件未被创建,弹出另存为对话框 try { File savefile=new File(path); savefile.createNewFile(); FileWriter fw=new FileWriter(savefile); fw.write(txt1.getText()); fw.close(); }catch(IOException e){} } if(p.getActionCommand()=="另保存为 "){ othersave(); } if(p.getActionCommand()=="退出 "||p.getSource()==exit){ exit(); } //////////////////编辑//////////////////// if(p.getActionCommand()=="复制 "||p.getSource()==copy) { txt1.copy(); } if(p.getActionCommand()=="剪切 "||p.getSource()==cut) { txt1.cut(); } if(p.getActionCommand()=="粘贴 "||p.getSource()==pp) { txt1.paste(); } if(p.getActionCommand()=="删除 "||p.getSource()==del){ txt1.replaceSelection(""); } /////////////////////////////////////////////////////// if(p.getActionCommand()=="全选 "){ txt1.selectAll(); } if(p.getActionCommand()=="日期/时间 "){ //用DATE类插入当前日期/时间,编译时会出现说明 int inpoint=txt1.getCaretPosition(); Date dt=new Date(); String strdate=dt.toLocaleString(); txt1.insert(strdate,inpoint);} //格式// //////////字体样式//////////////// if(p.getActionCommand()=="正常 "){ newfont=txt1.getFont(); //得到当前应用字体,获得字体大小,创建相应样式 int size=newfont.getSize(); txt1.setFont(new Font("宋体",Font.PLAIN,size)); } if(p.getActionCommand()=="粗体 "){ newfont=txt1.getFont(); int size=newfont.getSize(); txt1.setFont(new Font("宋体",Font.BOLD,size)); } if(p.getActionCommand()=="斜体 "){ newfont=txt1.getFont(); int size=newfont.getSize(); txt1.setFont(new Font("宋体",Font.ITALIC,size)); } ////////////字体大小///////////////// if(p.getActionCommand()=="最大 "){ newfont=txt1.getFont(); ////得到当前应用字体,获得字体样式,创建相应字体的大小 int sty=newfont.getStyle() ; txt1.setFont(new Font("宋体",sty,35)); } if(p.getActionCommand()=="较大 "){ newfont=txt1.getFont(); int sty=newfont.getStyle() ; txt1.setFont(new Font("宋体",sty,30)); } if(p.getActionCommand()=="适 "){ newfont=txt1.getFont(); int sty=newfont.getStyle() ; txt1.setFont(new Font("宋体",sty,18)); } if(p.getActionCommand()=="较小 "){ newfont=txt1.getFont(); int sty=newfont.getStyle() ; txt1.setFont(new Font("宋体",sty,16)); } if(p.getActionCommand()=="最小 "){ newfont=txt1.getFont(); int sty=newfont.getStyle() ; txt1.setFont(new Font("宋体",sty,14)); } if(p.getActionCommand()=="字体颜色 "||p.getSource()==color){ //字体颜色 JColorChooser jColor=new JColorChooser(); //调用颜色面板,设置前景就可更改字体颜色 Color fcolor=txt1.getForeground(); txt1.setForeground( jColor.showDialog(txt1,"选择字体颜色",fcolor)); } if(p.getActionCommand()=="自动换行 "){ txt1.setLineWrap(true); m34.setEnabled(false);} //if(p.getActionCommand()=="系统风格 ") //不稳定,在不同编译平台下表现不一致 // { } if(p.getActionCommand()=="MOTIF风格 "){ this.dispose(); myfr ww=new myfr("我的javaX记事本"); try { //MOTIF界面 UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); SwingUtilities.updateComponentTreeUI(ww); }catch ( Exception e ) {} } if(p.getActionCommand()=="默认风格 "){ this.dispose(); myfr ww=new myfr("猪猪java记事本"); try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(ww); }catch ( Exception e ) {} } if(p.getActionCommand()=="状态栏 ") //状态栏的隐藏和显视 {state.setVisible( !(state.isVisible()) );} /////////////////////帮助/////////////////////////////////////////// if(p.getActionCommand()=="帮助主题 "||p.getSource()==help){ myhelp help=new myhelp(); help.setSize(200,240);} if(p.getActionCommand()=="关于 "){ JLabel prompt=new JLabel("欢迎使用我的JAVAX记事本",JLabel.CENTER); JOptionPane.showMessageDialog(null,prompt,"关于我的JAVAX记事本",JOptionPane.INFORMATION_MESSAGE); } } public void othersave() {//另存为方法 if(choose.APPROVE_OPTION==choose.showSaveDialog(this)){ path=choose.getSelectedFile().getPath(); newfiles=new File(path); state.setText(" 猪猪java记事本------"+path); fname=choose.getSelectedFile().getName();; try { newfiles=new File(path); newfiles.createNewFile(); FileWriter fw=new FileWriter(newfiles); fw.write(txt1.getText()); fw.close(); }catch(IOException e){} } } public void notfindmethod(){ //提示查找不到的方法notfindmethod if(!txt1.getSelectedText().equals(findtxt.getText())) { txt1.setCaretPosition(0); //光标返回文件头部 JOptionPane.showMessageDialog(null,"查找不到对应的字符!","查找错误",JOptionPane.ERROR_MESSAGE); m26.setEnabled(false); } } public void exit(){ int value; String[] qq={"返回", "退出"}; value=JOptionPane.showOptionDialog(null, "你确定退出吗?请注意保存文件!", "退出程序?", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,null, qq, qq[0]); if(value==JOptionPane.YES_OPTION) return; else if(value==JOptionPane.NO_OPTION) { System.exit(0); } } }//主窗口类结束// class xxx extends WindowAdapter{ //关闭窗口XXX类//////////// myfr fx; xxx(myfr fxx) {fx=fxx;} public void windowClosing(WindowEvent e){ JOptionPane.showMessageDialog(null,"欢迎使用本软件!","退出",JOptionPane.INFORMATION_MESSAGE); fx.dispose(); System.exit(0); } } class xxxhelp extends WindowAdapter{ //关闭帮助主题窗口类XXXhelp myhelp fx; xxxhelp(myhelp fxx){ fx=fxx;} public void windowClosing(WindowEvent e){ fx.dispose(); } } class myhelp extends JFrame{ //帮助主题类///////////////// TextArea helparea; myhelp() { super("我的帮助主题"); helparea=new TextArea("",45,25,TextArea.SCROLLBARS_NONE);//创建没有滚动条的帮助窗口 helparea.setText(" "); helparea.append("我的JAVAX记事本是一个用来创建简单的文档的基本的文本编辑器.可用于打开查看TXT文档。"); helparea.append("要编辑文字,请先选定它,然后单击相应菜单上的相关命令。"); helparea.append("鼠标悬停在工具栏上会出现相关提示。本软件在SDK 1.40下编写,"); helparea.append("最好在1.4环境下运行,否则会出现一些小问题,但不影响正常使用……"); setResizable(false); getContentPane().add(helparea); show();pack(); helparea.setFont(new Font("宋体",Font.PLAIN,14)); helparea.setEnabled(false); addWindowListener(new xxxhelp(this)); } } class handlemouse extends MouseAdapter //处理右键弹出菜单类 { myfr fx; handlemouse(myfr fxx){ fx=fxx; } public void mouseReleased(MouseEvent n){ if(n.isPopupTrigger()) fx.popm.show((Component)n.getSource(),n.getX(),n.getY()); } }
JAVA语言课程设计报告 题 目:记事本的制作 设 计 者: 专业班级: 学 号: 2012年 12 月 24 日 目录 1、系统需求分析 3 2.系统总体设计 3 3 系统详细设计 5 4软件测试 13 5 系统总结 13 6系统设计心得体会 13 7参考文献 13 1、系统需求分析 1.1系统名称: Window记事本 1.2系统介绍: 开发一个window记事本,主要有一个主界面及以下功能: 1:文件的新建,打开,保存,打印,另存等; 2:对文件的编辑,如全选,复制,剪切,粘贴等; 3:对文件的格式操作,如自动换行,字体等; 4:帮助,包括帮助主题,关于。 1.3开发环境 Eclipse 2.系统总体设计 2.1 系统功能结构图 2.2系统文件结构图 2.3系统编辑结构图 2.4系统格式、帮助结构图 3 系统详细设计 3.1.主界面 主界面主要是用于对选择相应的功能进行相应的功能,主界面主要包括文件,编辑,格式,帮助四个下拉菜单功能。 重要代码: ①创建界面,安装各种监听器 public Notebook() { setTitle("记事本 -- 刘兴钢"); con=getContentPane(); text=new JTextArea(); JSPane=new JScrollPane(text); createMenu(); createPopupMenu(); setJMenuBar(mainMenuBar); con.add(JSPane,BorderLayout.CENTER); text.setComponentPopupMenu(popMenu); text.getDocument().addDocumentListener(this); text.addKeyListener(new handleKey()); text.addMouseListener(new handleMouse()); setSize(400,300); setVisible(true); ② 菜单代码 public void createMenu(){ //创建JMenuBar mainMenuBar=new JMenuBar(); //创建四个JMenu fileMenu=new JMenu("文件"); editMenu=new JMenu("编辑"); formatMenu=new JMenu("格式"); helpMenu=new JMenu("帮助"); 3.2.字体设计界面 主要代码 import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.awt.*; public class fontDialog extends JDialog implements ActionListener,ListSelectionListener{ public static final int Cancle=0; public static final int OK=1; public static final String [] style={"正常","斜体","粗体","粗斜体"}; public static final String [] size={"8","9","10","11","12","14","16", "18","20","22","24","26","28","36","48","72"}; private Font userFont=null; private int userSelect=Cancle; private JFrame parent=null; private Container con; private JScrollPane nameSPane,styleSPane,sizeSPane; private JPanel panel[]; private JLabel nameLbl,styleLbl,sizeLbl; private JTextField nameText,styleText,sizeText; private JList nameList,styleList,sizeList; private JButton OKBtn,cancleBtn; public fontDialog() { this(null); } public fontDialog(JFrame owner){ super(owner,true); parent=owner; setTitle("字体"); con=getContentPane(); BoxLayout box=new BoxLayout(con,BoxLayout.Y_AXIS); con.setLayout(box); panel=new JPanel[4]; for(int i=0;i<3;i++){ panel[i]=new JPanel(); panel[i].setLayout(new GridLayout(1,3)); } panel[3]=new JPanel(); panel[3].setLayout(new FlowLayout()); nameLbl=new JLabel("字体"); styleLbl=new JLabel("字形"); sizeLbl=new JLabel("大小"); panel[0].add(nameLbl); panel[0].add(styleLbl); panel[0].add(sizeLbl); nameText=new JTextField("宋体"); nameText.setColumns(5); nameText.setEditable(false); styleText=new JTextField("正常"); styleText.setColumns(5); styleText.setEditable(false); sizeText=new JTextField("12"); sizeText.setColumns(5); sizeText.setEditable(false); panel[1].add(nameText); panel[1].add(styleText); panel[1].add(sizeText); GraphicsEnvironment eq = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] availableFonts= eq.getAvailableFontFamilyNames(); nameList=new JList(availableFonts); nameList.addListSelectionListener(this); nameSPane=new JScrollPane(nameList); styleList=new JList(style); styleList.addListSelectionListener(this); styleSPane=new JScrollPane(styleList); sizeList=new JList(size); sizeList.addListSelectionListener(this); sizeSPane=new JScrollPane(sizeList); panel[2].add(nameSPane); panel[2].add(styleSPane); panel[2].add(sizeSPane); OKBtn=new JButton("确定"); OKBtn.addActionListener(this); cancleBtn=new JButton("取消"); cancleBtn.addActionListener(this); panel[3].add(OKBtn); panel[3].add(cancleBtn); for(int i=0;i<4;i++) con.add(panel[i]); } public int showFontDialog(){ setSize(300,300); int x,y; if (parent!=null){ x=parent.getX()+30; y=parent.getY()+30; }else{ x=150; y=100; } setLocation(new Point(x,y)); setVisible(true); return userSelect; } public Font getFont(){ return userFont; } public void actionPerformed(ActionEvent e){ int styleIndex=Font.PLAIN,fontSize; if(e.getSource()==OKBtn){ if(styleText.getText().equals("正常")) styleIndex=Font.PLAIN; if(styleText.getText().equals("斜体")) styleIndex=Font.ITALIC; if(styleText.getText().equals("粗体")) styleIndex=Font.BOLD; if(styleText.getText().equals("粗斜体")) styleIndex=Font.BOLD | Font.ITALIC; fontSize=Integer.parseInt(sizeText.getText()); userFont=new Font(nameText.getText(),styleIndex,fontSize); userSelect=OK; setVisible(false); }else{ userSelect=Cancle; setVisible(false); } } public void valueChanged(ListSelectionEvent e){ if (e.getSource()==nameList) nameText.setText((String)nameList.getSelectedValue()); if (e.getSource()==styleList) styleText.setText((String)styleList.getSelectedValue()); if (e.getSource()==sizeList) sizeText.setText((String)sizeList.getSelectedValue()); } } 3.3.保存界面 代码 int doSave(){ FileOutputStream fout; byte content[]; int flag; if (!haveName){ flag = doSaveAs(); }else if(changed){ try{ fout=new FileOutputStream(file); content=text.getText().getBytes(); fout.write(content); fout.close(); changed=false; flag = 1; }catch(FileNotFoundException e){ JOptionPane.showMessageDialog(this,"指定的文件名称或属性有问题!"); flag = 0; }catch(IOException e){ JOptionPane.showMessageDialog(this,"无法写文件,请检查文件是否被锁定"); flag = 0; } }else{ flag =1; } return flag; } 3.4.打印设计界面
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(); } }

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧