mojo's Blog
JComboBox, Action 이벤트를 이용한 콤보박스 활용 본문
JComboBox 연습 코드
import javax.swing.*; // JFrame
import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;
import java.awt.*;
public class ComboBoxEx extends JFrame{
private String[] fruits= {"apple","banana","kiwi","mango","pear",
"peach","berry","strawberry","blackberry"};
private String[] names= {"kitae","jaemoon","hyosoo","namyun"};
ComboBoxEx(){
setTitle("11장 연습");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
JComboBox<String> strCombo=new JComboBox<String>(fruits);
c.add(strCombo);
JComboBox<String> nameCombo = new JComboBox<String>();
for(int i=0;i<names.length;i++) {
nameCombo.addItem(names[i]);
}
c.add(nameCombo);
setSize(300, 300); // 프레임 크기 300x300
setVisible(true); // 프레임 출력
c.setFocusable(true);
c.requestFocus();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ComboBoxEx();
}
}
Action 이벤트를 이용한 콤보박스 활용 예
import javax.swing.*; // JFrame
import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;
import java.awt.*;
public class ComboBoxEx extends JFrame{
private String[] fruits= {"apple","bear","cherry"};
private ImageIcon[] images= {
new ImageIcon("C:\\Temp/apple.jpg"),
new ImageIcon("C:\\Temp/bear.jpg"),
new ImageIcon("C:\\Temp/cherry.png")
};
private JLabel imgLabel = new JLabel(images[0]);
private JComboBox<String> strCombo=new JComboBox<String>(fruits);
ComboBoxEx(){
setTitle("11장 연습");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(strCombo);
c.add(imgLabel);
strCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox<String> cb=(JComboBox<String>)e.getSource();
int index=cb.getSelectedIndex();
imgLabel.setIcon(images[index]);
}
});
setSize(300, 300); // 프레임 크기 300x300
setVisible(true); // 프레임 출력
c.setFocusable(true);
c.requestFocus();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ComboBoxEx();
}
}
'Java' 카테고리의 다른 글
명품 JAVA Programming 제 11장 Open Challenge (0) | 2021.07.29 |
---|---|
JSlider, 슬라이더 컴포넌트 (0) | 2021.07.29 |
JList, JList의 아이템 변경하기 (0) | 2021.07.29 |
JTextField, JTextArea (0) | 2021.07.29 |
JCheckBox / JRadioButton 연습하기 (0) | 2021.07.28 |
Comments