By GokiSoft.com| 09:51 21/07/2021|
Java Basic

[Share Code] Tìm hiểu cú pháp lambda - Java Swing - Regular Express trong Java - Khóa học Java BT2341

#MainFrame.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 lesson08;

import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Diep.Tran
 */
public class MainFrame extends javax.swing.JFrame {
    DefaultTableModel tableModel;
    
    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        
        tableModel = (DefaultTableModel) bookTable.getModel();
    }

    /**
     * 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() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        booknameTxt = new javax.swing.JTextField();
        authorTxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        saveBtn = new javax.swing.JButton();
        resetBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        bookTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("QUAN LY THU VIEN");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("NHAP THONG TIN SACH"));

        jLabel1.setText("TEN SACH:");

        jLabel2.setText("TAC GIA:");

        saveBtn.setText("SAVE");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        resetBtn.setText("RESET");
        resetBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(51, 51, 51)
                        .addComponent(booknameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(51, 51, 51)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(saveBtn)
                                .addGap(18, 18, 18)
                                .addComponent(resetBtn))
                            .addComponent(authorTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(booknameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(authorTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveBtn)
                    .addComponent(resetBtn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bookTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "TEN SACH", "TAC GIA"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(bookTable);
        if (bookTable.getColumnModel().getColumnCount() > 0) {
            bookTable.getColumnModel().getColumn(0).setResizable(false);
            bookTable.getColumnModel().getColumn(2).setResizable(false);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
        // TODO add your handling code here:
        System.out.println("Click save");
        String bookName = booknameTxt.getText();
        String author = authorTxt.getText();
        
        tableModel.addRow(new Object[] {tableModel.getRowCount() + 1, bookName, author});
    }//GEN-LAST:event_saveBtnActionPerformed

    private void resetBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetBtnActionPerformed
        // TODO add your handling code here:
        System.out.println("Click reset");
        booknameTxt.setText("");
        authorTxt.setText("");
    }//GEN-LAST:event_resetBtnActionPerformed

    /**
     * @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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField authorTxt;
    private javax.swing.JTable bookTable;
    private javax.swing.JTextField booknameTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton resetBtn;
    private javax.swing.JButton saveBtn;
    // 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 lesson08;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    @FunctionalInterface
    interface IMessage {
        void onMessage();
    }
    
    @FunctionalInterface
    interface IMessage3 {
        void onMessage(String s1, String s2);
    }
    
    interface IMessage2 {
        void onMessage();
        void onMessage2();
    }
    
    static class OMessage implements IMessage {

        @Override
        public void onMessage() {
            System.out.println("Hello World!!!");
        }
        
    }
    
    public static void main(String[] args) {
        //Item 1 - For
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        
        list.forEach(v -> {
            System.out.println(v);
        });
        
        //Item 2 - Tim hieu ham tao trong lambda
        //Khoi tao doi tuong tu Interface -> IMessage
        IMessage m = new IMessage() {
            @Override
            public void onMessage() {
                System.out.println("Hello World!!!");
            }
        };
        m.onMessage();
        
        //Khoi tao tu class object -> kha bt
        OMessage o = new OMessage();
        o.onMessage();
        
        //Khoi tao doi tuong tu Interface -> IMessage
        IMessage m2 = () -> {
            System.out.println("Hello World --- OKOK!!!");
        };
        m2.onMessage();
        
        //Cach viet nay -> Trong than phuong thuc onMessage chi co 1 dong lenh
        IMessage m3 = () -> System.out.println("Hello World --- OKOK!!!");
        m3.onMessage();
        
        IMessage m4 = () -> {
            System.out.println("Hello World --- OKOK 1!!!");
            System.out.println("Hello World --- OKOK 2!!!");
            System.out.println("Hello World --- OKOK 3!!!");
            System.out.println("Hello World --- OKOK 4!!!");
            System.out.println("Hello World --- OKOK 5!!!");
        };
        m4.onMessage();
        
        IMessage2 m11 = new IMessage2() {
            @Override
            public void onMessage() {
                System.out.println("M1 --- ");
            }

            @Override
            public void onMessage2() {
                System.out.println("M2 ---");
            }
        };
        m11.onMessage();
        m11.onMessage2();
        
        IMessage3 m33 = new IMessage3() {
            @Override
            public void onMessage(String s1, String s2) {
                System.out.println("s1 = " + s1 + ", s2 = " + s2);
            }
        };
        m33.onMessage("123", "456");
        
        m33 = (String s1, String s2) -> {
            System.out.println("s1 = " + s1 + ", s2 = " + s2);
        };
        m33.onMessage("123", "456");
        
        m33 = (s1, s2) -> {
            System.out.println("s1 = " + s1 + ", s2 = " + s2);
        };
        m33.onMessage("123", "456");
        
        m33 = (s1, s2) -> System.out.println("s1 = " + s1 + ", s2 = " + s2);
        m33.onMessage("123", "456");
        
//        Stream
        System.out.println("======== T1 =================");
        Stream st1 = list.stream();
        st1.forEach(System.out::println);
        
        System.out.println("======== T2 =================");
        Stream st2 = list.parallelStream();
        st2.forEach(System.out::println);
        
        //Tim hieu ve pattern express
        //Vi du: s -> du lieu dau vao. Kiem tra xem s co chua 1 chuoi
        //p (sinh theo quy luat sau: aaba (a: a-z -> gom 1 -> 4 ky tu, b: 0 -> 9 gom 2-5 ky tu)
        String s = "xin chao abc15kk osdfdsf abb15kk sdfh";
        
        Pattern pattern = Pattern.compile("[a-z]{1,4}[a-z]{1,4}[0-9]{2,5}[a-z]{1,4}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(s);
        /**boolean matchFound = matcher.find();
        if(matchFound) {
            System.out.println("Tim thay");
        } else {
            System.out.println("Ko tim thay");
        }*/
        while(matcher.find()) {
            System.out.println("Tim thay: start = " + matcher.start()+ ", end = " + matcher.end());
            String sub = s.substring(matcher.start(), matcher.end());
            System.out.println("sub: " + sub);
        }
    }
}


