반응형
package hello;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class FileInputStreamTest1 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String src = "c:\\windows\\system.ini";
		try {
			Scanner fileScanner = new Scanner(new FileReader(src));
			String line;
			int lineNumber = 1;
			while(fileScanner.hasNext()) {
				line = fileScanner.nextLine();
				System.out.printf("%4d", lineNumber++);
				System.out.println(":" + line);
			}
			fileScanner.close();
		} catch (FileNotFoundException e) {
			System.out.println("파일을 찾을 수 없습니다.");
		} catch (NoSuchElementException e) {
			System.out.println("파일의 끝에 도달하여 읽을 내용이 없습니다.");
		}finally {
			scanner.close();
		}
	}
}
   1:; for 16-bit app support
   2:[386Enh]
   3:woafont=dosapp.fon
   4:EGA80WOA.FON=EGA80WOA.FON
   5:EGA40WOA.FON=EGA40WOA.FON
   6:CGA80WOA.FON=CGA80WOA.FON
   7:CGA40WOA.FON=CGA40WOA.FON
   8:
   9:[drivers]
  10:wave=mmdrv.dll
  11:timer=timer.drv
  12:
  13:[mci]
반응형
반응형

1. FileOutputStream으로 바이너리 파일 쓰기

package hello;
import java.io.*;
public class FileOutputStreamEx {
	public static void main(String[] args) {
		byte b[] = {7, -51, 3, 4, -1, -2, 24};
		
		try {
			FileOutputStream fout = new FileOutputStream("c:\\Temp\\test.out");
			for(int i=0; i<b.length; i++) {
				fout.wait(b[i]); //배열  b의 바이너리를 그대로 기록 
			}
			fout.close();
		} catch (Exception e) {
			System.out.println("c:\\Temp\\test.out을 저장하였습니다.");
		}
	}
}

 

2. 코드 차이분석 24 | - FileInputStream

1)

package hello;
import java.io.FileInputStream;
public class Ex10_09 {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("c:/Temp/data1.txt");
		int ch;
		
		while((ch = fis.read()) != -1) {
			System.out.print((char) ch);
		}
		
		fis.close();
	}
}
File Read Sample ??´?´?.

2)

package hello;
import java.io.FileInputStream;
public class Ex10_09 {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("c:/Temp/data1.txt");
		int ch;
		
		while((ch = fis.read()) != -1) {
			System.out.println((char) ch);
		}
		
		fis.close();
	}
}
File Read Sample 입니다.

 

반응형

'JAVA' 카테고리의 다른 글

[자바] Thread  (0) 2020.01.19
[자바]이벤트와 메뉴  (0) 2020.01.18
[자바] Gui 프로그래밍  (0) 2020.01.18
반응형

1. Thread를 상속받아 1초 단위 타이머 스레드 만들기

package hello;
import java.awt.*;
import javax.swing.*;

class TimerThread extends Thread {
	private JLabel timerLabel;
	public TimerThread(JLabel timerLabel) {
		this.timerLabel = timerLabel;
	}
	public void run() {
		int n=0, min=0;
		while(true) {
			//timerLabel.setText(Integer.toString(n));
			String str = String.format("%02d:%02d",n, min);
			timerLabel.setText(str);
			 
			min++;
			if(min == 60) {
				min=0;
				n++;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				return;
			}
		}
	}
}
public class TimerThreadEx  extends JFrame {
	public TimerThreadEx() {
		setTitle("Thread를 상속받은 타이머 스레드 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		
		JLabel timerLabel = new JLabel();
		timerLabel.setFont(new Font("Gothic", Font.ITALIC, 80));
		c.add(timerLabel);
		
		TimerThread th = new TimerThread(timerLabel);
		setSize(250,150);
		setVisible(true);
		th.start();
		
	}
	public static void main(String[] args) {
		new TimerThreadEx();
	}
}

package hello;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class TimerRunnable implements Runnable {
	private JLabel timerLabel;
	
	public TimerRunnable(JLabel timerJLabel) {
		this.timerLabel = timerJLabel;
	}

	@Override
	public void run() {
		int n=0;
		while(true) {
			timerLabel.setText(Integer.toString(n));
			n++;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				return;
			}
		}
	}
}
public class ThreadInterruptEx extends JFrame{
	private Thread th;
	public ThreadInterruptEx() {
		setTitle("threadInterruptEx에제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		
		JLabel timerLabel = new JLabel();
		timerLabel.setFont(new Font("Gothic", Font.ITALIC, 80));
		
		TimerRunnable runnable =  new TimerRunnable(timerLabel);
		th = new Thread(runnable);
		c.add(timerLabel);
		
		JButton btn = new JButton("kill timer");
		btn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				th.interrupt();
				JButton btn = (JButton)e.getSource();
				btn.setEnabled(false);
			}
		});
		c.add(btn);
		setSize(300,170);
		setVisible(true);
		
		th.start();
	}
	public static void main(String[] args) {
		new ThreadInterruptEx();
	}
	
}

 

