반응형

어쩌다보니 Maven에 익숙해졌고, 이번 프로젝트는 Mybatis, JavaFX가 함께 들어가는 프로젝트가 되었다. 이걸 만드는데까지는 괜찮았는데, 배포하려니 또 어렵다. 중요한건 jre와 javafx-sdk가 jar파일 또는 exe파일과 함께 있어야 한다는 것이다.

 

1. jre

각종 버전 문제를 피하기 위해 배포할때엔 런타임환경을 함께 구성해서 배포하는게 낫겠다고 판단했다. 

jre는 새로 다운받는게 아니라, jdk폴더의 bin, lib, conf폴더만 복사해서 가져오면 된다.

   /jre
     ㄴ/bin
     ㄴ/lib
     ㄴ/conf

 

2. javafx-sdk

인텔리제이에서 pom.xml 설정으로 라이브러리가 받아졌겠지만, 다시한번 적당한 버전을 받는다. 

- 공식사이트: https://gluonhq.com/products/javafx

 

JavaFX - Gluon

Roadmap Release GA Date Latest version Minimum JDK Long Term Support Extended or custom support Details 25 September 2025 early access 22 no 24 March 2025 24.0.1 (April 2025) 22 no upon request details 23 September 2024 23.0.2 (January 2025) 21 no upon req

gluonhq.com

- 직접다운로드: https://download2.gluonhq.com/openjfx/17.0.15/openjfx-17.0.15_windows-x64_bin-sdk.zip

 

3. 폴더 구성

javaFX maven 프로젝트를 빌드하면 Target 폴더에 jar파일이 생성되게 된다. 동일한 폴더에 jre와 javafx-sdk를 복사해 넣으면 작동 환경은 구성된 것이다.

 

4. pom.xml

우선 jar파일이 정상적으로 실행이 되어야한다. 그런데 실행하다보면 MainClass가 빠졌다는 등의 오류가 발생하는 경우가 있다. 이런경우 maven-shade-plugin을 사용해 Fat JAR을 생성한다. 아래 플러그인 부분에서 Fat JAR만들기 부분 참조

<plugins>
          <!-- 컴파일러 -->
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.11.0</version>
              <configuration>
                  <source>17</source>
                  <target>17</target>
              </configuration>
          </plugin>

          <!-- ✅ Fat JAR (실행 가능한 JAR) 만들기 -->
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-shade-plugin</artifactId>
              <version>3.5.0</version>
              <executions>
                  <execution>
                      <phase>package</phase>
                      <goals>
                          <goal>shade</goal>
                      </goals>
                      <configuration>
                          <transformers>
                              <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                  <mainClass>com.example.javafx05.HelloApplication</mainClass>
                              </transformer>
                          </transformers>
                      </configuration>
                  </execution>
              </executions>
          </plugin>
      </plugins>

 

 

실행은 우측의 Maven아이콘 클릭 후, 수명주기 -> package를 더블 클릭하면 패키징이 되면서 jar파일이 생성된다.

 

java --module-path "C:\javafx-sdk-17.0.15\lib" 
     --add-modules javafx.controls,javafx.fxml 
     -jar target/javafx05-1.0-SNAPSHOT-shaded.jar

jar 파일 생성 후에는 해당 폴더에서 위의 형식으로 명령어를 주면 실행되는 모습을 볼 수 있다.

 

5. Launch4j로 exe파일 만들기

launch4j는 지금 실행한 환경을 하나의 파일로 packaging하는 것 뿐이다.

 

우선, 아웃풋 파일명과 Jar파일의 위치를 인식시키고..

 

 

그 다음으로는 미리 준비해둔 jre의 위치, 최소 jre버전정보, 그리고 JVM option을 넣어준 뒤 빌드하면 된다. 마지막 배포시에도 jre와 java-fx폴더는 exe파일과 동일한 폴더에 계속 함께 존재해야 실행된다.

 

 

- 끝 -

반응형
반응형

C# WPF로 작업하던 프로그램이 오류를 뱉는데, 디버깅이 안되어 Java로 전부 바꾸는 실험을 했다. WPF는 Visual Studio Code에서 만든거라, 디버깅이 좀 힘들었다. 반면에 Java는 무료이면서도 강력한 IntelliJ가 있다. 물론 이클립스도 있다. 

이번엔 IntelliJ로 프로젝트를 만들었는데, 사실 그것도 처음이라 좀 많이 힘들었다.

 

이번 프로젝트는 출입 통제하는 프로그램이다. 자료실에 드나드는 사람에게 ID 태그를 읽혀서 들어올땐 "안녕하세요", 나갈땐 "안녕히가세요"를 출력해주고, 다른 탭에서 전체 출입인원 목록을 확인하면 된다.

 

프로젝트 구성은 아래와 같다. 

Spring Boot를 해본 사람이라면 좀 익숙할 수도 있겠다. 그것과 비슷한 구조로 만들려고 신경을 써봤다. 각 파일들의 코드를 기록으로 남기고자 한다. 참고하려는 분들은 아래의 프로젝트 구성도를 계속 확인하면서 보면 좋겠다.

 

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  .
  .
  .
   <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.10</version>
    </dependency>
    
    <!-- OraCLE.. 두가지가 다 필요했다. -->
    <dependency>
      <groupId>com.oracle.database.jdbc</groupId>
      <artifactId>ojdbc11</artifactId>
      <version>23.5.0.24.07</version>
    </dependency>

    <dependency>
      <groupId>com.oracle.ojdbc</groupId>
      <artifactId>orai18n</artifactId>
      <version>19.3.0.0</version>
    </dependency>

    <!-- Serial 통신 라이브러리 -->
    <dependency>
      <groupId>com.fazecast</groupId>
      <artifactId>jSerialComm</artifactId>
      <version>2.11.0</version>
    </dependency>

  </dependencies>

  ...

 

 

2. 화면구성(hello-view.fxml)

