728x90

 

MouseClickedEvents 보다 ActionListener를 더 많이 사용함

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class My implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e){
        JButton b=(JButton) e.getSource(); //이벤트가 어디서 발생했니? = Jbutton에서!

        if(b.getText().equals("클릭")){ //이벤트가 발생한 버튼명 알아냄
           b.setText("click");
        }
        else
            b.setText("클릭");
        
    }
}

public class Test1 extends JFrame {
    Test1(){
        Container c= getContentPane();
        c.setLayout(new FlowLayout());

        JButton j1 = new JButton("클릭");

        c.add(j1);
        setVisible(true);

        j1.addActionListener(new My());

    }

    public static void main(String[] args) {

        new Test1();
    }
}

 

 

 

 

 

버튼 비활성

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Test1 extends JFrame {
    Test1(){
        Container c= getContentPane();
        c.setLayout(new FlowLayout());

        JButton j1 = new JButton("ok");
        JButton j2 = new JButton("cancle");

        c.add(j1);
        c.add(j2);
        setVisible(true);


        j1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("ok");
            }
        });

        j2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                j2.setEnabled(false); // 버튼 비활성화
            }
        });
    }

    public static void main(String[] args) {

        new Test1();
    }
}

 

 

드래그 할 때 색 변환

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;

class Mouse extends MouseAdapter{
	@Override
	public void mouseDragged(MouseEvent e) {
		Container c=(Container)e.getSource();
		c.setBackground(Color.yellow);
	}	
	@Override
	public void mouseReleased(MouseEvent e) {
		Container c=(Container)e.getSource();
		c.setBackground(Color.pink);
	}	
}
public class Test1 extends JFrame{
	Test1(){
		Container c=getContentPane();
		c.setLayout(new FlowLayout());
		c.setBackground(Color.pink);
	
		setVisible(true);
		
		c.addMouseListener(new Mouse());
		c.addMouseMotionListener(new Mouse());
		
	}
		
	public static void main(String[] args) {	
		new Test1();
	}
}
728x90

+ Recent posts