반응형

'JAVA' 카테고리의 다른 글

[자바] 입출력, 자바의 IO패키지  (0) 2020.01.19
[자바]이벤트와 메뉴  (0) 2020.01.18
[자바] Gui 프로그래밍  (0) 2020.01.18
반응형

1.

package hello;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.security.KeyStore;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public class MenuDemo extends JFrame implements ActionListener {
	MenuDemo() {
		setTitle("메뉴 구성하기");
		makeMenu();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 170);
		setVisible(true);
	}

	void makeMenu() {
		JMenuItem item;
		KeyStroke key;
		JMenuBar mb = new JMenuBar();
		JMenu m1 = new JMenu("파일");
		m1.setMnemonic(KeyEvent.VK_F);
		JMenu m2 = new JMenu("색상");
		m2.setMnemonic(KeyEvent.VK_C);
		item = new JMenuItem("새 파일", KeyEvent.VK_N);
		item.addActionListener(this);
		m1.add(item);
		item = new JMenuItem("파일열기", KeyEvent.VK_O);
		item.addActionListener(this);
		m1.add(item);
		m1.add(new JMenuItem("파일 저장"));
		m1.addSeparator();
		m1.add(new JMenuItem("종료"));
		
		item = new JMenuItem("파란색");
		key = KeyStroke.getKeyStroke(KeyEvent.VK_B, ActionEvent.CTRL_MASK);
		item.setAccelerator(key);
		item.addActionListener(this);
		m2.add(item);
		
		item = new JMenuItem("빨간색");
		key = KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK);
		item.setAccelerator(key);
		item.addActionListener(this);
		m2.add(item);
		
		item = new JMenuItem("노란색");
		key = KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK);
		item.setAccelerator(key);
		item.addActionListener(this);
		m2.add(item);
		mb.add(m1);
		mb.add(m2);
		setJMenuBar(mb);
	}

	public void actionPerformed(ActionEvent e) {
		JMenuItem mi = (JMenuItem) (e.getSource());
		switch (mi.getText()) {
		case "새 파일":
			System.out.println("새 파일");
			break;
		case "파일열기":
			System.out.println("파일열기");
			break;
		case "파란색":
			this.getContentPane().setBackground(Color.BLUE);
			break;
		case "빨간색":
			this.getContentPane().setBackground(Color.RED);
			break;
		case "노란색":
			this.getContentPane().setBackground(Color.YELLOW);
			break;
		}
	}

	public static void main(String[] args) {
		new MenuDemo();
	}
}

2.drawString() 메소드를 이용하여 문자열 출력하기

package hello;

import javax.swing.*;
import java.awt.*;

public class GraphicsDrawStringEx extends JFrame{
	private MyPanel panel = new MyPanel();
	
	public GraphicsDrawStringEx() { 
		setTitle(" drawString  사용 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setContentPane(panel);
		setSize(250, 200);
		setVisible(true);
	}
	class MyPanel extends JPanel {
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.drawString("자바는 재밌다,~~", 30,30);
			g.drawString("얼마나 하늘만큼 땅만큼!!!", 60,60);
		}
	}
	public static void main(String [] args) {
		new GraphicsDrawStringEx();
	}
}

반응형

'JAVA' 카테고리의 다른 글

[자바] 입출력, 자바의 IO패키지  (0) 2020.01.19
[자바] Thread  (0) 2020.01.19
[자바] Gui 프로그래밍  (0) 2020.01.18
반응형

