스윙 컴포넌트

package ch11;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class JComponentEx extends JFrame {
	
	private JButton b1, b2, b3;
	
	
	public JComponentEx(){
		setTitle("JComponent의 공통 메소드 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		
		b1 = new JButton("Magenta/Yellow Button");
		b2 = new JButton("___Disabled Button___");
		b3 = new JButton("getX(), getY()");
		
		b1.setBackground(Color.YELLOW); // 백그라운드
		b1.setForeground(Color.MAGENTA); // 포그라운드
		b1.setFont(new Font("Arial", Font.ITALIC, 20));
		b2.setEnabled(false);
		b3.addActionListener(new ActionListener() {
			
			//타겟 (콜백되는)
			@Override
			public void actionPerformed(ActionEvent e) {
				//JButton b = (JButton)e.getSource(); // Object를 리턴하기 때문에 다운캐스팅!!
				b3.setText("hello");
				//JComponentEx frame = (JComponentEx)b.getTopLevelAncestor();
				//frame.setTitle(b.getX() + "," + b.getY());
			}
		});
		
		c.add(b1); c.add(b2); c.add(b3);
		
		setSize(260, 200);
		setVisible(true);
		
		
		
	}
	
	public static void main(String[] args) {
		new JComponentEx();
	}
}

 

여러 버튼에 같은 리스너 적용

package ch11;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class JComponentEx01 extends JFrame implements ActionListener{

	private JButton b1, b2, b3;
	
	// 타겟
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton b = (JButton) e.getSource();
		b.setText("Hello");
	}
	
	public JComponentEx01() {
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		
		b1 = new JButton("b1");
		b2 = new JButton("b2");
		b3 = new JButton("b3");
		
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		
		c.add(b1);
		c.add(b2);
		c.add(b3);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(260, 200);
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new JComponentEx01();
	}

}

.

+ Recent posts