By GokiSoft.com| 19:29 29/03/2023|
Java Advanced

[Source Code] Tìm hiểu về đa ngôn ngữ trong Java - C2206L

#messages.properties

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

option_input = 1. Input data
option_display = 2. Display data
option_exit = 3. Exit
option_choose = Choose:

#messages_vi_VN.properties

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

option_input = 1. Nhap du lieu
option_display = 2. Hien thi du lieu
option_exit = 3. Thoat
option_choose = Chon:

#DataMgr.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft.lesson08;

import java.util.ArrayList;
import java.util.List;

/**
 * DataMgr -> tao ra duy nhat 1 object -> singleton object -> design class object
 * @author teacher
 */
public class DataMgr {
    List<Student> studentList;

    private static DataMgr instance = null;
    
    public static synchronized DataMgr getInstance() {
        if(instance == null) {
            instance = new DataMgr();
        }
        return instance;
    }
    
    private DataMgr() {
        this.studentList = new ArrayList<>();
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}

#LanguageFrame.form

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

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
  </Properties>
  <SyntheticProperties>
    <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
    <SyntheticProperty name="generateCenter" type="boolean" value="false"/>
  </SyntheticProperties>
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace min="-2" pref="49" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" attributes="0">
                  <Component id="option4Label" min="-2" max="-2" attributes="0"/>
                  <Component id="option3Label" min="-2" max="-2" attributes="0"/>
                  <Component id="option2Label" min="-2" max="-2" attributes="0"/>
                  <Component id="option1Label" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace max="32767" attributes="0"/>
          </Group>
          <Group type="102" alignment="1" attributes="0">
              <EmptySpace pref="340" max="32767" attributes="0"/>
              <Component id="vnBtn" min="-2" max="-2" attributes="0"/>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Component id="enBtn" min="-2" max="-2" attributes="0"/>
              <EmptySpace min="-2" pref="19" max="-2" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="vnBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="enBtn" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
              <Component id="option1Label" min="-2" max="-2" attributes="0"/>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Component id="option2Label" min="-2" max="-2" attributes="0"/>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Component id="option3Label" min="-2" max="-2" attributes="0"/>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Component id="option4Label" min="-2" max="-2" attributes="0"/>
              <EmptySpace pref="151" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Component class="javax.swing.JLabel" name="option1Label">
      <Properties>
        <Property name="text" type="java.lang.String" value="1. Nhap du lieu"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JLabel" name="option2Label">
      <Properties>
        <Property name="text" type="java.lang.String" value="2. Hien thi du lieu"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JLabel" name="option3Label">
      <Properties>
        <Property name="text" type="java.lang.String" value="3. Thoat"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JLabel" name="option4Label">
      <Properties>
        <Property name="text" type="java.lang.String" value="Chon: "/>
      </Properties>
    </Component>
    <Component class="javax.swing.JButton" name="vnBtn">
      <Properties>
        <Property name="text" type="java.lang.String" value="Viet Nam"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="vnBtnActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JButton" name="enBtn">
      <Properties>
        <Property name="text" type="java.lang.String" value="English"/>
        <Property name="toolTipText" type="java.lang.String" value=""/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="enBtnActionPerformed"/>
      </Events>
    </Component>
  </SubComponents>
</Form>

#LanguageFrame.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft.lesson08;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 *
 * @author teacher
 */
public class LanguageFrame extends javax.swing.JFrame {

    /**
     * Creates new form LanguageFrame
     */
    public LanguageFrame() {
        initComponents();
        
        Locale locale = Locale.getDefault();
        changeLanguage(locale);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        option1Label = new javax.swing.JLabel();
        option2Label = new javax.swing.JLabel();
        option3Label = new javax.swing.JLabel();
        option4Label = new javax.swing.JLabel();
        vnBtn = new javax.swing.JButton();
        enBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        option1Label.setText("1. Nhap du lieu");

        option2Label.setText("2. Hien thi du lieu");

        option3Label.setText("3. Thoat");

        option4Label.setText("Chon: ");

        vnBtn.setText("Viet Nam");
        vnBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vnBtnActionPerformed(evt);
            }
        });

        enBtn.setText("English");
        enBtn.setToolTipText("");
        enBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(option4Label)
                    .addComponent(option3Label)
                    .addComponent(option2Label)
                    .addComponent(option1Label))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(340, Short.MAX_VALUE)
                .addComponent(vnBtn)
                .addGap(18, 18, 18)
                .addComponent(enBtn)
                .addGap(19, 19, 19))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vnBtn)
                    .addComponent(enBtn))
                .addGap(41, 41, 41)
                .addComponent(option1Label)
                .addGap(18, 18, 18)
                .addComponent(option2Label)
                .addGap(18, 18, 18)
                .addComponent(option3Label)
                .addGap(18, 18, 18)
                .addComponent(option4Label)
                .addContainerGap(151, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void vnBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vnBtnActionPerformed
        // TODO add your handling code here:
        Locale locale = new Locale("vi", "VN");
        changeLanguage(locale);
    }//GEN-LAST:event_vnBtnActionPerformed

    private void enBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enBtnActionPerformed
        // TODO add your handling code here:
        Locale locale = Locale.US;
        changeLanguage(locale);
    }//GEN-LAST:event_enBtnActionPerformed

    private void changeLanguage(Locale locale) {
        ResourceBundle bundle = ResourceBundle.getBundle("languages/messages", locale);
        
        option1Label.setText(bundle.getString("option_input"));
        option2Label.setText(bundle.getString("option_display"));
        option3Label.setText(bundle.getString("option_exit"));
        option4Label.setText(bundle.getString("option_choose"));
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LanguageFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LanguageFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LanguageFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LanguageFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LanguageFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton enBtn;
    private javax.swing.JLabel option1Label;
    private javax.swing.JLabel option2Label;
    private javax.swing.JLabel option3Label;
    private javax.swing.JLabel option4Label;
    private javax.swing.JButton vnBtn;
    // End of variables declaration//GEN-END:variables
}

#Main.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft.lesson08;

/**
 *
 * @author teacher
 */
public class Main {
    public static void main(String[] args) {
        DataMgr dataMgr = DataMgr.getInstance();
    }
}

#Student.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft.lesson08;

/**
 *
 * @author teacher
 */
public class Student {
    String name;
    String email;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

#Test.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft.lesson08;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 *
 * @author teacher
 */
public class Test {
    public static void main(String[] args) {
        showMenu();
    }
    
    static void showMenu() {
        Locale locale = new Locale("vi", "VN");
//        Locale locale = Locale.US;
        ResourceBundle bundle = ResourceBundle.getBundle("languages/messages", locale);
        
        System.out.println(bundle.getString("option_input"));
        System.out.println(bundle.getString("option_display"));
        System.out.println(bundle.getString("option_exit"));
        System.out.println(bundle.getString("option_choose"));
    }
}
Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)