1. 마우스로 텍스트 움직이기 

package hello;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MouseListenerEx extends JFrame{
	private JLabel la = new JLabel("hello");
	
	public MouseListenerEx() {
		setTitle("Mouse 이벤트 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
		Container c = getContentPane();
		c.addMouseListener(new MyMouseListener());
		
		c.setLayout(null);
		la.setSize(50,20);
		la.setLocation(30, 30);
		c.add(la);
		
		setSize(250, 250);
		setVisible(true);
	}
	class MyMouseListener implements MouseListener {
		public void mousePressed(MouseEvent e) {
			int x = e.getX();
			int y = e.getY();
			la.setLocation(x, y);
		}
		public void mouseReleased(MouseEvent e) {}
		public void mouseClicked(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
	}
	public static void main(String[] args) {
		new MouseListenerEx();
	}
}

class MyMouseListener implements MouseListener {
		public void mousePressed(MouseEvent e) {
			int x = e.getX();
			int y = e.getY();
			la.setLocation(x, y);
		}
		public void mouseReleased(MouseEvent e) {}
		public void mouseClicked(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
	}

를 Adapter를 이용하여 간추릴 수 있다.

class MyMouseAdapter extends MouseAdapter {
		public void mousePressed(MouseEvent e) {
			int x = e.getX();
			int y = e.getY();
			la.setLocation(x, y);
		}
	}

완성된 코드 

package hello;

import javax.swing.*; // 스윙 컴포넌트 api
import java.awt.*; // 그래픽을 처리하는 api
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MouseListenerEx extends JFrame /*컨테이너 */{
	private JLabel la = new JLabel("hello");
	
	public MouseListenerEx() {
		setTitle("Mouse 이벤트 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// EXIT_ON_CLOSE : 종료할때 에플리케이션도 함께 종료 
		Container c = getContentPane();
		c.addMouseListener(new MyMouseAdapter());
		
		c.setLayout(null);
		la.setSize(50,20);
		la.setLocation(30, 30);
		c.add(la);
		
		setSize(250, 250);
		setVisible(true); // 스윙 프레임 출력
	}
	class MyMouseAdapter extends MouseAdapter {
		public void mousePressed(MouseEvent e) {
			int x = e.getX();
			int y = e.getY();
			la.setLocation(x, y);
		}
	}
	public static void main(String[] args) {
		new MouseListenerEx();
	}
}

결과는 첫번째 코드와 같지만 코드의 길이가 짧아진 것을 알 수 있다.

 

2. 상하좌우키로 텍스트 움직이기 

package hello;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FlyingTextEx extends JFrame{
	private final int FLYING_UNIT = 10;
	private JLabel la = new JLabel("HELLO");
	public FlyingTextEx() {
		setTitle("상,하,좌,우 키를 이용하여 텍스트 움직이기");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(null);
		c.addKeyListener(new  MyKeyListener());
		la.setLocation(50,50);
		la.setSize(100, 20);
		c.add(la);
		setSize(300,300);
		setVisible(true);
		c.setFocusable(true);
		c.requestFocus();
		
		c.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				Component com = (Component)e.getSource();
				com.setFocusable(true);
				com.requestFocus();
			}
		});
		}
	class MyKeyListener extends KeyAdapter {
		public void keyPressed(KeyEvent e) {
			int KeyCode = e.getKeyCode();
			
			switch (KeyCode) {
			case KeyEvent.VK_UP:
				la.setLocation(la.getX(), la.getY()-FLYING_UNIT);
				break;
			case KeyEvent.VK_DOWN:
				la.setLocation(la.getX(), la.getY()+FLYING_UNIT);
				break;
			case KeyEvent.VK_LEFT:
				la.setLocation(la.getX()-FLYING_UNIT, la.getY());
				break;
			case KeyEvent.VK_RIGHT:
				la.setLocation(la.getX()+FLYING_UNIT, la.getY());
			default:
				break;
			}
		}
	}
	public static void main(String[] args) {
		new FlyingTextEx();
	}
}

3.마우스와 마우스 모션 이벤트 활용

package hello;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseListenerAllEx extends JFrame{
	private JLabel la = new JLabel("No Mouse Event");
	
	public MouseListenerAllEx() {
		setTitle("MouseListener와 MouseMotionListener 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		
		MyMouseListener listener = new MyMouseListener();
		c.addMouseListener(listener);
		c.addMouseMotionListener(listener);
		
		c.add(la);
		
		setSize(300, 200);
		setVisible(true);
	}
	class MyMouseListener implements MouseListener, MouseMotionListener{
		public void mousePressed(MouseEvent e) {
			la.setText("mousePressed("+ e.getX()+", "+e.getY()+")");
		}
		public void mouseReleased(MouseEvent e) {
			la.setText("mouseReleased("+ e.getX()+", "+e.getY()+")");
		}

		@Override
		public void mouseDragged(MouseEvent e) {
			la.setText("mouseDragged("+ e.getX()+", "+e.getY()+")");
		}
		@Override
		public void mouseMoved(MouseEvent e) {
			la.setText("mouseMoved("+ e.getX()+", "+e.getY()+")");
			
		}

		@Override
		public void mouseClicked(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {
			Component c = (Component)e.getSource();
			c.setBackground(Color.CYAN);
		}

		public void mouseExited(MouseEvent e) {
			Component c = (Component)e.getSource();
			c.setBackground(Color.YELLOW);
		}
	}
	public static void main(String[] args) {
		new MouseListenerAllEx();
	}
}

4. 키를 입력받으면 컨텐트팬의 배경을 초록색으로, % 키를 입력받으면 노란색으로 변경

package hello;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class KeyCodeEx extends JFrame{
	private JLabel la = new JLabel();
	
	public KeyCodeEx() {
		setTitle("key Code 예제 : f1 키 - 초록색, %키 - 노란색");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		
		c.addKeyListener(new MyKeyListener());
		c.add(la);
		
		setSize(300, 150);
		setVisible(true);
		
		c.setFocusable(true);
		c.requestFocus();
	}
	class MyKeyListener extends KeyAdapter {
		public void keyPressed(KeyEvent e) {
			Container contentPane = (Container)e.getSource();
			la.setText(e.getKeyText(e.getKeyCode()));
		
			if(e.getKeyChar() == '%') {
				contentPane.setBackground(Color.YELLOW);
			}
			else if(e.getKeyCode() == KeyEvent.VK_F1) {
				contentPane.setBackground(Color.GREEN);
			}
		}
	}
	public static void main(String[] args) {
		new KeyCodeEx();
	}
}


(원래는 화면에 f1과 %가 나오는데 캡쳐를 했더니... alt가 나왔다...)

 

5. 더블클릭 시 컨텐트팬의 배경색 변경

package hello;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClickAndDoubleClickEx extends JFrame{
	public ClickAndDoubleClickEx() {
		setTitle("Click and DoubleClick 예제");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.addMouseListener(new MyMouseListener());
		setSize(300,200);
		setVisible(true);
	}
	class MyMouseListener extends MouseAdapter {
		public void mouseClicked(MouseEvent e) {
			if(e.getClickCount() == 2) {
				int r = (int )(Math.random()* 256);
				int g = (int )(Math.random()* 256);
				int b = (int )(Math.random()* 256);
				Component c = (Component)e.getSource();
				c.setBackground(new Color(r,g,b));
			}
		}
	}
	public static void main(String[] args) {
		new ClickAndDoubleClickEx();
	}
}

 

반응형

'JAVA' 카테고리의 다른 글

[자바] 입출력, 자바의 IO패키지  (0) 2020.01.19
[자바] Thread  (0) 2020.01.19
[자바]이벤트와 메뉴  (0) 2020.01.18
반응형
package gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ComponentDemo1 extends JFrame{
	ComponentDemo1() {
		setTitle("원 넓이 구하기");
		
		setLayout(new BorderLayout(10, 10));
		showNorth();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300,200);
		setVisible(true);
	}
	void showNorth() {
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel panel = new JPanel(new GridLayout(2,0));
		
		JLabel l1 = new JLabel("원의 반지름");
		JLabel l2 = new JLabel("원의 넓이");
		
		JTextField t1 = new JTextField(10);
		JTextField t2 = new JTextField(10);
		t2.setEnabled(false);
		
		p1.add(l1);
		p1.add(t1);
		p2.add(l2);
		p2.add(t2);
		panel.add(p1);
		panel.add(p2);
		
		add(panel, BorderLayout.NORTH);
	}
	public static void main(String[] args) {
		new ComponentDemo1();
	}
}

package gui;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class ComponentDemo2 extends JFrame{
	public ComponentDemo2() {
		setTitle("원 넓이 구하기");
		
		setLayout(new BorderLayout(10, 10));
		showCenter();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 220);
		setVisible(true);
	}
	void showCenter() {
		JPanel panel = new JPanel();
		
		JTextArea area= new JTextArea(30, 20);
		area.setText("이 영역에 원의 넓이를 \n 계산하는 과정이 나타납니다.");
		area.setEditable(false);
		area.setForeground(Color.RED);
		
		panel.add(area);
		
		add(panel, BorderLayout.CENTER);
		
	}
	public static void main(String[] args) {
		new ComponentDemo2();
	}
}

package gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ComponentDemo3 extends JFrame{
	 ComponentDemo3() {
		setTitle("원 넓이 구하기");
		
		setLayout(new BorderLayout(10, 10));
		
		showSouth();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 220);
		setVisible(true);
	}
	 void showSouth() {
		 String[] color = {"red", "blue", };
		 JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10,10));
		 
		 JButton cal = new JButton("계산");
		 JComboBox<String> cb = new JComboBox<>(color);
		 JButton reset = new JButton("리셋");
		 
		 panel.add(cal);
		 panel.add(cb);
		 panel.add(reset);
		 
		 add(panel, BorderLayout.SOUTH);
	 }
	 public static void main(String[] args) {
		new ComponentDemo3();
	}
}

