可与用户进行界面交互的监视器
作者:互联网
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Main{ public static void main(String[] args) { WindowView win=new WindowView(); win.setBounds(100,100,600,460); win.setTitle("监视器在文本区中显示"); } } ////// class WindowView extends JFrame{ JTextField textField; JTextArea textArea; JButton button; Listener listener; public WindowView(){ init(); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } void init(){ setLayout(new FlowLayout()); Font font=new Font("JetBrain",Font.PLAIN,20); textField=new JTextField(20); textField.setFont(font); button=new JButton("确定"); button.setFont(font); textArea=new JTextArea(9,30); listener=new Listener(); listener.setView(this);//将当前窗口传递给listener的窗口 textField.addActionListener(listener); button.addActionListener(listener); add(textField); add(button); add(new JScrollPane(textArea));//将文本区放到滚动窗格中 } } class Listener implements ActionListener{ WindowView view; public void setView(WindowView a){ this.view=a; } public void actionPerformed(ActionEvent e){ if(e.getSource()==view.textField){//ActionEvent的对象调用getSource()方法会获取发生该事件的事件源的一个对象的引用 String str=view.textField.getText(); view.textArea.append("\""+str+"\"的长度:"+str.length()+"\n"); } else if(e.getSource()==view.button){ String str=view.button.getText(); view.textArea.append(str+"\n"); } } }
标签:界面,button,listener,监视器,new,textField,交互,WindowView,view 来源: https://www.cnblogs.com/hzzzz/p/16297127.html