본문 바로가기
1.A. High Level Computing/SW Language Specifics

[토막글] Java UI띄우기 (Swing)

by Never Settle Down 2023. 2. 22.
반응형

 

Can't be a Rolling Stone if you live in a glass house
You keep on talking that talk, one day you're gonna blast out
You can't be bitter if I'm out here showing my face
You want what now looks like, let me give you a taste

유 킵 온 톡킹 댁 톡. (브리티시 억양을 맛깔나게 살려야된다)

렛미 기뷰 어 테이스트~

 

 

 

예전에 했던 프로젝트 소스들이

대거 유실되었기 때문에

(아마 구글 + icloud 파일 corruption을 당했을 때 잃은 것 같다. 한데 몰아놓고 압축해버렸거덩 ㅜㅜ)

새로 배우는 김에 글을 남기고 있다.

 

돌아가는 포트키:

2023.02.02 - [Engineering Log/On Premise Computing] - 파일 관리 프로그램 작성기 (feat. 가내 서버)

 

파일 관리 프로그램 작성기 (feat. 가내 서버)

장을 비워내려고 합ㄴ...후드득 macOS + Windows + Linux 형태로 컴퓨팅을 하는 나에게 파일 관리 시스템의 필요성이 생겨 만들어보게될(또는 된) 파일 관리 프로그램의 이야기 프로그램과 글을 같이

thewanderer.tistory.com

Window 용 클래스를 별도로 만들어주었다.

나중에 다른 코드에서도 불러다 쓸 수 있게끔.

 

일단은 테스트니까

생성자 메서드를 창 띄우는 것으로 만들었다.

 

 

 

 

아래 참조 블로그 코드를 그대로 복붙했다.

 

잘되넴.

쏘오스코드:

더보기
package javaPlaegraund;
import javax.swing.JFrame;

public class WindowModule extends JFrame
{
	public WindowModule()
	{
		super("Whatsup world");
		this.setSize(500, 500);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}
}

쬐끔 수정했다

생성자를 스트링 아규먼트 받냐 안 받냐로 나눠서 맹글고

테스트.

굿.

 

 

텍스트박스랑 버튼 만들어보자

엠... 왓더??

 

버튼이 새 창에 뜬다.

this를 static으로 가지고 있어야되는거여?

아니지, 노 스태틱으로 만들어야되나?

 

thisFrame은 널을 참조한다며 익셉션을 꿿하고 뿜었다.

Static...?

근데 스태틱 해버리면

윈도 여러개 띄웠을 때 여러 윈도우에 똑같은 버튼 생기지 아니하니?

왓 더 f...????

 

스태틱으로 하니깤ㅋㅋ

순서가 꼬인다??

 

스태틱 풀고 그냥 super로 다시 ㄱ

창이 3개가 뜬다.

Defualt Title에서 꼬였나보다.

String 입력인자 없는 메서드에서 인자 있는 메서드 new로 하는게 문제인듯.

 

역시 C랑 다르네 ㅜㅜ

생성메서드 겹치는 코드를 private 메서드로 다시 만들어 호출하자.

 

소스코드보기:

더보기
package javaPlaegraund;
import javax.swing.*;


public class WindowModule extends JFrame
{
	//private JFrame thisFrame;
	
	public WindowModule()
	{
		super("Default Title");
		createNewWindow(200, 100);
	}
	public WindowModule(String arg1)
	{
		super(arg1);
		createNewWindow(200, 100);
	}
	private void createNewWindow(int width, int height)
	{
		this.setSize(width, height);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setVisible(true);
	}
	
	
	public void addButton() {addButton("default button");}
	public void addButton(String btnStr) 
	{
		JButton button = new JButton(btnStr);
		this.getContentPane().add(button);
		this.setVisible(true);
	}
}

height랑 width 위치 찍었는데

맞았다 ㅋㅋㅋㅋ 개이득.

 

아 저 super()랑 create...(...) 코드 겹치는거

진짜 보기 싫다.

 

일단은 잘 뜬다.

메서드는 같은이름 다른인자 메서드를 호출해도 상관없는데

생성자메서드는 그렇게 하면 안되나보다.

 

오키도키.

 

버튼 생성메서드에 사이즈 인자도 넣어야되는데... 일단은.

 

 

 

텍스트박스 만들어볼까나.

 

...

열심히 하고 있다.

하기가 싫어서 그렇짘ㅋㅋㅋ

로깅을 남길만한 시점이 오면 더 이어가는 것으로.

 

여기까지 소오스코드:

더보기
package javaPlaegraund;
import java.awt.FlowLayout;

import javax.swing.*;


public class WindowModule extends JFrame
{
	public static enum layoutTypes{
		Flow, 		// Default, Left to Right, 
		Border, 	// 5 Sectors, Top - MidLeft-MidCentre-MidRight - Bottom
		Grid, 		// n by m grid
		GridBag, 	// grid + customisable location & size
		Card, 		// tabbed, multiple layouts
		Manual		// null, manual setup for size & locations
	}
	