통합↓

package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ComponentDemo4 extends JFrame{
	ComponentDemo4() {
		setTitle("원 넓이 구하기");
		
		setLayout(new BorderLayout(10, 10));
		showNorth();
		showCenter();
		showSouth();
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 200);
		setVisible(true);
	}
	void showNorth() {
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel panel = new JPanel(new GridLayout(2,0));
		
		JLabel l1 = new JLabel("원의 반지름");
		JLabel l2 = new JLabel("원의 넓이");
		
		JTextField t1 = new JTextField(10);
		JTextField t2 = new JTextField(10);
		t2.setEnabled(false);
		
		p1.add(l1);
		p1.add(t1);
		p2.add(l2);
		p2.add(t2);
		panel.add(p1);
		panel.add(p2);
		
		add(panel, BorderLayout.NORTH);
	}
	void showCenter() {
		JPanel panel = new JPanel();
		
		JTextArea area= new JTextArea(30, 20);
		area.setText("이 영역에 원의 넓이를 \n 계산하는 과정이 나타납니다.");
		area.setEditable(false);
		area.setForeground(Color.RED);
		
		panel.add(area);
		
		add(panel, BorderLayout.CENTER);
	}
	void showSouth() {
		String[] color = {"red", "blue", };
		 JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10,10));
		 
		 JButton cal = new JButton("계산");
		 JComboBox<String> cb = new JComboBox<>(color);
		 JButton reset = new JButton("리셋");
		 
		 panel.add(cal);
		 panel.add(cb);
		 panel.add(reset);
		 
		 add(panel, BorderLayout.SOUTH);
	}
	public static void main(String[] args) {
		new ComponentDemo4();
	}
}

