172day(动作)

《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);
		});
		
	}
}

 

 

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值