화면은 단순하다. 그렇지만 수많은 시행착오끝에 만든 화면이다. JavaFX로 만들어보는건 처음이라..

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.DatePicker?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<TabPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1400.0" tabClosingPolicy="UNAVAILABLE" xmlns="http://javafx.com/javafx/23.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.javafx05.HelloController">
  <tabs>
    <Tab text="Home">
      <content>
        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
          <children>
            <VBox alignment="TOP_CENTER" prefHeight="571.0" prefWidth="800.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
              <children>
                <Label alignment="CENTER" contentDisplay="CENTER" prefHeight="64.0" prefWidth="1000.0" style="-fx-font-weight: bold; -fx-text-fill: #2c3e50;" text="DATA ROOM SECURITY" textAlignment="CENTER">
                  <font>
                    <Font name="System Bold" size="72.0" />
                  </font>
                           <VBox.margin>
                              <Insets bottom="20.0" top="20.0" />
                           </VBox.margin>
                </Label>
                <Label fx:id="welcomeText" alignment="CENTER" contentDisplay="CENTER" prefHeight="200.0" prefWidth="1200.0" style="-fx-text-fill: #3498db;" text="입/퇴장시 체크해주세요" textAlignment="CENTER">
                  <font>
                    <Font name="System Bold" size="96.0" />
                  </font>
                           <VBox.margin>
                              <Insets bottom="60.0" top="30.0" />
                           </VBox.margin>
                </Label>
                <HBox alignment="CENTER" prefHeight="278.0" prefWidth="1400.0">
                  <children>
                    <VBox alignment="CENTER" prefHeight="334.0" prefWidth="500.0">
                      <children>
                            <GridPane alignment="CENTER" prefHeight="293.0" prefWidth="500.0">
                              <columnConstraints>
                                <ColumnConstraints hgrow="SOMETIMES" maxWidth="194.0" minWidth="10.0" prefWidth="103.0" />
                                <ColumnConstraints hgrow="SOMETIMES" maxWidth="297.0" minWidth="10.0" prefWidth="297.0" />
                              </columnConstraints>
                              <rowConstraints>
                                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                              </rowConstraints>
                               <children>
                                  <Button alignment="CENTER" contentDisplay="RIGHT" mnemonicParsing="false" prefHeight="50.0" prefWidth="200.0" text="Purpose" GridPane.halignment="CENTER">
                                             <font>
                                                <Font size="24.0" />
                                             </font></Button>
                                  <Button alignment="CENTER" mnemonicParsing="false" prefHeight="50.0" prefWidth="200.0" text="Location" textAlignment="CENTER" wrapText="true" GridPane.halignment="CENTER" GridPane.rowIndex="1">
                                             <font>
                                                <Font size="24.0" />
                                             </font></Button>
                                  <Button alignment="CENTER" mnemonicParsing="false" prefWidth="200.0" text="DEPT" GridPane.halignment="CENTER" GridPane.rowIndex="2">
                                             <font>
                                                <Font size="24.0" />
                                             </font></Button>
                                  <Button alignment="CENTER" mnemonicParsing="false" prefWidth="200.0" text="ID" GridPane.halignment="CENTER" GridPane.rowIndex="3">
                                             <font>
                                                <Font size="24.0" />
                                             </font></Button>
                                  <Button alignment="CENTER" mnemonicParsing="false" prefWidth="200.0" text="NAME" GridPane.halignment="CENTER" GridPane.rowIndex="4">
                                             <font>
                                                <Font size="24.0" />
                                             </font></Button>
                                  <ComboBox fx:id="purpose_combo" prefHeight="50.0" prefWidth="300.0" promptText="도서 열람" style="-fx-alignment: CENTER; -fx-font-size: 18px; -fx-font-weight: bold;" GridPane.columnIndex="1" GridPane.rowIndex="0">
                                    <items>
                                      <FXCollections fx:factory="observableArrayList">
                                        <String fx:value="도서 열람" />
                                        <String fx:value="도서 대출" />
                                        <String fx:value="도서 반납" />
                                        <String fx:value="스캔" />
                                        <String fx:value="기타" />
                                      </FXCollections>
                                    </items>
                                  </ComboBox>
                                  <ComboBox fx:id="location_combo" prefHeight="50.0" prefWidth="300.0" promptText="무인기사업부자료실" style="-fx-font-size: 18px;" GridPane.columnIndex="1" GridPane.rowIndex="1">
                                    <items>
                                    <FXCollections fx:factory="observableArrayList">
                                      <String fx:value="무인기사업부자료실" />
                                      <String fx:value="군용기정비자료실" />
                                      <String fx:value="품질경영부" />
                                    </FXCollections>
                                  </items>
                                 </ComboBox>
                                  <TextField fx:id="dept_field" prefHeight="50.0" prefWidth="300.0" GridPane.columnIndex="1" GridPane.rowIndex="2">
                                             <font>
                                                <Font size="18.0" />
                                             </font></TextField>
                                  <TextField fx:id="id_field" prefHeight="50.0" prefWidth="300.0" GridPane.columnIndex="1" GridPane.rowIndex="3">
                                             <font>
                                                <Font size="18.0" />
                                             </font></TextField>
                                  <TextField fx:id="name_field" prefHeight="50.0" prefWidth="300.0" GridPane.columnIndex="1" GridPane.rowIndex="4">
                                             <font>
                                                <Font size="18.0" />
                                             </font></TextField>
                               </children>
                            </GridPane>
                      </children>
                    </VBox>
                  </children>
                </HBox>
              </children>
            </VBox>
          </children></AnchorPane>
      </content>
    </Tab>
      <Tab text="History">
          <content>
              <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="794.0" prefWidth="1400.0">
                  <children>
                      <VBox prefHeight="778.0" prefWidth="1400.0" AnchorPane.bottomAnchor="-8.0" AnchorPane.leftAnchor="2.0" AnchorPane.rightAnchor="-2.0" AnchorPane.topAnchor="1.0">
                          <children>
                              <GridPane alignment="CENTER_RIGHT">
                                  <columnConstraints>
                                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                                  </columnConstraints>
                                  <rowConstraints>
                                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                                  </rowConstraints>
                                  <children>
                                      <Label text="이름" GridPane.halignment="RIGHT">
                                 <GridPane.margin>
                                    <Insets right="10.0" />
                                 </GridPane.margin></Label>
                                      <Label text="Purpose" GridPane.halignment="RIGHT" GridPane.rowIndex="1">
                                 <GridPane.margin>
                                    <Insets right="10.0" />
                                 </GridPane.margin></Label>
                                      <Label text="Location" GridPane.halignment="RIGHT" GridPane.rowIndex="2">
                                 <GridPane.margin>
                                    <Insets right="10.0" />
                                 </GridPane.margin></Label>
                                      <Label text="From" GridPane.columnIndex="2" GridPane.halignment="RIGHT">
                                 <GridPane.margin>
                                    <Insets right="10.0" />
                                 </GridPane.margin></Label>
                                      <Label text="To" GridPane.columnIndex="2" GridPane.halignment="RIGHT" GridPane.rowIndex="1">
                                 <GridPane.margin>
                                    <Insets right="10.0" />
                                 </GridPane.margin></Label>
                                      <TextField fx:id="search_name" GridPane.columnIndex="1" />
                                      <ComboBox fx:id="search_purpose" prefHeight="17.0" prefWidth="297.0" promptText="도서 열람" GridPane.columnIndex="1" GridPane.rowIndex="1">
                                          <items>
                                              <FXCollections fx:factory="observableArrayList">
                                                  <String fx:value="" />
                                                  <String fx:value="도서 열람" />
                                                  <String fx:value="도서 대출" />
                                                  <String fx:value="도서 반납" />
                                                  <String fx:value="스캔" />
                                                  <String fx:value="기타" />
                                              </FXCollections>
                                          </items>
                                      </ComboBox>
                                      <ComboBox fx:id="search_location" prefHeight="17.0" prefWidth="297.0" promptText="무인기사업부자료실" GridPane.columnIndex="1" GridPane.rowIndex="2">
                                          <items>
                                              <FXCollections fx:factory="observableArrayList">
                                                  <String fx:value="" />
                                                  <String fx:value="무인기사업부자료실" />
                                                  <String fx:value="군용기정비자료실" />
                                                  <String fx:value="품질경영부" />
                                              </FXCollections>
                                          </items>
                                      </ComboBox>
                                      <DatePicker fx:id="search_from" GridPane.columnIndex="3" />
                                      <DatePicker fx:id="search_to" GridPane.columnIndex="3" GridPane.rowIndex="1" />
                                      <Button fx:id="history_search" minWidth="100.0" mnemonicParsing="false" onAction="#history_search_click" text="검색" GridPane.columnIndex="5" />
                                      <Button fx:id="initiate_search" minWidth="100.0" mnemonicParsing="false" onAction="#initiate_search_click" text="초기화" GridPane.columnIndex="5" GridPane.rowIndex="1" />
                                  </children>
                                  <VBox.margin>
                                      <Insets top="20.0" />
                                  </VBox.margin>
                              </GridPane>
                              <TableView fx:id="historyTable" prefHeight="500.0" prefWidth="1400.0" VBox.vgrow="ALWAYS">
                                  <columns>
                                      <TableColumn fx:id="colEmpNo" minWidth="100.0" prefWidth="150.0" text="사번" style="-fx-alignment:CENTER"/>
                                      <TableColumn fx:id="colName" minWidth="100.0" prefWidth="150.0" text="이름"  style="-fx-alignment:CENTER"/>
                                      <TableColumn fx:id="colDept" minWidth="100.0" prefWidth="150.0" text="부서"  style="-fx-alignment:CENTER"/>
                                      <TableColumn fx:id="colIn_D" minWidth="200.0" prefWidth="250.0" sortType="DESCENDING" text="입장" />
                                      <TableColumn fx:id="colOut_D" minWidth="200.0" prefWidth="250.0" text="퇴장" />
                                      <TableColumn fx:id="colPurpose" minWidth="150.0" prefWidth="200.0" text="방문목적" />
                                      <TableColumn fx:id="colLocation" minWidth="200.0" prefWidth="300.0" resizable="true" text="위치" />
                                  </columns>
                                  <VBox.margin>
                                      <Insets top="15.0" />
                                  </VBox.margin>
                              </TableView>
                          </children>
                      </VBox>
                  </children></AnchorPane>
          </content>
      </Tab>

  </tabs>