package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class EventExams extends JFrame implements ActionListener {
	int index = 0;
	String[] msgs = {"First", "Second", "Third"};
	JButton button1 = new JButton("<<");
	JButton button2 = new JButton(">>");
	JButton button3 = new JButton("msg[0]");
	
	public EventExams() {
		BorderLayout layout = new BorderLayout();
		setLayout(layout);
		button1.addActionListener(this);
		button2.addActionListener(this);
		button3.setEnabled(false);
		add(button1, BorderLayout.WEST);
		add(button2, BorderLayout.EAST);
		add(button3, BorderLayout.CENTER);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setSize(300, 100);
		setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		if(obj == button1) {
			index --;			
		}
		else if (obj == button2) {
			index ++;
		}
		if(index > 2) {
			index = 0;
		}
		else if(index < 0) {
			index = 2;
		}
		
		button3.setText(msgs[index]);
	}
	public static void main(String[] args) {
		EventExams app = new EventExams();
	}
	
}

package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class IndepClassListener extends JFrame {
	JTextField t1, t2;
	JTextArea area;
	JButton cal,reset;
	JComboBox<String> cb;
	
	public IndepClassListener() {
		 setTitle("원 넓이 구하기");
		 setLayout(new BorderLayout(10, 10));
		 showNorth();
		 showCenter();
		 showSouth();
		 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		 setSize(300, 220);
		 setVisible(true);
	
	}
	void showNorth() {
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel panel = new JPanel(new GridLayout(2,0));
		
		JLabel l1 = new JLabel("원의 반지름");
		JLabel l2 = new JLabel("원의 넓이");
		
		t1 = new JTextField(10);
		t2 = new JTextField(10);
		t2.setEnabled(false);
		
		p1.add(l1);
		p1.add(t1);
		p2.add(l2);
		p2.add(t2);
		panel.add(p1);
		panel.add(p2);
		
		add(panel, BorderLayout.NORTH);
	}
	void showCenter() {
		JPanel panel = new JPanel();
		
		area= new JTextArea(30, 20);
		area.setText("이 영역에 원의 넓이를 \n 계산하는 과정이 나타납니다.");
		area.setEditable(false);
		area.setForeground(Color.RED);
		
		panel.add(area);
		
		add(panel, BorderLayout.CENTER);
	}
	void showSouth() {
		String[] color = {"red", "blue", };
		 JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10,10));
		 
		 cal = new JButton("계산");
		 cal.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if(t1.getText().isEmpty() == true) {
					 System.out.println("반지름을 입력하세요");
				}
				else {
					String s = t1.getText();
					double radius = Double.parseDouble(s);
					double result = radius * radius * 3.14;
					t2.setText("" + result);
					area.setText(radius + " * " + radius + " * 3.14 = " + result);
			}}
		});
		 
		 cb = new JComboBox<>(color);
		 reset = new JButton("리셋");
		 reset.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				t1.setText("");
				t2.setText("");
				area.setText("");
				
			}
		});
		 
		 panel.add(cal);
		 panel.add(cb);
		 panel.add(reset);
		 
		 add(panel, BorderLayout.SOUTH);
	}
	public static void main(String[] args) {
		new IndepClassListener();
	}
}

