在对象间“广播消息”

来源:互联网 发布:千牛淘宝助手在哪里 编辑:程序博客网 时间:2024/04/30 05:08

最近在看金旭日老师的Java课程,为后期的通过Android实现某个项目做准备:

目标:完成  在对象之间“广播消息”http://www.jinxuliang.com/course/PPT/Show/5469992f137e420664f62752

参考:http://www.jinxuliang.com/course/PPT/Show/54699909137e420664f62751

界面依然用的是Swing Designer设计的:

//功能:在对象间“广播消息”//http://www.jinxuliang.com/course/PPT/Show/5469992f137e420664f62752import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.border.EmptyBorder;import javax.swing.JButton;import java.awt.Font;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class GUITest2 extends JFrame {private JPanel contentPane;/** * Launch the application. */public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {GUITest2 frame = new GUITest2();frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/** * Create the frame. */public GUITest2() {setTitle("\u4E3B\u7A97\u4F53");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100, 100, 450, 300);contentPane = new JPanel();contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));setContentPane(contentPane);contentPane.setLayout(null);JButton btnNewButton_Counter = new JButton("\u70B9\u51FB\u589E\u52A0\u8BA1\u6570\u503C");btnNewButton_Counter.setFont(new Font("微软雅黑", Font.PLAIN, 16));btnNewButton_Counter.setBounds(93, 121, 246, 48);contentPane.add(btnNewButton_Counter);JButton btnNewButton = new JButton("\u70B9\u51FB\u65B0\u5EFA\u4E00\u4E2A\u4ECE\u7A97\u4F53\u5BF9\u8C61");btnNewButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {BlankFrame frame=new BlankFrame(btnNewButton_Counter);//这里是要点:新的窗体的构造函数接收一个JButton对象frame.setVisible(true);//显示}});btnNewButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));btnNewButton.setBounds(93, 36, 246, 48);contentPane.add(btnNewButton);}/**   A blank frame that can be countered by clicking a button.*/static class BlankFrame extends JFrame{public BlankFrame(JButton Counter){counterTitle++;setTitle("从窗体"+counterTitle);setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);setLocation(SPACING * counterTitle, SPACING * counterTitle); JTextField Text=new JTextField();Text.setEditable(false);//不能编辑add(Text);//添加文本框String str=Integer.toString(counterNumber);Text.setText(str);//设置文本框默认值counterListener=new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubcounterNumber++;String str=Integer.toString(counterNumber);Text.setText(str);//修改按钮响应事件}};Counter.addActionListener(counterListener);}private ActionListener counterListener;private static int counterTitle = 0;private  int counterNumber = 0;public static final int DEFAULT_WIDTH = 200;public static final int DEFAULT_HEIGHT = 150; public static final int SPACING = 40;}}
结果:





0 0
原创粉丝点击