	public WindowModule()
	{
		super("Default Title");
		createNewWindow(200, 100);
	}
	public WindowModule(String title)
	{
		super(title);
		createNewWindow(200, 100);
	}
	public WindowModule(int width, int height, String title)
	{
		super(title);
		createNewWindow(width, height);
	}
	private boolean createNewWindow(int width, int height)
	{
		try {
			this.setSize(width, height);
			this.setLocationRelativeTo(null);
			this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
			this.setVisible(true);
			return true;
		}catch (Exception e){
			return false;
		}finally {;}
	}
	
	public void setRootProcess(boolean gonnabeRoot)
	{
		this.setDefaultCloseOperation(
			gonnabeRoot ? EXIT_ON_CLOSE : DISPOSE_ON_CLOSE
		);
	}
	public void addButton() {addButton("default button");}
	public void addButton(String btnStr) 
	{
		JButton button = new JButton(btnStr);
		this.getContentPane().add(button);
		this.setVisible(true);
	}

	public void setLayoutAs(layoutTypes type) 
	{
		switch(type) 
		{
		case Flow:
			this.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 50));
			break;
		case Border:
			//this.setLayout(new BorderLayout());
			break;
		case Grid:
			break;
		case GridBag:
			break;
		case Card:
			break;
		case Manual:
			
		}
		return;
	}
	
	public void setMenuBar()
	{
		String swName = "PlaeGraundStret";
		JMenuBar menuBar = new JMenuBar();
		JMenu menu[] = {new JMenu(swName), 
						new JMenu("File"),
						new JMenu("Edit"),
						new JMenu("Window"),
						new JMenu("Help")};

		menu[0].add(new JMenuItem("About " + swName));
		menu[0].add(new JMenuItem("Preferences"));
		menu[0].add(new JMenuItem("Services"));
		menu[0].add(new JMenuItem("Quit " + swName));
		menu[1].add(new JMenuItem("aaa"));
		menu[1].add(new JMenuItem("bbbb"));
		menu[1].add(new JMenuItem("Open Directory"));
		menu[1].add(new JMenuItem("Save As..."));
		menu[2].add(new JMenuItem("a"));
		menu[2].addSeparator();
		menu[2].add(new JMenuItem("a"));
		menu[2].add(new JMenuItem("w"));
		menu[3].add(new JMenuItem("4"));
		menu[3].add(new JMenuItem("1"));
		menu[3].add(new JMenuItem("5"));
		menu[3].add(new JMenuItem("6"));
		menu[4].add(new JMenuItem("s"));
		menu[4].add(new JMenuItem("a"));
		menu[4].add(new JMenuItem("w"));
		
		for(JMenu each:menu)
		{
			menuBar.add(each);
		}
		
		this.setJMenuBar(menuBar);
		setVisible(true);
	}
}

 

 

JFrame (윈도) 안에 JPanel을 넣고

그 안에 컴포넌트를 넣고 있다.

 

 

이제 액숀리스너를 엮을 차례.

 

자바 컴포넌트는 좋은게

별도로 백그라운드에서 돌고 있는 (JVM이 거버먼트 하고 있겠지) 리스너 매니저가

액션 발생시 리스너를 호출해주며 (소프트웨어 인터럽트 아니면 별도 쓰레드 생성이지 않을까)

리스너 코드를 실행하고, 해당 코드에 인자로 포인터를 (객체를) 던져준다.

 

객체를 생성하고나서 (new) 포인터를 따로 기억해 뒀다가 연결할 필요가 없다.

그냥 받아서 이름만 보고 처리해도 되는것.

 

물론 같은 JPanel 위에 같은 이름을 가진 같은 컴포넌트가 있다면

손을 좀 봐야것지

 

 

 

 

 

 

참조 블로그:

(역시 한국 블로그는 Instruction 타입 포스팅이 널려있다. 깔끔한게 보기 참 좋구만.)

https://studydeveloper.tistory.com/5

 

[자바 Swing 기초] 1. 창 띄우기

오늘의 결과물 자바에서 GUI를 개발하기 위해서는 JFrame 클래스를 상속받아야 한다. 그러면 JFrame에 있는 메소드들을 사용할 수 있다. import javax.swing.JFrame; class 클래스명 extends JFrame 창을 띄우기 위

studydeveloper.tistory.com

https://www.guru99.com/java-swing-gui.html

 

Java Swing Tutorial: How to Create a GUI Application in Java

Java Swing package lets you make GUI components for your java applications. This tutorial gives programs and examples to create Swing GUI.

www.guru99.com

https://ming9mon.tistory.com/47

 

자바 Swing으로 GUI 만들기

자바의 GUI를 만드는데에는 AWT와 Swing이 있다. Swing은 AWT보다 컴포넌트가 많고, AWT보다 가볍기 때문에 보통 Swing을 사용한다. AWT 자바가 처음 나왔을 때 함께 배포된 패키지로 많은 GUI 컴포넌트를

ming9mon.tistory.com

 

 

끝. End of Document

반응형

댓글