mojo's Blog

명품 JAVA Programming 제 11장 실습문제 6번 본문

Java

명품 JAVA Programming 제 11장 실습문제 6번

_mojo_ 2021. 7. 29. 12:45

code

import javax.swing.*; // JFrame
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
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.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;
import java.awt.*;

public class MyFrame extends JFrame{
	
	private JTextArea ta;
	private JSlider sl;
	
	MyFrame(){
		setTitle("11장 실습문제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());

		ta=new JTextArea(5, 20);
		c.add(ta);
		c.add(new JScrollPane(ta));
		
		ta.addKeyListener(new KeyAdapter() {

			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
				String s=ta.getText();
				sl.setValue(s.length());
			}
			
		});
		
		sl = new JSlider(JSlider.HORIZONTAL,0,100,0);
		// JSlider의 메소드를 호출하여 슬라디어 모양을 제어함
		sl.setPaintLabels(true);
		sl.setPaintTicks(true); 
		sl.setPaintTrack(true);
		sl.setMajorTickSpacing(20); // 수치상으로 50씩 간격
		sl.setMinorTickSpacing(5); // 눈금으로 10씩 간격
		
		c.add(sl);
		
		sl.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				// TODO Auto-generated method stub
				String s=ta.getText();
				JSlider js=(JSlider)e.getSource();
				int len = js.getValue();
				
				String tmp="";
				for(int i=0;i<len;i++) {
					if(i>=s.length()) break;
					tmp+=s.charAt(i);
				}
				
				ta.setText(tmp);
			}
			
		});
		
		setSize(300, 300); // 프레임 크기 300x300
		setVisible(true); // 프레임 출력
		
		c.setFocusable(true);
		c.requestFocus();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MyFrame();
	}

}
Comments