반응형
반응형

1. 범위를 벗어난 배열의 접근 

오류 메세지 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

 

코드 

public class DEMO {
	public static void main(String[] args) {
		int [] array = { 0, 1, 2, };
		
		System.out.println(array[3]);
	}
}

 배열의 크기가 3이고 배열이 0부터 시작하기 때문에 배열 3칸은 없음.

 

2. 0으로 나눌때 발생하는 ArithmeticException 예외

public class Demo2 {
	public static void main(String[] args) {
		int [] aa = new int[3];
		try {
			aa[2] = 100/0;
			aa[3] = 100;
		}catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열 첨자가 배열 크기보다 커요 ~~");
		} catch (ArithmeticException e) {
			System.out.println("0으로 나누는 등의 오류에요~~");
		} finally {
			System.out.println("이 부분은 무조건 나와요 ~~");
		}
	}
	
}
public class Demo3 {
	public static void main(String[] args) {
		int a = 100, b = 0;
		int result;
		try {
			result = a / b;
		} catch (ArithmeticException e) {
			System.out.print("발생 오류 ==>");
			System.out.println(e.getMessage());
		}
	}
}

 결과

발생 오류 ==>/ by zero

3. 예외발생으로 프로그램이 강제 종료되는 경우 

오류 메세지 : Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type InterruptedException

package test01;

public class Demo3 {
	public static void main(String[] args) {
		Thread.sleep(100);
	}
}

4. 예외 잡아 처리하기 (범위를 벗어난 배열의 접근 )

