如何从各种文本字段中查找某个条件并从文本文件中显示匹配项?

时间:2016-05-28 17:23:13

标签: java swing user-interface

我应该从GUI制作库存程序。我的代码到目前为止可以打开文件。但是,我现在需要这样做,它只显示符合条件的文件。主要问题是文本文件以一种奇怪的方式排序,这是解码所必需的。

所以如果我要把:宝马放在制造领域,21123代表序列号,消声器代表名称,119.99代表价格,0代表股票。我应该在文本区域中获得前5行。

如何从各种文本字段中查找某个条件并从文本文件中显示匹配项?

BMW
Muffler
21123
119.99
0
Chevy
Muffler
20911
52.99
2
Ford
Muffler
26854
129.59
2
Honda
Muffler
23319
159.99
2
Toyota
Muffler
27813
199.29
1
BMW
Catalytic Converter
900122
132.33
2
Chevy
Catalytic Converter
902391
69.59
1
Ford
Catalytic Converter
905778
61.23
4

代码

package lib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Show extends javax.swing.JFrame {

/**
 * Creates new form Show
 */
public Show() {
    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() {

    FileName = new javax.swing.JTextField();
    name = new javax.swing.JTextField();
    serialNumber = new javax.swing.JTextField();
    price = new javax.swing.JTextField();
    onHand = new javax.swing.JTextField();
    make = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    display = new javax.swing.JTextArea();
    open = new javax.swing.JButton();
    save = new javax.swing.JButton();
    find = new javax.swing.JButton();
    Clear = new javax.swing.JButton();
    FileLabel = new javax.swing.JLabel();
    nameLabel = new javax.swing.JLabel();
    serialNumberLabel = new javax.swing.JLabel();
    PriceLabel = new javax.swing.JLabel();
    InstockLabel = new javax.swing.JLabel();
    makeLabel = new javax.swing.JLabel();
    Update = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

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

    display.setColumns(20);
    display.setRows(5);
    jScrollPane1.setViewportView(display);
    display.setEditable(false);

    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });

    save.setText("Save");

    find.setText("Find");
    find.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            findActionPerformed(evt);
        }
    });

    Clear.setText("Clear");
    Clear.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            ClearActionPerformed(evt);
        }
    });

    FileLabel.setText("File Name");

    nameLabel.setText("Name");

    serialNumberLabel.setText("serial Number");

    PriceLabel.setText("Price");

    InstockLabel.setText("In Stock:");

    makeLabel.setText("Make");

    Update.setText("Update");

    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)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(FileLabel)
                            .addGap(18, 18, 18)
                            .addComponent(FileName, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(nameLabel)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(serialNumberLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(PriceLabel))
                                .addComponent(InstockLabel)
                                .addComponent(makeLabel))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(serialNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(name)
                                .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(onHand, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(make, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGap(18, 18, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(open)
                    .addGap(18, 18, 18)
                    .addComponent(save)
                    .addGap(18, 18, 18)
                    .addComponent(find)
                    .addGap(18, 18, 18)
                    .addComponent(Clear)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(Update)
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {FileName, make, name, onHand, price, serialNumber});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(27, 27, 27)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(FileLabel)
                                .addComponent(FileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(nameLabel))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(serialNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(serialNumberLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(PriceLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(onHand, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(InstockLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(make, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(makeLabel))))
            .addGap(38, 38, 38)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(open)
                .addComponent(save)
                .addComponent(find)
                .addComponent(Clear)
                .addComponent(Update))
            .addContainerGap(57, Short.MAX_VALUE))
    );

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

private void FileNameActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

private void nameActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
}                                    

private void serialNumberActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
}                                            

private void ClearActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    FileName.setText("");
    name.setText("");
    serialNumber.setText("");
    price.setText("");
    onHand.setText("");
    make.setText("");
    display.setText("");
}                                     

private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
    try {
        File file = new File(FileName.getText());
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
                    int i=0;

                    while ((line = bufferedReader.readLine()) != null) {

                            stringBuffer.append(line+" ");
                            if(i==4){
                                stringBuffer.append("\n");
                                i =-1;
                            }
                            i++;

                    }
        fileReader.close();
        display.setText(display.getText() + stringBuffer.toString());
    } catch (IOException e) {
                display.setText("Error 101: File Not Found! ");
    }

}                                    

private void findActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:

}                                    

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

// Variables declaration - do not modify                     
private javax.swing.JButton Clear;
private javax.swing.JLabel FileLabel;
private javax.swing.JTextField FileName;
private javax.swing.JLabel InstockLabel;
private javax.swing.JLabel PriceLabel;
private javax.swing.JButton Update;
private javax.swing.JTextArea display;
private javax.swing.JButton find;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField make;
private javax.swing.JLabel makeLabel;
private javax.swing.JTextField name;
private javax.swing.JLabel nameLabel;
private javax.swing.JTextField onHand;
private javax.swing.JButton open;
private javax.swing.JTextField price;
private javax.swing.JButton save;
private javax.swing.JTextField serialNumber;
private javax.swing.JLabel serialNumberLabel;
// End of variables declaration                   
}

1 个答案:

答案 0 :(得分:1)

JTableRowSorter应该是一个很好的解决方案。

也许某些代码也很有用。

 public void search() {
  String s = tf.getText();
  String content = textArea.getText(); // instead from a file
  int index = content.indexOf(s, 0);
  if (index >= 0) {   
   try {
   int end = index + s.length();
   // do something
  }
 }