《2018年4月1日》【连续172天】
标题:动作;
内容:
1.
2.
EventQueue简单工作原理
简单来讲,在EventQueue中有一个dispatchThread,这是一个线程类,负责事件的分发,当Queue中有事件的时候,它会摘取前面的事件并分发给相应的对象进行处理,等处理完之后再获取下一个,当Queue中没有事件的时候,线程等待。
当有事件触发时,系统会调用EventQueue的push方法将AWTEvent添加到EventQueue的最后,同时唤醒dispatchThread。
为什么界面会死掉
所以可以看到,Swing的事件分发实际上是同步的,并且都是在dispatchThread这个线程中处理的,也就是说是一个事件一个事件处理的,如果有某一个事件处理的时间非常长的时侯,其他事件就会被堵塞在那里,从现象上看得话,就是界面会死掉,如果界面被其他窗口覆盖之后再回到前面的时侯,会变成一片灰色,这是因为PaintEvent被堵塞而不能被分发出去的缘故。
3.
一个简单的将设置可以控制背景的按钮:
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);
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
{
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);
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(() ->
{
JFrame frame =new ActionFrame();
frame.setTitle("Action");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}