</TabPane>

 

3. module-info.java

JavaFX에서 모듈을 인식하기 위해서는 module-info.java가 필요하다. 한 프로젝트 안에서 동작하는 것임에도 손으로 하나씩 추가해야하는 부분이 많다. 뭐 하나라도 빠지면 동작을 안해서 난감했다.

module com.example.javafx05 {
    requires javafx.controls;
    requires javafx.fxml;
    requires org.mybatis;  <--추가
    requires java.sql;     <--추가
    requires com.fazecast.jSerialComm;  <--추가


    opens com.example.javafx05 to javafx.fxml;
    exports com.example.javafx05;
    exports com.example.javafx05.emp to org.mybatis;     <--추가(Mapper용)
    exports com.example.javafx05.history to org.mybatis; <--추가(Mapper용)

    opens mapper;<--추가(Mapper용)
}

 

 

4. Database접속(mybatis-config.xml)

이 파일은 특별할 건 없다. 형식에 맞춰서 입력만 해주면 된다.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@10.48.63.71:1526:database_name"/>
                <property name="username" value="my_user_name"/>
                <property name="password" value="my_user_pw"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/empMapper.xml"/>
        <mapper resource="mapper/historyMapper.xml"/>
    </mappers>
</configuration>

 

5. MyBatisUtil.java

MyBatis를 사용시 데이터베이스 연결을 관리하는 파일이다. 

package com.example.javafx05;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

 

6. HelloApplication

