您好,登錄后才能下訂單哦!
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class TestEventMouse extends JFrame{
Container contentPanel; //內容格引用
JButton a1,a2,a3,a4,a5;//按鈕
JRadioButton backGroundRadio,foreGroundRadio; //定義兩個單選框
ButtonGroup radioGroup; //單選按鈕組
int xValue,yValue; //保留鼠標位置(x,y)
JFrame jf=this;
public TestEventMouse(){ //構造函數
super("寫字板");
a1=new JButton("Black");//實現五個按鈕
a2=new JButton("Blue");
a3=new JButton("Red");
a4=new JButton("White");
a5=new JButton("Yellow");
contentPanel=this.getContentPane();//獲取內容格
contentPanel.setLayout(new FlowLayout());//設置內容格的布局管理器
backGroundRadio=new JRadioButton("backGround"); //實例化復選框
foreGroundRadio=new JRadioButton("foreGround");
contentPanel.add(backGroundRadio);//添加到內容格里面去
contentPanel.add(foreGroundRadio);
contentPanel.add(a1);//添加按鈕
contentPanel.add(a2);
contentPanel.add(a3);
contentPanel.add(a4);
contentPanel.add(a5);
MouseListenerHandler mou=new MouseListenerHandler(); //實現一個事件監聽類
a1.addMouseListener(mou); //注冊為五個按鈕的監聽者
a2.addMouseListener(mou);
a3.addMouseListener(mou);
a4.addMouseListener(mou);
a5.addMouseListener(mou);
radioGroup=new ButtonGroup(); //實例單選按鈕組
radioGroup.add(backGroundRadio);//將兩個radio按鈕構成一個組
radioGroup.add(foreGroundRadio);
addMouseMotionListener( //匿名類
new MouseMotionAdapter(){ //因為是當前一個對象調用,所以搞了個適配器玩玩
public void mouseDragged(MouseEvent e){
xValue=e.getX();
yValue=e.getY();
repaint(); //調用paint()方法
}
}
);
setSize(500,500);
setVisible(true); //設置可見
}
public class MouseListenerHandler implements MouseListener{ //鼠標事件監聽類
public void mousePressed(MouseEvent e){
if(e.getSource()==a1){ //用getSouce()獲取對象
if(backGroundRadio.isSelected())
contentPanel.setBackground(Color.BLACK);//用內容格來設置背景色
else
jf.setForeground(Color.BLACK); //用Frame框架來設置前景色
}
if(e.getSource()==a2){
if(backGroundRadio.isSelected())
contentPanel.setBackground(Color.BLUE);
else
jf.setForeground(Color.BLUE);
}
if(e.getSource()==a3){
if(backGroundRadio.isSelected())
contentPanel.setBackground(Color.RED);
else
jf.setForeground(Color.RED);
}
if(e.getSource()==a4){
if(backGroundRadio.isSelected())
contentPanel.setBackground(Color.WHITE);
else
jf.setForeground(Color.WHITE);
}
if(e.getSource()==a5){
if(backGroundRadio.isSelected())
contentPanel.setBackground(Color.YELLOW);
else
jf.setForeground(Color.YELLOW);
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
public void paint(Graphics g){
g.fillOval(xValue, yValue, 4, 4);
}
public static void main(String args[]){
new TestEventMouse();
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。