try {
	예외가 발생할 수 있는 실행문;
} catch (예외클래스 1 | 예외 클래스 2 변수) {
	핸들러;
}
public class Demo3 {
	public static void main(String[] args) {
		int [] array = { 0 , 1, 2, };
		try { 
			System.out.println("마지막 원소 => " + array[3]);
			System.out.println("첫 번째 원소 => " + array[0]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("원소가 존재하지 않습니다. ");
		} 
		System.out.println("어이쿠!!");
	}
}

ArrayIndexOutOfBoundsException : 배열, 벡터 등에서 범위를 벗어난 인덱스를 사용할 때 발생한다.

 

결과

원소가 존재하지 않습니다. 
어이쿠!!

 

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 인터페이스 구현  (0) 2020.01.04
[JAVA] 추상클래스  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
반응형

로또 추출 번호 게임 

// 로또 추출 번호 게임
package test01;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test {
	public static void main(String[] args) {
		System.out.println("로또 번호를 추출할 횟수를 입력해주세요 :");
		 Scanner sc = new Scanner(System.in);
		 int play_count = sc.nextInt();
		 
		 for(int i = 1; i <= play_count; i++) {
			 System.out.println(i + "번째: " + making_lottonumber());
		 }
		 sc.close();
	}
	static String making_lottonumber() {
		int [] arr = new int[6];
		Random random = new Random();
		while(true) {
			for(int a = 0; a<6; a++ ) {
				arr[a] = random.nextInt(45) + 1;
			}
			Arrays.sort(arr);
			if(checking_overlap(arr) == true) {
				break;
			}
		}
		return Arrays.toString(arr);
	}
	static boolean checking_overlap (int[] arr) {
		int[] check_arr = new int[46];
		for(int i =0 ;  i<6; i++) {
			check_arr[arr[i]] += 1;
			if(check_arr[arr[i]] == 2) {
				return false;
			}
		}
		return true;
	}
}

 

반응형

'JAVA > 2020 프로그램' 카테고리의 다른 글

[JAVA] 파일 입출력  (0) 2020.01.19
[JAVA] GUI 프로그래밍  (0) 2020.01.12
[JAVA] 랜덤함수를 이용하여 숫자배열 만들기  (0) 2019.12.15
[JAVA] 숫자 출현횟수  (0) 2019.12.15
[JAVA] 가위바위보 게임  (0) 2019.12.08
반응형
package hello;
class Pencil{
	public void write() {
		System.out.println("연필로 쓴다");
	}
}

class Ballpoint{
	public void writing() {
		System.out.println("볼펜으로 쓴다.");
	}
}
public class Mainclass {
	public static void main(String[] args) {
		Pencil pencil = new Pencil();
		Ballpoint ballpoint = new Ballpoint();
		pencil.write();
		ballpoint.writing();
	}
}
package hello;
interface Frindle {
	public void write();
}

class Pencil implements Frindle {
	public void write() {
		System.out.println("연필로 쓴다.");
	}
}

class Ballpoint implements Frindle {
	public void write() {
		System.out.println("볼펜으로 쓴다.");
	}
}

public class Mainclass{
	public static void main(String[] args) {
		Frindle frindle = new Pencil();
		frindle.write();
		Frindle frindle1 = new Ballpoint();
		frindle1.write();
	}
}
package hello;
interface PhoneInterface {
	final int TIMEOUT = 10000;
	void sendCall();
	void receiveCall();
	default void printLogo() {
		System.out.println("** phone **");
	}
}
class SamsungPhone implements PhoneInterface {

	@Override
	public void sendCall() {
		System.out.println("띠리리리링");
		
	}

