最近在看金旭日老师的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/5469992f137e420664f62752
import 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() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
counterNumber++;
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;
}
}
结果: