标签:
import javax.swing.*; import java.awt.event.*; import java.awt.*; public class TouChaCol implements ActionListener{ JFrame frame; public static void main(String [] args){ TouChaCol game = new TouChaCol(); game.go(); } public void go(){ frame = new JFrame(); JButton button = new JButton("Can you touch me?"); button.addActionListener(this); Panel aPanel = new Panel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(BorderLayout.SOUTH,button); frame.getContentPane().add(BorderLayout.CENTER,aPanel); frame.setSize(300, 300); frame.setVisible(true); } public void actionPerformed(ActionEvent event){ frame.repaint(); } }
查询java api文档:
ActionEvent 类 来自java.awt.event
JFrame,JButton 类来自javax.swing
接口 ActioListener来自java.awt.event
BorderLayout 类 来自java.awt 用法:BorderLayout.SOUTH/CENTER...详见文档
import javax.swing.*; import java.awt.*; public class Panel extends JPanel{ public void paintComponent(Graphics g){ int red = (int)(Math.random() * 255); int green = (int)(Math.random() * 255); int blue = (int)(Math.random() * 255); Color myColor = new Color(red,green,blue); g.setColor(myColor); g.fillOval(70,70, 100, 100); } }
让Panel继承JPanel,覆盖它的paintComponent(Graphics g)方法则可以按照自己的意思画图
整体思想:
建一个类TouChaCol
分别建1个 JFrame ,Panel(继承过JPanel)和 button的对象
再将后两者的对象放到JFrame对象上,将button的监听者设为TouChaCol的对象(该对象即为ActionListener)
所以要在该对象的类中实现接口ActionListener中的actionPerformed(ActionEvent e)方法作为事件处理方法(e即为button被按了一下)
特意将frame设为实例变量,不用是不行的
标签:
原文地址:http://www.cnblogs.com/gabygoole/p/4910126.html