	@Override
	public void receiveCall() {
		System.out.println("전화가 왔습니다.");
		
	}
	public void flash() {
		 System.out.println("전화기에 불이 켜졌습니다.");
	}
	
}

public class Mainclass {
	public static void main(String[] args) {
		SamsungPhone phone = new SamsungPhone();
		phone.printLogo();
		phone.sendCall();
		phone.receiveCall();
		phone.flash();
	}
}
package hello;
interface Mammal {
	abstract void giveBirth();
}
abstract class Fish {
	void swim() {
		System.out.println("물고기는 헤엄치며 움직입니다.");
	}
}

class Whale extends Fish implements Mammal{
	public void giveBirth() {
		System.out.println("고래는 새끼를 낳습니댜.");
	}
	public void swim() {
		System.out.println("고래는 헤엄치며 움직입니다.");
	}
}
public class Ifpr {
	public static void main(String[] args) {
		Whale w = new Whale();
		w.swim();
		w.giveBirth();
	}
}
package hello;
class OuterClass1 {
	void a() {
		System.out.println("method a");
	}
	void b() {}
}

public class Anonymous {
	public static void main(String[] args) {
		OuterClass1 o = new OuterClass1() {
			void a() {
				System.out.println("새롭게 정의한 익명 클래스의 메서드입니다.");
			}
		};
		o.a();
		OuterClass1 ok = new OuterClass1();
		ok.a();
	}
}
새롭게 정의한 익명 클래스의 메서드입니다.
method a
반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 예외처리  (0) 2020.01.05
[JAVA] 추상클래스  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
반응형

추상클래스 : 몸체가 구성되어 있지 않은 메서드를 가지고 있는 클래스 

즉, 선언되어 있으나 구현 되어 있지 않은 메서드, abstract로 선언함.

 1. 추상클래스는 서브 클래스에서 오버라이딩 하여 구현해야 함.

package hello;

abstract class Car{
	int speed = 0;
	String color;
	void upSpeed(int speed) {
		this.speed += speed;
	}
}
class Sedan extends Car{
}
class Truck extends Car{
}
public class AbstractClassExample{
	public static void main(String[] args) {
		Sedan sedan1 = new Sedan();
		System.out.println("승용차 인스턴스 생성~");
		Truck truck1 = new Truck();
		System.out.println("트럭 인스턴스 생성~");
	}
}
package hello;
abstract class Pokemon{
	
	private String name;
	abstract void attack();
	abstract void sound();
	Pokemon(String name) {
		this.name = name;
	}
	public String getname() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
class Pikachu extends Pokemon{
	public Pikachu() {
		super("피카츄"); 
	}
	void attack() {
		System.out.println("전기 공격");
	}
	void sound() {
		System.out.println("피카피카");
	}
}

class Squirtle extends Pokemon{
	public Squirtle() {
		super("꼬북이"); 
	}
	void attack() {
		System.out.println("물 공격");
	}
	void sound() {
		System.out.println("꼬북꼬북");
	}
}

public class Sample{
	public static void main(String[] args) {
		Pikachu s = new Pikachu();
		System.out.println("이 포켓몬의 이름은 : " + s.getname());
		s.attack();
		s.sound();
		Squirtle a = new Squirtle();
		System.out.println("이 포켓몬의 이름은 : " + a.getname());
		a.attack();
		a.sound();
	}
}
package hello;

abstract class Car{ 
	private int speed = 0;
	private String name;
	public Car(String name){
		this.name = name;
	}
	void upSpeed(int speed) {
		 this.speed += speed;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	abstract void work();
}

class Sedan extends Car{
	public Sedan(String name) {
		super(name);
	}
	void work() {
		System.out.println(super.getName() +"가 사람을 태우고 있습니다.");
	}
}
class Truck extends Car{
	public Truck(String name) {
		super(name);
	}
	
	void work() {
		System.out.println(super.getName() + "이 짐을 싣고 있습니다.");
	}
}

public class AbstractMethodExample{
	public static void main(String[] args) {
		Sedan sd = new Sedan("빨간 승용차");
		sd.work();
		Truck tk = new Truck("노란트럭");
		tk.work();
	}
}
package hello;

abstract class Calculator{
	public abstract int add(int a, int b);
	public abstract int subtract(int a, int b);
	public abstract double average(int[] a);
}
public class GoodCalc {
	public int add(int a, int b) {
		return a + b;
	}
	
	public int subtract(int a, int b) {
		return a - b;
	}
	public double average(int[] a) {
		int sum = 0;
		for(int i=0; i<a.length; i++) {
			sum += a[i];
		}
		return sum/a.length;
	}
	
	public static void main(String[] args) {
		GoodCalc a = new GoodCalc();
		System.out.println("2 + 3 = " + a.add(2,3));
		System.out.println("2 - 3 = " + a.subtract(2, 3));
		System.out.println("(2 + 3 + 4)/3 = " + a.average(new int [] {2,3,4}) );
	}
}
반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 예외처리  (0) 2020.01.05
[JAVA] 인터페이스 구현  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15

+ Recent posts