mojo's Blog

JList, JList의 아이템 변경하기 본문

Java

JList, JList의 아이템 변경하기

_mojo_ 2021. 7. 29. 10:26

JList 연습 code

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.awt.*;

public class ListEx extends JFrame{

	private String []fruits= {"apple","banana","kiwi","mango","pear",
			"peach","berry","strawberry","blackberry"};
	private ImageIcon []images= {new ImageIcon("C:\\Temp/apple.jpg"),
								new ImageIcon("C:\\Temp/bear.jpg"),
								new ImageIcon("C:\\Temp/cherry.png")};
	
	ListEx(){
		setTitle("11장 연습");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
	
		JList<String> strList = new JList<String>(fruits);
		c.add(strList);
		
		JList<ImageIcon> imageList = new JList<ImageIcon>(images);
		imageList.setListData(images);
		c.add(imageList);
		
		JList<String> scrollList=new JList<String>(fruits);
		c.add(new JScrollPane(scrollList));
		
		setSize(350, 450); // 프레임 크기 300x300
		setVisible(true); // 프레임 출력
		
		c.setFocusable(true);
		c.requestFocus();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new ListEx();
	}

}

 

JList 아이템 변경하기 코드

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 ListEx extends JFrame{

	private JTextField tf=new JTextField(10);
	private Vector<String> v=new Vector<String>();
	private JList<String> nameList=new JList<String>(v);
	
	ListEx(){
		setTitle("11장 연습");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
	
		c.add(new JLabel("이름 입력 후 <Enter> 키"));
		c.add(tf);
		
		v.add("황기태");
		v.add("이재문");
		nameList.setVisibleRowCount(5);
		nameList.setFixedCellWidth(100);
		c.add(new JScrollPane(nameList));
		
		tf.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JTextField t=(JTextField)e.getSource();
				v.add(t.getText());
				t.setText("");
				nameList.setListData(v);
			}
		});
		
		setSize(300, 300); // 프레임 크기 300x300
		setVisible(true); // 프레임 출력
		
		c.setFocusable(true);
		c.requestFocus();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new ListEx();
	}

}
Comments