理论知识部分
1.监听器:监听器类必须实现与事件源相对应的接口,即必须提供接口中方法的实现。
监听器接口方法实现
class Mylistener implements ActionListener { public void actionPerformed (ActionEvent event) { …… } }
2.用匿名类、lambda表达式简化程序:
例ButtonTest.java中,各按钮需要同样的处理:
a.使用字符串构造按钮对象;
b.把按钮添加到面板上;
c.用对应的颜色构造一个动作监听器;
d.注册动作监听器。
3.适配器类:
当程序用户试图关闭一个框架窗口时,Jframe 对象就是WindowEvent的事件源。
捕获窗口事件的监听器:
WindowListener listener=…..; frame.addWindowListener(listener);
注册事件监听器:
可将一个Terminator对象注册为事件监听器:
WindowListener listener=new Terminator();
frame.addWindowListener(listener);
4.动作事件:
Swing包提供了非常实用的机制来封装命令,并将它们连接到多个事件源,这就是Action接口。
动作对象是一个封装下列内容的对象:
–命令的说明:一个文本字符串和一个可选图标;
–执行命令所需要的参数。
5.鼠标事件:
鼠标事件 – MouseEvent
鼠标监听器接口
– MouseListener
– MouseMotionListener
鼠标监听器适配器
– MouseAdapter
– MouseMotionAdapter
实验部分:
实验1:
测试程序1:
package button; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class ButtonTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new ButtonFrame();//构建一个ButtonFrame类对象 frame.setTitle("ButtonTest");//设置Title属性,确定框架标题栏中的文字 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭 frame.setVisible(true);//设置Visible属性,组件可见 }); } }
package button; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A frame with a button panel */ public class ButtonFrame extends JFrame { private JPanel buttonPanel; private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; public ButtonFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // 创建按钮 JButton yellowButton = new JButton("Yellow"); JButton blueButton = new JButton("Blue"); JButton redButton = new JButton("Red"); buttonPanel = new JPanel(); // 添加按钮到面板 buttonPanel.add(yellowButton);//调用add方法将按钮添加到面板 buttonPanel.add(blueButton); buttonPanel.add(redButton); // 添加面板到框架 add(buttonPanel); // 创建按钮事件 ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED); // 将时间与按钮关联 yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); } /** * An action listener that sets the panel's background color. */ private class ColorAction implements ActionListener//实现了ActionListener的接口类 { private Color backgroundColor; public ColorAction(Color c) { backgroundColor = c; } public void actionPerformed(ActionEvent event)//actionListener方法接收一个ActionEvent对象参数 { buttonPanel.setBackground(backgroundColor); } } }
输出结果:
测试程序2:
package plaf; import java.awt.*; import javax.swing.*; /** * @version 1.32 2015-06-12 * @author Cay Horstmann */ public class PlafTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new PlafFrame();//构建一个PlafFrame类对象 frame.setTitle("PlafTest");//设置Title属性,确定框架标题栏中的文字 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭 frame.setVisible(true);//设置Visible属性,组件可见 }); } }
package plaf; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * A frame with a button panel for changing look-and-feel */ public class PlafFrame extends JFrame { private JPanel buttonPanel; public PlafFrame() { buttonPanel = new JPanel(); UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();//获得一个用于描述已安装的观感实现的对象数组 for (UIManager.LookAndFeelInfo info : infos) makeButton(info.getName(), info.getClassName());//返回观感的显示名称,返回观感实现类的名称 add(buttonPanel); pack(); } /** * Makes a button to change the pluggable look-and-feel. * @param name the button name * @param className the name of the look-and-feel class */ private void makeButton(String name, String className) { // 添加按钮到面板 JButton button = new JButton(name); buttonPanel.add(button); // 设置按钮事件 button.addActionListener(event -> { // 按钮动作:切换到新的外观 try { UIManager.setLookAndFeel(className); SwingUtilities.updateComponentTreeUI(this); pack(); } catch (Exception e) { e.printStackTrace(); } }); }//使用辅助方法makeButton和匿名内部类指定按钮动作 }
输出结果:
测试程序3:
package action; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class ActionTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new ActionFrame();//构建一个ActionFrame类对象 frame.setTitle("ActionTest");//设置Title属性,确定框架标题栏中的文字 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭 frame.setVisible(true);//设置Visible属性,组件可见 }); } }
package action; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A frame with a panel that demonstrates color change actions. */ public class ActionFrame extends JFrame { private JPanel buttonPanel; private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; public ActionFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); buttonPanel = new JPanel(); // 定义操作 Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW); Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); // 为这些操作添加按钮 buttonPanel.add(new JButton(yellowAction)); buttonPanel.add(new JButton(blueAction)); buttonPanel.add(new JButton(redAction)); // 将面板添加到框架 add(buttonPanel); // 将Y、B和R键与名称关联起来 InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);//获得将按键映射到动作键的输入映射 imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");//根据一个便于人们阅读的说明创建一个按钮(由空格分隔的字符串序列) imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue"); imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red"); // 将名称与操作关联起来 ActionMap amap = buttonPanel.getActionMap();//返回关联动作映射键和动作对象的映射 amap.put("panel.yellow", yellowAction); amap.put("panel.blue", blueAction); amap.put("panel.red", redAction); } public class ColorAction extends AbstractAction { /** * Constructs a color action. * @param name the name to show on the button * @param icon the icon to display on the button * @param c the background color */ public ColorAction(String name, Icon icon, Color c) { putValue(Action.NAME, name);//将名/值放置在动作对象内 putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase()); putValue("color", c); } public void actionPerformed(ActionEvent event) { Color c = (Color) getValue("color");//返回被存储的名对的值 buttonPanel.setBackground(c); } } }
输出结果:
测试程序4:
package mouse; import java.awt.*; import javax.swing.*; /** * @version 1.34 2015-06-12 * @author Cay Horstmann */ public class MouseTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new MouseFrame();//构建一个MouseFrame类对象 frame.setTitle("MouseTest");//设置Title属性,确定框架标题栏中的文字 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭 frame.setVisible(true);//设置Visible属性,组件可见 }); } }
package mouse; import javax.swing.*; /** * A frame containing a panel for testing mouse operations */ public class MouseFrame extends JFrame { public MouseFrame() { add(new MouseComponent()); pack(); } }
package mouse; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.*; import javax.swing.*; /** * A component with mouse operations for adding and removing squares. */ public class MouseComponent extends JComponent { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private static final int SIDELENGTH = 10; private ArrayList<Rectangle2D> squares; private Rectangle2D current; // 包含鼠标光标的正方形 public MouseComponent() { squares = new ArrayList<>(); current = null; addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // 画出所有方块 for (Rectangle2D r : squares) g2.draw(r); } /** * Finds the first square containing a point. * @param p a point * @return the first square that contains p */ public Rectangle2D find(Point2D p) { for (Rectangle2D r : squares) { if (r.contains(p)) return r; } return null; } /** * Adds a square to the collection. * @param p the center of the square */ public void add(Point2D p) { double x = p.getX(); double y = p.getY(); current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); squares.add(current); repaint(); } /** * Removes a square from the collection. * @param s the square to remove */ public void remove(Rectangle2D s) { if (s == null) return; if (s == current) current = null; squares.remove(s); repaint(); } private class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent event) { // 如果光标不在正方形内,则添加一个新的正方形 current = find(event.getPoint()); if (current == null) add(event.getPoint()); } public void mouseClicked(MouseEvent event) { // 如果双击,则删除当前方块 current = find(event.getPoint()); if (current != null && event.getClickCount() >= 2) remove(current); } } private class MouseMotionHandler implements MouseMotionListener { public void mouseMoved(MouseEvent event) { // 如果鼠标指针在内部,则将其设置为十字线 // 一个矩形 if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor()); else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); } public void mouseDragged(MouseEvent event) { if (current != null) { int x = event.getX(); int y = event.getY(); // 拖动当前矩形到(x, y)的中心 current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); repaint(); } } } }
输出结果:
实验2:结对编程练习
结对编程伙伴:冯志霞
import java.util.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt.Frame; import java.io.File; import java.io.FileNotFoundException; public class Dianmingqi extends JFrame implements ActionListener { private JButton but; private JButton show; private static boolean flag = true; public static void main(String arguments[]) { new Dianmingqi(); } public Dianmingqi() { but = new JButton("START"); but.setBounds(100, 150, 100, 40); show = new JButton("开始点名"); show.setBounds(80, 80, 180, 30); show.setFont(new Font("宋体", Font.BOLD, 30)); add(but); add(show); setLayout(null);// 布局管理器必须先初始化为空才能赋值 setVisible(true); setResizable(false); setBounds(100, 100, 300, 300); //setBackground(Color.red);不起作用 this.getContentPane().setBackground(Color.cyan); setTitle("START"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); but.addActionListener(this); } public void actionPerformed(ActionEvent e) { int i = 0; String names[] = new String[50]; try { Scanner in = new Scanner(new File("studentnamelist.txt")); while (in.hasNextLine()) { names[i] = in.nextLine(); i++; } } catch (FileNotFoundException e1) { e1.printStackTrace(); } if (but.getText() == "START") { show.setBackground(Color.BLUE); flag = true; new Thread() { public void run() { while (Dianmingqi.flag) { Random r = new Random(); int i = r.nextInt(47); show.setText(names[i]); } } }.start(); but.setText("STOP");// 更改文本内容 but.setBackground(Color.YELLOW); } else if (but.getText() == "STOP") { flag = false; but.setText("START"); but.setBackground(Color.WHITE); show.setBackground(Color.GREEN); } } }
实验总结:
这个周的结对编程练习,由于对很多知识的不理解,无法完全实现编程题的内容,我深感自己的不足。对于代码中的一些方法还不是能够完全理解。
package 点名器; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.List; import javax.swing.JFrame; import java.util.ArrayList; public class RollCaller extends JFrame{ private String fileName="studentnamelist.txt"; private File f; private FileReader fr; private BufferedReader br; private List<String> names=new ArrayList<String>(); private String Name; private Label labelName; private Button button; public static void main(String[] args) { RollCaller rollcaller=new RollCaller(); rollcaller.newFrame(); rollcaller.read(); } public void newFrame() { labelName=new Label("随机点名"); button=new Button("START"); this.setLocation(300,300); this.setResizable(true);//设置此窗体是否可由用户调整大小。 this.setSize(1000,800); this.add(labelName,BorderLayout.NORTH); this.add(button,BorderLayout.CENTER); this.pack(); this.setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); button.addActionListener(new ButtonAction()); } public void read() { try{ f=new File(fileName); if(!f.exists()){ f.createNewFile(); } fr=new FileReader(f); br=new BufferedReader(fr); String str=br.readLine(); while(str!=null){ names.add(str); str=br.readLine(); } }catch(Exception e){ e.printStackTrace(); } } public void name() { try{ int index=(int)(Math.random()*names.size()); Name=names.get(index); }catch(Exception e){ e.printStackTrace(); } } private class ButtonAction implements ActionListener{ public void actionPerformed(ActionEvent e){ name(); labelName.setText(Name); } } }
这次的作业,我在网络中查询了很多,
通过在网上查询,我查到了BufferedReader由Reader类扩展而来,提供文本读取。
还有label对象是一个可在容器中放置文本的组件。一个标签只显示一行只读文本。文本可由应用程序更改,但是用户不能直接对其进行编辑。
但是这个代码还存在着很多问题,对于很多知识我还需更多的掌握,不论是从程序的实用,还是外观,都还需更加深入的学习。