繁体   English   中英

Java GUI 和操作

[英]Java GUI and actions

我有个问题。

我已经退出游戏一段时间了,并为朋友提供了一个副项目。 他让我创建一个带有搜索栏、按钮和标签的 GUI。

他曾问我,当用户输入内容并按 Enter 键时,结果必须显示在下表中。

所以我启动了 Netbeans 并开始使用拖放支持开始创建 GUI。

然后我被卡住了。 我需要帮助的是弄清楚如何将它们联系在一起。

这是我到目前为止:

package video.store;

import javax.swing.*;
import java.sql.*;

public class NewJFrame extends javax.swing.JFrame{

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        super("Films & Series");
        setSize(300, 120);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        lbMovie = new JLabel("Enter movie name: ");
        txField = new JTextField();
        bSearch = new JButton("Search");
        tblList = new JTable();
        setVisible(true);
        initComponents();
    }

    /**
     * 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">                          
    private void initComponents() {

        lbMovie = new javax.swing.JLabel();
        txField = new javax.swing.JTextField();
        bSearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblList = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbMovie.setText("Enter Move Name: ");

        txField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txFieldActionPerformed(evt);
            }
        });

        bSearch.setText("Search");
        bSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSearchActionPerformed(evt);
            }
        });

        tblList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblList);

        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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbMovie)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txField, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbMovie)
                    .addComponent(txField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bSearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void txFieldActionPerformed(java.awt.event.ActionEvent evt) {                                        

    }                                       

    private void bSearchActionPerformed(java.awt.event.ActionEvent evt) {                                        

    }                                       

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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() {
                try {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=master;user=Brandon;password=Brandon1");
                    System.out.println("Connection successful");
                } catch (SQLException sqle) {
                    System.out.println("SQL Exception" + sqle);
                } catch (ClassNotFoundException e) {
                    System.out.println("Error" + e);
                }
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton bSearch;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbMovie;
    private javax.swing.JTable tblList;
    private javax.swing.JTextField txField;
    // End of variables declaration                   
}

请帮忙。

听起来您需要在文本字段中附加一个密钥侦听器

KeyListener keyListener = new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {
          printIt("Pressed", keyEvent);
      }

      public void keyReleased(KeyEvent keyEvent) {
          printIt("Released", keyEvent);
      }

     public void keyTyped(KeyEvent keyEvent) {
          printIt("Typed", keyEvent);
     }

     private void printIt(String title, KeyEvent keyEvent) {
         int keyCode = keyEvent.getKeyCode();
         String keyText = KeyEvent.getKeyText(keyCode);
         System.out.println(title + " : " + keyText + " / " + 
             keyEvent.getKeyChar());
     }
};
txField.addKeyListener(keyListener);

您还可以使用更改侦听器来检测文本字段中文本的更改

同样只是让您知道,JavaFX 是 Swing 的替代品。 不再支持 Swing,但它应该仍然可以正常工作。 供参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM