2.补充完整程序代码,实现如下图形用户界面。当在窗口中单击鼠标时,能显示鼠标位置坐标,当点击“Quit”按钮时,退出程序。import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AdapterTest extends JFrame implements ActionListener { int x,y; String str; JButton b; JLabel l; public AdapterTest(){ super("The Mouse Adapter"); getContentPane(). ; //设置流式布局 JPanel p=new JPanel(); l=new JLabel("Please click the window"); getContentPane().add(l); b=new JButton("Quit"); b. ; //注册按钮单击事件监听器 getContentPane().add(b); ListenerClass listen=new ListenerClass(); ; //注册框架的鼠标事件监听器 setSize(300,300); setVisible(true); } public void actionPerformed(ActionEvent ae){ String s= ; //获取按钮的标签字符串 if("Quit".equals(s)){ System.exit(0); } } public static void main(String args[]){ AdapterTest f=new AdapterTest(); } } class ListenerClass extends MouseAdapter{ public void mouseClicked(MouseEvent me){ AdapterTest at= ; //获取事件源对象 at.l.setText("Mouse clicked at: "+me.getX()+","+me.getY()); } }
时间: 2023-06-27 09:07:52 浏览: 151
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AdapterTest extends JFrame implements ActionListener {
int x,y;
String str;
JButton b;
JLabel l;
public AdapterTest(){
super("The Mouse Adapter");
getContentPane().setLayout(new FlowLayout()); //设置流式布局
JPanel p=new JPanel();
l=new JLabel("Please click the window");
getContentPane().add(l);
b=new JButton("Quit");
b.addActionListener(this); //注册按钮单击事件监听器
getContentPane().add(b);
ListenerClass listen=new ListenerClass();
addMouseListener(listen); //注册框架的鼠标事件监听器
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
String s=b.getText(); //获取按钮的标签字符串
if("Quit".equals(s)){
System.exit(0);
}
}
public static void main(String args[]){
AdapterTest f=new AdapterTest();
}
}
class ListenerClass extends MouseAdapter{
public void mouseClicked(MouseEvent me){
AdapterTest at=(AdapterTest)me.getSource(); //获取事件源对象
at.l.setText("Mouse clicked at: "+me.getX()+","+me.getY());
}
}
阅读全文