import javax.swing.*; import java.awt.*; import java.io.*; import java.awt.event.*; public class Editor extends JFrame implements ActionListener { JPanel Panel = new JPanel(); JTextArea editor = new JTextArea(30, 60); JMenuItem kaiti = new JMenuItem("楷体"); JMenuItem lishu = new JMenuItem("隶书"); JMenuItem yahei = new JMenuItem("微软雅黑"); Editor() { super("文本编辑器 "); setBounds(250, 100, 700, 450); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { int option = JOptionPane.showConfirmDialog(Editor.this, "确定要退出吗? ", "Warning ", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) if (e.getWindow() == Editor.this) { System.exit(0); } else { return; } } }); add(new JScrollPane(editor));// ); editor.setFont(new Font("宋体", Font.PLAIN, 20)); JMenuBar wenben = new JMenuBar(); this.setJMenuBar(wenben); wenben.setOpaque(true); JMenu custom = new JMenu("自定义"); JMenu OptionM = new JMenu("字体"); custom.add(OptionM); OptionM.add(kaiti); OptionM.add(lishu); OptionM.add(yahei); wenben.add(custom); kaiti.addActionListener(this); lishu.addActionListener(this); yahei.addActionListener(this); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String actionCommand = e.getActionCommand(); if (e.getSource() instanceof JMenu) { if (e.getSource() == kaiti) { editor.setFont(new Font("楷体", Font.PLAIN, editor.getFont().getSize())); } else if (e.getSource() == lishu) { editor.setFont(new Font("隶书", Font.PLAIN, editor.getFont().getSize())); } else if (e.getSource() == yahei) { editor.setFont(new Font("微软雅黑", Font.PLAIN, editor.getFont().getSize())); } } } }
还是说这写不行。求指教,就是actionPerformed不执行。
//我发现在if (e.getSource() instanceof JMenu)的后面加上分号就可以运行了,这是什么原因呢
你试试用匿名 内部类 来监听:
看起来是swing
的代码,但你贴的实在不全,也不知道你需求是什么?哪段没执行?