无需按Enter键即可收听Jtext字段

时间:2015-08-19 12:18:51

标签: java sql swing ms-access-2007

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.Document;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


@SuppressWarnings("serial")
public class Save extends JPanel {

Connection con;
Statement st;
ResultSet rs;

String TrailerName;
String BlockName;
String LocationName;
String newline = "\n";
String text;

JComboBox<?> TrailerList;
JComboBox<?> BlockList;
JComboBox<?> LocationList;
JTextField textField;
JTextArea textArea;

public Save() {
     super(new BorderLayout());

     textField = new JTextField(20);

     textArea = new JTextArea(5, 20);
     textArea.setEditable(false);
     textField.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
                  text = textField.getText();
                  textArea.append(text + newline);
                  textField.selectAll();

                  textArea.setCaretPosition(textArea.getDocument().getLength());
                  System.out.println("Comment: " + text);
                 }
              });

    String[] Trailer = { "A1", "A2", "B1", "B2", "C1", "Please select a Trailer" };
    String[] Block = { "A", "B", "C", "D", "E", "Please select a Block" };
    String[] Location = { "Door A3", "Door B2", "Door C4", "Door D2", "Door E9", "Please select a Location" };

    TrailerList = new JComboBox<Object>(Trailer);
    TrailerList.setSelectedIndex(5);
    TrailerList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
                 TrailerName = (String) TrailerList.getSelectedItem();
                 System.out.println("Trailer: " + TrailerName);
        }
    });

    BlockList = new JComboBox<Object>(Block);
    BlockList.setSelectedIndex(5);
    BlockList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
                   BlockName = (String) BlockList.getSelectedItem();
                   System.out.println("Block: " + BlockName);
   }

});

    LocationList = new JComboBox<Object>(Location);
    LocationList.setSelectedIndex(5);
    LocationList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
                   LocationName = (String) LocationList.getSelectedItem();
                   System.out.println("Location: " + LocationName);
   }

});

    JButton buttonSave = new JButton("Save");
    add(buttonSave);
    buttonSave.setActionCommand("Save");
    add(buttonSave);
    buttonSave.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
             String action = evt.getActionCommand();
                if (action.equals("Save")) {
                    System.out.println("Button pressed!");
                    try {
                        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
                        Class.forName(driver);
                        String db = "jdbc:odbc:TTracking";
                    con = DriverManager.getConnection(db);

                    DatabaseMetaData meta = con.getMetaData();
                    System.out.println("Server name: " +
           meta.getDatabaseProductName());
                    System.out.println("Server version: " +
           meta.getDatabaseProductVersion());
                    System.out.println("");

                    System.out.println("Inserting records into the table...");

                    PreparedStatement st = con.prepareStatement(
                        "INSERT INTO TrailerLocation (Trailer, Block, Location, Day, SetTime, Comment) " +
                        "VALUES (?, ?, ?, NOW(), NOW(), ?)");

                        st.setString(1, TrailerName);
                        st.setString(2, BlockName);
                        st.setString(3, LocationName);
                        st.setString(4, text);
                        st.addBatch();

                        st.executeBatch();

                        JOptionPane.showMessageDialog(null,"Inserted record into the table: "
                                + "\nTrailer : " + TrailerName
                                + "\nBlock : " + BlockName
                                + "\nLocation : " + LocationName
                                + "\nComment : " + text);

                       }catch(SQLException se){
                      //Handle errors for JDBC
                      se.printStackTrace();
                       }catch(Exception e1){
                      //Handle errors for Class.forName
                      e1.printStackTrace();
                      }finally{
                      //finally block used to close resources
                      try{
                            if(st!=null)
                            con.close();
                      }catch(SQLException se){
                      }// do nothing
                         try{
                         if(con!=null)
                         con.close();
                         }catch(SQLException se){
                         se.printStackTrace();
                         }//end finally try
                    }//end try
                         System.out.println("Goodbye!");
                   }}
                 });

    add(TrailerList, BorderLayout.WEST);
    add(BlockList, BorderLayout.CENTER);
    add(LocationList, BorderLayout.EAST);
    add(buttonSave,BorderLayout.SOUTH);
    add(textField, BorderLayout.NORTH);
    setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}

private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Save");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setUndecorated(true);


    //Create and set up the content pane.
    JComponent newContentPane = new Save();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
            }
        });
    }
}
  1. 对于我正在创建的表单,我有一个文本字段供人们添加注释但问题是注释保存您需要按Enter按钮有没有办法在不按Enter按钮的情况下执行此操作

  2. 尝试了Doc-listener和Action侦听器但无法获取代码

1 个答案:

答案 0 :(得分:0)

简单的解决方案是,删除变量“text”的用法并直接使用textField.getText(),但要更新文本区域,仍然需要使用DocumentListener。

例如:

st.setString(4, textField.getText());

但在设计方面,这应该有所改进,我的建议是使用Model来维护GUI数据状态, 您可以使用beansbinding将GUI组件与模型同步。 一旦用户点击了保存按钮,那么该模型应该被提交给其他一些类来处理保存功能。