시작점이 되는 파일이다. 코드 아래쪽을 보면 SerialService라는 서비스를 불러내는데, controller를 인자로 넘겨준다. controller는 화면 구성요소와 그에 대한 controll을 하는 부분이다. 이 controller를 넘겨줘야 Serial 데이터의 입력에 맞춰 화면에 정보를 뿌릴 수 있다. 

package com.example.javafx05;

import com.example.javafx05.emp.EmpDto;
import com.example.javafx05.emp.EmpService;
import com.fazecast.jSerialComm.SerialPort;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {

    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader loader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(loader.load(), 900, 800);
        HelloController controller = loader.getController();

        stage.setTitle("Data Room Security");
        stage.setScene(scene);
        stage.show();

        SerialService serialService = new SerialService(controller);  //<-- 시리얼 통신 + UI 컨트롤
        serialService.initializeSerialCommunication();                //<-- 시리얼 통신 + UI 컨트롤
    }

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

 

7. SerialService.java

위의 HelloApplication에서 시작하여 Serial데이터를 받기 시작하는 서비스이다. 데이터를 너무 빨리 처리하면 Serial데이터가 두번에 나눠져 들어온다. 그래서 초기에 약간의 대기시간(50ms)을 두었으며, 그래도 모를 예외를 대비해서 12자리를 모두 채우면 데이터를 처리하도록 만들었다.

 

데이터(message)가 취득되면 emp_check이라는 직원 체크 함수로 간다. 이 함수에서 MyBatis를 통한 DB데이터를 가져오고, 최종 만들어진 데이터 및 인사말은 

```Platform.runLater(() -> controller.updateUI(emp, finalHello));``` 

부분에서 화면으로 전달된다.

 

package com.example.javafx05;

import com.example.javafx05.emp.EmpDto;
import com.example.javafx05.emp.EmpService;
import com.fazecast.jSerialComm.SerialPort;
import javafx.application.Platform;
import javafx.scene.control.Alert;

import java.util.HashMap;
import java.util.Map;

public class SerialService {

    private final HelloController controller;
    private final EmpService empService = new EmpService();
    private SerialPort serialPort;
    private String message = "";

    public SerialService(HelloController controller){
        this.controller = controller;
    }

    public void initializeSerialCommunication(){
        SerialPort[] ports = SerialPort.getCommPorts();
        if (ports.length ==0){
            System.out.println("No serial ports available");
            return;
        }

        serialPort = ports[0];
        serialPort.setComPortParameters(9600, 8, 1, 0);
        serialPort.openPort();
        System.out.println("Serial port opend: " + serialPort.getSystemPortName());

        // 데이터 수신 스레드 시작
        new Thread(() -> {
            while(serialPort.isOpen()){
                try{
                    if (serialPort.bytesAvailable() > 0) {
                        Thread.sleep(50); // 짧은 시간 대기
                        byte[] readBuffer = new byte[serialPort.bytesAvailable()];
                        int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
                        String receivedData = new String(readBuffer, 0, numRead);
                        message += receivedData;
                        // 12자리 데이터가 모두 수신되었는지 확인
                        if (message.length() >= 12) {
//                            showPopup(message.substring(4, 11)); // 필요한 길이만큼만 팝업에 표시
                            emp_check(message.substring(4, 11));
                            message = "";   // message 초기화
                            Thread.sleep(3000); // 3초
                            init_screen();
                        }
                    } else {
                        // 데이터가 일정 시간 동안 들어오지 않으면 (예: 50ms) message 초기화
                        // 이는 데이터가 끊겨서 들어올 때 이전 데이터와 합쳐지는 것을 방지합니다.
                        try {
                            Thread.sleep(10); // 짧은 시간 대기
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        if (serialPort.bytesAvailable() == 0 && !message.isEmpty()) {
                            message = "";
                        }
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void emp_check(String emp_n){
        EmpDto emp = empService.selectAll(emp_n);

        Map<String, String> history = new HashMap<String, String>();
        history = empService.check_history(emp_n);
        String purpose= controller.getSelectedPurpose();
        String location=controller.getSelectedLocation();

        String hello="";
        if(history==null){
            hello="안녕하세요";
            empService.in_log(emp_n, purpose, location);
        }else{
            hello="안녕히가세요";
            empService.out_log(emp_n);
        }

        final String finalHello=hello;
        Platform.runLater(() -> controller.updateUI(emp, finalHello));
    }

    private void init_screen(){
        Platform.runLater(() -> controller.updateUI(null,"입/퇴장시 체크해주세요"));
    }

}

 

8. EmpService (직원정보 관련 서비스)

package com.example.javafx05.emp;

import com.example.javafx05.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

public class EmpService {
    public EmpDto selectAll(String emp_number){
        SqlSession session = MyBatisUtil.getSession();
        EmpDto emp_found = null;

        try{
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            emp_found = mapper.select_member(emp_number);
//            System.out.println(emp_found.toString());
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return emp_found;
    }

    public Map<String, String> check_history(String emp_number){
        SqlSession session = MyBatisUtil.getSession();
        Map<String, String> result = new HashMap<String, String>();

        try{
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            result = mapper.history_found(emp_number);
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return result;
    }

    public void in_log(String emp_number, String purpose, String location){
        SqlSession session = MyBatisUtil.getSession();
        try{
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            mapper.history_in_log(emp_number, purpose, location);
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return;
    }

    public void out_log(String emp_number){
        SqlSession session = MyBatisUtil.getSession();
        try{
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            mapper.history_out_log(emp_number);
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return;
    }

}

 

9. EmpDto 

package com.example.javafx05.emp;

public record EmpDto (
    String emp_no,
    String emp_x,
    String kornm_n,
    String hannm_n,
    String engnm_n,
    String res,
    String dept_c,
    String dept_n
) {
}

 

10. EmpMapper

package com.example.javafx05.emp;

import org.apache.ibatis.annotations.Param;

import java.util.Map;

public interface EmpMapper {
    EmpDto select_member(String emp_no);
    Map<String, String> history_found(String emp_no);
    void history_in_log(@Param("emp_no") String emp_no,@Param("purpose")  String purpose,@Param("location") String location);
    void history_out_log(String emp_no);
}

 

 

11. empMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.javafx05.emp.EmpMapper">
    <select id="select_member" resultType="com.example.javafx05.emp.EmpDto">
        select emp_# as emp_no,
        emp_x,
        kornm_n,
        hannm_n,
        engnm_n,
        res_#1 as res,
        dept_c,
        dept_n
        from bemp a
        where a.emp_#=#{emp_no}
    </select>

    <select id="history_found" resultType="map">
        select EMP_# as emp_no,
        IN_D,
        OUT_D,
        PURPOSE,
        LOCATION
        FROM BEMP_DATAROOM_HSTRY a
        where a.emp_#=#{emp_no}
        AND to_char(a.in_d,'YYYYMMDD')=to_char(SYSDATE,'YYYYMMDD')
        AND a.OUT_D IS null
        ORDER BY a.IN_D DESC
    </select>

    <select id="history_in_log">
        insert into BEMP_DATAROOM_HSTRY (emp_#, in_d, out_d, purpose, location)
        values (#{emp_no}, sysdate,NULL,#{purpose},#{location})
    </select>

    <select id="history_out_log">
        update BEMP_DATAROOM_HSTRY a
        set a.out_d=sysdate
        where a.emp_#=#{emp_no}
        and a.out_d IS NULL
        AND to_char(a.in_d,'YYYYMMDD')=to_char(SYSDATE,'YYYYMMDD')
    </select>
</mapper>

 

12. HistoryDto

package com.example.javafx05.history;

public record HistoryDto( String emp_no,
                          String kornm_n,
                          String dept_c,
                          String in_d,
                          String out_d,
                          String purpose,
                          String location) {
}

 

13. HistoryMapper

package com.example.javafx05.history;

import org.apache.ibatis.annotations.Param;

import java.time.LocalDate;
import java.util.List;

public interface HistoryMapper {
    List<HistoryDto> historyRecords(@Param("emp_name") String emp_name,
                                    @Param("purpose") String purpose,
                                    @Param("location")  String location,
                                    @Param("from")  String from,
                                    @Param("to")  String to); //,, LocalDate to
}

 

14. HistoryService

package com.example.javafx05.history;

import com.example.javafx05.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class HistoryService {
    public List<HistoryDto> find_history(String emp_name, String purpose, String location, String from, String to){
        SqlSession session = MyBatisUtil.getSession();
        List<HistoryDto> result = new ArrayList<>();

        try{
            HistoryMapper mapper = session.getMapper(HistoryMapper.class);
            result = mapper.historyRecords(emp_name, purpose, location, from, to);
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return result;
    }
}

 

15. historyMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.javafx05.history.HistoryMapper">
    <select id="historyRecords" resultType="com.example.javafx05.history.HistoryDto">
        select a.emp_# ,
        b.KORNM_N ,
        b.dept_c,
        a.in_d,
        a.out_d,
        a.purpose,
        a.location
        from temp_dataroom_hstry a, temp b
        where a.emp_#=b."EMP_#"
        <if test="emp_name!=null and emp_name!=''">
            and b.kornm_n like '%'||#{emp_name}||'%'
        </if>
        <if test="purpose!=null and purpose!=''">
            and a.purpose like '%'||#{purpose}||'%'
        </if>
        <if test="location!=null and location!=''">
            and a.location like '%'||#{location}||'%'
        </if>
        <if test="from!=null and from!=''">
            and a.in_d &gt; to_date(#{from},'YYYY-MM-DD')
        </if>
        <if test="to!=null and to!=''">
            and a.in_d &lt; to_date(#{to},'YYYY-MM-DD')
        </if>
        order by a.in_d desc
    </select>

</mapper>

 

 

[결과 화면 ]

 

반응형
반응형

재귀적으로 처리하는 여러 예제가 있는데, AI한테 물어보니 간단한 방법을 알려줬다.

 

import org.apache.commons.io.FileUtils;

public class CopyDirectoryCommonsIO {
    public static void main(String[] args) throws IOException {
        Path source = Paths.get("C:/source/folder");
        Path target = Paths.get("C:/target/folder");

        FileUtils.copyDirectory(source.toFile(), target.toFile());
        System.out.println("폴더 복사 완료");
    }
}

 

 

반응형
반응형

 

위와 같이 프로젝트가 구성되있다고 할 때, pom.xml에 mybatis와 database driver를 설치해줍니다.

 

1. pom.xml (Maven기준)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>abc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>javafx03_mybatis</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.10.0</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>17.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17.0.6</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>12.4.2.jre11</version>
            <scope>runtime</scope>
        </dependency>
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.8</version>
                <executions>
                    <execution>
                        <!-- Default configuration for running with: mvn clean javafx:run -->
                        <id>default-cli</id>
                        <configuration>
                            <mainClass>org.example.abc.HelloApplication</mainClass>
                            <launcher>app</launcher>
                            <jlinkZipName>app</jlinkZipName>
                            <jlinkImageName>app</jlinkImageName>
                            <noManPages>true</noManPages>
                            <stripDebug>true</stripDebug>
                            <noHeaderFiles>true</noHeaderFiles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

 

2. module-info.java

스프링처럼 사용하려면 module-info.java 파일이 필요함. 아래의 추가부분을 설정해준다. (이 부분을 몰라서 한참 헤멤)

module org.example.abc {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.sql;
    requires org.mybatis;  // <-- Add this

    opens org.example.abc to javafx.fxml;
    exports org.example.abc;
    exports org.example.abc.mapper;
    opens org.example.abc.mapper to javafx.fxml;
    exports org.example.abc.dto;
    opens org.example.abc.dto to javafx.fxml;
    opens mapper; // <-- 이거 추가해야 mapper 인식
}

 

3. MyBatisUtil.java

 

package org.example.abc;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

 

4. mybatis-config.xml

특별한 건 없습니다. DB 접속정보를 적어주고, Mapper의 위치를 적어줍니다.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
                <property name="url" value="jdbc:sqlserver://<databaseURL>:<port_number>;databaseName=<DB>;encrypt=true;trustServerCertificate=true;"/>
                <property name="username" value="<username>"/>
                <property name="password" value="<password>"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/<매퍼이름>.xml"/>
    </mappers>
</configuration>

 

Mapper.xml 상세와 DTO, UI상세 등은 Spring과 동일함.

반응형
반응형
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
                <property name="url" value="jdbc:sqlserver://<주소>:<포트>;databaseName=<DB이름>;encrypt=true;trustServerCertificate=true;"/>
                <property name="username" value="이름"/>
                <property name="password" value="비밀번호"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/dbMapper.xml"/>
        <mapper resource="mapper/itemMapper.xml"/>
    </mappers>
</configuration>

 

encrypt=true;trustServerCertificate=true;

이 구문을 넣어줘야한다.

반응형
반응형

프로젝트 구조

 

1. 프로젝트 생성시 Mavin으로 생성

- pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>swing02_mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc11 -->
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc11</artifactId>
            <version>23.5.0.24.07</version>
        </dependency>

        <dependency>
            <groupId>com.oracle.ojdbc</groupId>
            <artifactId>orai18n</artifactId>
            <version>19.3.0.0</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

 

 

(ps) libs폴더에 테마를 위한 파일들을 넣어주고 "프로젝트 구조 > 종속 요소"에서 추가해준다. 개인적 취향...

idw-gpl.jar
0.70MB
JTattoo.jar
0.62MB
liquidlnf.jar
0.35MB
ojdbc6-11.2.0.4.jar
2.61MB
quaqua.jar
1.94MB

 

 

2. mybatis-config.xml에서 DB정보 생성

 

3. org.example.mapper > dbMapper 인터페이스 생성

package org.example.mapper;

import org.example.model.dbModel;
import java.util.List;

public interface dbMapper {
    List<dbModel> selectAll();
}

 

4. org.example.dto> dbDto생성 (레코드 형식이 편해서 클래스 대신 레코드를 주로 사용함)

package org.example.dto;

public record dbDto(
        String emp_no,
        String emp_x,
        String kornm_n,
        String hannm_n,
        String engnm_n,
        String res
) {
}

 

5. MyBatisUtil 생성

package org.example;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

 

 

6. service > DbService 생성

DAO를 생성하는 경우가 많이 있는 것 같은데, 개인적으로는 복잡도가 낮아서 service만 만들어 구현해도 큰 어려움이 없는것 같다. DAO에 대한 개념도 없는 상태라, 프로젝트의 복잡도만 늘리는 것 같아서 Service만 구현했다.

package org.example.service;

import org.apache.ibatis.session.SqlSession;
import org.example.MyBatisUtil;
import org.example.dto.dbDto;
import org.example.mapper.dbMapper;

import java.util.List;

public class DbService {
    public List<dbDto> selectAll(){
        SqlSession session = MyBatisUtil.getSession();
        List<dbDto> list = null;

        try{
            dbMapper mapper = session.getMapper(dbMapper.class);
            list = mapper.selectAll();
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            session.close();
        }
        return list;
    }
}

 

 

7. resources > mapper > dbMapper.xml 생성

Spring에서 사용하던 Mybatis와 동일하게 생성

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.example.mapper.dbMapper">
    <select id="selectAll" resultType="org.example.model.dbModel">
        select emp_# as emp_no,
        emp_x,
        kornm_n,
        hannm_n,
        engnm_n,
        res_#1 as res
        from temp a
        where a.kornm_n='김동개'
    </select>
</mapper>

 

8. org.example.view > MainView.java 생성

package org.example.view;

import org.example.dto.dbDto;
import org.example.service.DbService;

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

public class MainView extends JFrame {
        DbService dbService = new DbService();

        JFrame f1 =new JFrame();    // Main Frame
        JMenuBar mb = new JMenuBar(); // 메뉴바
        JPanel sidePanel = new JPanel(); // 사이드 패널
        JPanel contentPanel = new JPanel(); // 컨텐츠 패널
        JPanel footerPanel = new JPanel();  // 푸터 패널
        JButton jb1 = new JButton("search"); // 버튼 초기화
        JButton jb2 = new JButton("insert"); // 버튼 초기화
        JButton jb3 = new JButton("delete"); // 버튼 초기화

//      JTable data_table = new JTable(); //테이블 생성시에는 초기값과 헤더를 넣어줘야한다. 
//        이 작업은 초기 화면 생성하는 함수에 넣어주기 위해, 아래와 같이 null로 우선 생성한다.
        JTable data_table = null;

        public void set_style(Component target){
            // 스타일 적용(Look & Feel)
            try{
                UIManager.setLookAndFeel ("com.birosoft.liquid.LiquidLookAndFeel"); 	//Liquid
            }catch(Exception e){
                System.out.println(e + "오류 발생");
            }
            SwingUtilities.updateComponentTreeUI(target) ;
        }

        public void createFrame(){
            // Main Frame 세팅
            f1.setSize(1024,760);//크기
            f1.setDefaultCloseOperation(f1.EXIT_ON_CLOSE);
            f1.setLocationRelativeTo(null);

            // 스타일 적용
            f1.setDefaultLookAndFeelDecorated(true);
            set_style(f1);

            // 아이콘 적용
            Image icon = Toolkit.getDefaultToolkit().getImage("D:\\7_System_dev2\\4_Java\\01_gui\\src\\icon.png");
            f1.setIconImage(icon);

            // 레이아웃 적용
            BorderLayout bl = new BorderLayout();
            f1.setLayout(bl);

            // 화면 요소 생성 및 추가
            createMenu();
            createSidePanel();
            createContentPanel();
            createFooter();

            f1.add(mb, BorderLayout.NORTH);
            f1.add(sidePanel, BorderLayout.WEST);       // f1라는 프레임에 sidePanel추가
            f1.add(contentPanel, BorderLayout.CENTER);  // f1라는 프레임에 contentPanel추가
            f1.add(footerPanel, BorderLayout.SOUTH);    // f1라는 프레임에 FooterPanel추가

            f1.setTitle("Frame Test");//제목
            f1.setVisible(true);//생성
        }

        // 메뉴바
        public void createMenu(){
            JMenu fileMenu = new JMenu("File");
            fileMenu.add(new JMenuItem("New"));
            fileMenu.add(new JMenuItem("Open"));
            fileMenu.add(new JMenuItem("Preferences"));

            mb.add(fileMenu);
            mb.add(new JMenu("Edit"));
            mb.add(new JMenu("About"));
            mb.add(new JMenu("Help"));
            setJMenuBar(mb);
        }

        // 사이드 패널
        public void createSidePanel(){
            sidePanel.setPreferredSize(new Dimension(100, 300)); // 사이드패널 사이즈 조절
            sidePanel.setBorder(BorderFactory.createEmptyBorder(15 , 10, 10 , 10));
//            sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS));

            sidePanel.add(jb1);
            sidePanel.add(jb2);
            sidePanel.add(jb3);

            set_style(sidePanel);

            jb1.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    data_mapping();

                    // 패널 갱신
                    contentPanel.revalidate();
                    contentPanel.repaint();
                }
            });
        }

        // Contents 패널
        public void createContentPanel(){
            contentPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
            JLabel Headline = new JLabel("Swing Table Data with Styles");
            Font f = new Font("고딕", Font.BOLD,20);
            Headline.setFont(f);
            contentPanel.add(Headline);

            // 테이블 준비
            String[] header = {"EMP No", "Name"};
            String[][] contents = {{"",""},{"",""},{"",""}};
            data_table = new JTable(contents, header);
            Font font = new Font("고딕", Font.PLAIN,12);
            data_table.setFont(font);
            contentPanel.add(new JScrollPane(data_table), BorderLayout.CENTER);
			// JScrollPane(data_table)에 넣어주지 않으면 header가 나타나지 않는다.
            set_style(contentPanel);
        }

        // Footer
        public void createFooter(){
            footerPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            footerPanel.setBackground(Color.orange);
            JLabel Footer = new JLabel("Copyright by Wilkyway");
            footerPanel.add(Footer);

            // set_style(footerPanel);
        }

        public void data_mapping() {
            List<dbDto> models = dbService.selectAll();

            int i=0;
            for (dbDto model : models) {
                System.out.println("ID: " + model.emp_no() + ", Name: " + model.kornm_n());
                data_table.setValueAt(model.emp_no(),i,0);
                data_table.setValueAt(model.kornm_n(),i,1);
                i++;
            }
        }

}

 

 

8. Main.java

package org.example;
import org.example.view.MainView;

public class Main {

    public static void main(String[] args) {
        MainView mp = new MainView();
        mp.createFrame();
    }
}

 

 

<결과>

반응형
반응형

 인텔리제이(Intellij) IDE 를 사용하여 간단한 텍스트 에디터를 만들어보도록 하겠습니다.

 

1. 새 프로젝트 생성

인텔리제이 메뉴에서 File - New - Project 를 클릭하여 새 프로젝트를 생성해줍니다. Name은 editor로 하고, 적당한 위치에 아래와 같은 세팅으로 진행할 예정입니다. JDK는 설치되어있지 않다면 JDK의 드롭다운 메뉴 중 Download JDK를 눌러, 적당한 버전을 고른 후 다운로드 받아줍니다. 혹은 직접 원하는 JDK를 다운로드 받아서 선택할 수도 있습니다.

2. Main Class 생성

프로젝트 하위 폴더 중 src에서 우클릭하여 New - Java Class 를 클릭한 후, 클래스 이름을 editor로 하여 새로운 클래스를 생성해줍니다. 

만들어진 클래스 내부에 프로그램 진입점인 main함수를 만들어서 테스트해보겠습니다.

public class editor {
    public static void main(String[] args){
        System.out.println("Hello world");
    }
}

3. Build & Run

Build - Build Project를 눌러 프로젝트를 빌드해줍니다. (최초에는 Run 메뉴가 아직 활성화되지 않았습니다. 한번만 Build해주면, 다음부터는 Run만해도 자동으로 Build까지 수행해줍니다.)

다음으로 Run해줍니다. 그리고 editor라고 되어있는 메뉴를 클릭합니다.

콘솔에 Hello world가 잘 나옵니다.

4. GUI 프로그램 코드

아래의 코드를 복사하여 실행이 되는지 확인해봅니다.

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


public class editor extends JFrame implements ActionListener {

    JTextArea t;
    JFrame f;

    // Constructor
    editor(){
        f = new JFrame("editor");
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        
        // 테마 설정
        try{
            UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
        } catch (Exception e) {
            System.out.println(e + "오류 발생");
        }
                
        t = new JTextArea(); // 텍스트 편집창
        JMenuBar mb = new JMenuBar(); // 메뉴바

        JMenu m1 = new JMenu("File"); //메뉴1
        JMenuItem mi1 = new JMenuItem("New"); //메뉴 아이템1
        JMenuItem mi2 = new JMenuItem("Open"); //메뉴 아이템2
        JMenuItem mi3 = new JMenuItem("Save"); //메뉴 아이템3
        JMenuItem mi9 = new JMenuItem("Print"); //메뉴 아이템4
        mi1.addActionListener(this);
        mi2.addActionListener(this);
        mi3.addActionListener(this);
        mi9.addActionListener(this);
        m1.add(mi1);
        m1.add(mi2);
        m1.add(mi3);
        m1.add(mi9);

        JMenu m2 = new JMenu("Edit");	// 메뉴2
        JMenuItem mi4 = new JMenuItem("cut"); //메뉴 2-1
        JMenuItem mi5 = new JMenuItem("copy");//메뉴 2-2
        JMenuItem mi6 = new JMenuItem("paste");//메뉴 2-3
        mi4.addActionListener(this);
        mi5.addActionListener(this);
        mi6.addActionListener(this);
        m2.add(mi4);
        m2.add(mi5);
        m2.add(mi6);

        JMenuItem mc = new JMenuItem("close"); // 메뉴3
        mc.addActionListener(this);

        mb.add(m1);
        mb.add(m2);
        mb.add(mc);

        f.setJMenuBar(mb);
        f.add(t);
        f.setSize(500, 500);
        f.show();


    }

	// 각 클릭 이벤트에 대한 기능 정의
    @Override
    public void actionPerformed(ActionEvent e) {
        String s = e.getActionCommand();

        if (s.equals("cut")){
            t.cut();
        } else if (s.equals("copy")){
            t.copy();
        } else if(s.equals("paste")){
            t.paste();
        } else if (s.equals("Save")){
            JFileChooser j = new JFileChooser("f:");

            int r = j.showSaveDialog(null);

            if (r == JFileChooser.APPROVE_OPTION){
                File fi = new File(j.getSelectedFile().getAbsolutePath());
                try {
                    FileWriter wr = new FileWriter(fi, false);
                    BufferedWriter w = new BufferedWriter(wr);
                    w.write(t.getText());

                    w.flush();
                    w.close();
                } catch (Exception evt){
                    JOptionPane.showMessageDialog(f, evt.getMessage());
                }
            } else JOptionPane.showMessageDialog(f, "the user cancelled the operation");
        } else if (s.equals("Print")) {
            try {
                t.print();
            } catch (Exception evt) {
                JOptionPane.showMessageDialog(f, evt.getMessage());
            }
        } else if (s.equals("Open")){
            JFileChooser j = new JFileChooser("f:");
            int r = j.showOpenDialog(null);
            if (r == JFileChooser.APPROVE_OPTION){
                File fi = new File(j.getSelectedFile().getAbsolutePath());

                try {
                    String s1 = "", sl = "";
                    FileReader fr = new FileReader(fi);
                    BufferedReader br = new BufferedReader(fr);

                    sl = br.readLine();

                    while((s1 = br.readLine()) != null){
                        sl = sl + "\n" + s1;
                    }
                    t.setText(sl);
                } catch(Exception evt){
                    JOptionPane.showMessageDialog(f, evt.getMessage());

                }
            } else JOptionPane.showMessageDialog(f, "the user canced the operation");
        }
        else if (s.equals("New")){
            t.setText("");
        } else if(s.equals("close")){
//            f.setVisible(false);
            System.exit(0);
        }
    }

    public static void main(String[] args) {

        editor e = new editor();
    }
}

 

 

5. 테마 적용

프로젝트(editor) 에서 우클릭 후 New- Directory를 클릭하고, 폴더 이름을 libs로 하여 새 폴더를 생성합니다.

생성된 폴더에 제가 애용하는 liquid 테마를 복사해 넣습니다. 해당 테마(라이브러리)는 첨부 참조하시기 바랍니다.

liquidlnf.jar
0.35MB

폴더를 보면 liquidlnf.jar파일이 추가되어 있는 것이 보입니다. libs폴더를 우클릭 후, Add as Library...를 클릭, OK 클릭하면 해당 폴더의 라이브러리들이 자동으로 프로젝트 라이브러리 리스트에 추가됩니다.

실행해보면 liquid 테마가 들어간 프로그램이 실행되는 모습을 볼 수 있습니다. (버튼이 많아야 좀 더 화려한데...)

 

이상으로 간단한 텍스트 에디터를 Swing으로 만들어보았습니다.

 

~~끝~~

반응형
반응형

 

linux를 처음 알고 시작했을 당시만해도 xmms라는 콘솔에서 실행하는 프로그램을 설치하고 음악을 듣곤 했었는데, 거기서부터 파생된 gui형태의 프로그램들이 많이 나온것 같습니다. xmms2도 있었고, audacious라는 프로그램을 최근까지도 메인으로 사용하고 있었는데, 얼마전 qmmp라는 또다른 프로그램을 알게 되었습니다. 이름에서 알 수 있듯이 QT기반의 프로그램 이라고 합니다. 어떤 녀석인지 한 번 설치해 보도록 하겠습니다.

현재 제 데스크탑에는 ubuntu 20.04 lts가 설치되어 있습니다. 그래서 ubuntu package manager로 가서 qmmp를 찾아봅니다. 2개가 나오는데 어떤걸까요? 아래쪽이 1.5 버전이라고 되어있어서 아래쪽 프로그램을 설치하겠습니다.

설치하고 나니 보이긴 하는데, 아이콘이 안나오네요...ㅠㅠ

 

프로그램 실행은 문제가 없어 보입니다.

아이콘이 안나오는게 찜찜하네요. 아까 설치하지 않은 1.3버전을 설치해보도록 하겠습니다. 혹시 모르니 qmmp 사이트에서 repository를 추가한 후 업데이트를 합니다.

sudo add-apt-repository ppa:forkotov02/ppa
sudo apt update

 

나비모양의 아이콘이 있는 Qmmp가 하나 더 설치되었습니다.

실행해보니 버전이 1.6.1??

저장소 업데이트가 효과가 있었나봅니다. 먼저 설치했던(아이콘 안나오는..) 1.5버전을 삭제했습니다. 그래도 실행이 잘 되네요..^^;;

 

스킨을 한번 변경해보겠습니다. 구글에서 qmmp skin 이라고 검색하고 확장자가 .wsz인 파일 몇개를 다운받아 놓습니다. 어떤 분이 몇가지 스킨을 모아놓으셔서 링크를 공유해드립니다. 다운받은 뒤 Qmms 우클릭 > 설정 > 모양새 > 스킨 > 추가...로 받아놓은 스킨 파일들을 추가해줍니다.

적당한 스킨을 하나 클릭하여 "닫기" 버튼을 클릭하면..

잘 적용이 되네요~

반응형

+ Recent posts