#MainFrame.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"/>
    <Property name="title" type="java.lang.String" value="QUAN LY THU VIEN"/>
  </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" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" attributes="0">
                  <Component id="jPanel1" max="32767" attributes="0"/>
                  <Component id="jScrollPane1" max="32767" attributes="0"/>
              </Group>
              <EmptySpace 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"/>
              <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
              <EmptySpace type="unrelated" max="-2" attributes="0"/>
              <Component id="jScrollPane1" min="-2" pref="145" max="-2" attributes="0"/>
              <EmptySpace max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Container class="javax.swing.JPanel" name="jPanel1">
      <Properties>
        <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
          <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
            <TitledBorder title="NHAP THONG TIN SACH"/>
          </Border>
        </Property>
      </Properties>

      <Layout>
        <DimensionLayout dim="0">
          <Group type="103" groupAlignment="0" attributes="0">
              <Group type="102" alignment="0" attributes="0">
                  <EmptySpace min="-2" pref="31" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="1" attributes="0">
                      <Group type="102" attributes="0">
                          <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="51" max="-2" attributes="0"/>
                          <Component id="booknameTxt" min="-2" pref="338" max="-2" attributes="0"/>
                      </Group>
                      <Group type="102" alignment="1" attributes="0">
                          <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="51" max="-2" attributes="0"/>
                          <Group type="103" groupAlignment="0" attributes="0">
                              <Group type="102" attributes="0">
                                  <Component id="saveBtn" min="-2" max="-2" attributes="0"/>
                                  <EmptySpace type="separate" max="-2" attributes="0"/>
                                  <Component id="resetBtn" min="-2" max="-2" attributes="0"/>
                              </Group>
                              <Component id="authorTxt" min="-2" pref="338" max="-2" attributes="0"/>
                          </Group>
                      </Group>
                  </Group>
                  <EmptySpace pref="28" max="32767" attributes="0"/>
              </Group>
          </Group>
        </DimensionLayout>
        <DimensionLayout dim="1">
          <Group type="103" groupAlignment="0" attributes="0">
              <Group type="102" alignment="0" attributes="0">
                  <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="booknameTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="authorTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="saveBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="resetBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace max="32767" attributes="0"/>
              </Group>
          </Group>
        </DimensionLayout>
      </Layout>
      <SubComponents>
        <Component class="javax.swing.JLabel" name="jLabel1">
          <Properties>
            <Property name="text" type="java.lang.String" value="TEN SACH:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="booknameTxt">
        </Component>
        <Component class="javax.swing.JTextField" name="authorTxt">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel2">
          <Properties>
            <Property name="text" type="java.lang.String" value="TAC GIA:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JButton" name="saveBtn">
          <Properties>
            <Property name="text" type="java.lang.String" value="SAVE"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="saveBtnActionPerformed"/>
          </Events>
        </Component>
        <Component class="javax.swing.JButton" name="resetBtn">
          <Properties>
            <Property name="text" type="java.lang.String" value="RESET"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="resetBtnActionPerformed"/>
          </Events>
        </Component>
      </SubComponents>
    </Container>
    <Container class="javax.swing.JScrollPane" name="jScrollPane1">
      <AuxValues>
        <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
      </AuxValues>

      <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
      <SubComponents>
        <Component class="javax.swing.JTable" name="bookTable">
          <Properties>
            <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
              <Table columnCount="3" rowCount="0">
                <Column editable="false" title="STT" type="java.lang.Object"/>
                <Column editable="false" title="TEN SACH" type="java.lang.Object"/>
                <Column editable="false" title="TAC GIA" type="java.lang.Object"/>
              </Table>
            </Property>
            <Property name="columnModel" type="javax.swing.table.TableColumnModel" editor="org.netbeans.modules.form.editors2.TableColumnModelEditor">
              <TableColumnModel selectionModel="0">
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
              </TableColumnModel>
            </Property>
            <Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor">
              <TableHeader reorderingAllowed="true" resizingAllowed="true"/>
            </Property>
          </Properties>
        </Component>
      </SubComponents>
    </Container>
  </SubComponents>
</Form>


Tags:

Liên kết rút gọn:

https://gokisoft.com/2341

Bình luận