-
[자바프로그래밍] 인터페이스, 람다식, 패키지 // 미작성공부 2023. 6. 9. 14:42
package event; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; class MyFrame extends JFrame { private JButton button1; private JButton button2; private JButton button3; private JPanel panel; public MyFrame() { this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("이벤트 예제"); panel = new JPanel(); button1 = new JButton("노란색"); button1.addActionListener(new MyListener()); panel.add(button1); button2 = new JButton("핑크색"); button2.addActionListener(new MyListener()); panel.add(button2); button3 = new JButton("파랑색"); button3.addActionListener(new MyListener()); panel.add(button3); this.add(panel); this.setVisible(true); } private class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) { panel.setBackground(Color.YELLOW); } else if (e.getSource() == button2) { panel.setBackground(Color.PINK); } else if (e.getSource() == button3) { panel.setBackground(Color.BLUE); } } } } public class ChangeBackground { public static void main(String[] args) { MyFrame t = new MyFrame(); } }
인터페이스의 정의
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class KeyPad extends JFrame implements ActionListener { private JTextField txt; private JPanel panel; KeyPad() { txt = new JTextField(20); add(txt, BorderLayout.NORTH); panel = new JPanel(); panel.setLayout(new GridLayout(0, 3)); add(panel, BorderLayout.CENTER); for(int i=0; i<=9; i++) { JButton btn = new JButton("" + i); btn.addActionListener(this); btn.setPreferredSize(new Dimension(100, 100)); panel.add(btn); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } } @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command.charAt(0)== 'C') txt.setText(""); else txt.setText(txt.getText() + command); } }
'공부' 카테고리의 다른 글
[JSP] CheckBox (0) 2023.09.12 [JSP] Login (0) 2023.09.12 [자바프로그래밍] 이벤트 처리 (0) 2023.06.02 [자바프로그래밍] 그래픽 사용자 인터페이스 (0) 2023.06.02 [웹 프로그래밍] DOM (0) 2023.06.01