java 实现在文本域读取信息并据此在文件中遍历查询,同时显示在jtable表格中,若未查询到则弹出查询失败对话框代码实现
时间: 2024-03-23 16:36:16 浏览: 102
以下是一个简单的 Java 代码示例,实现了在文本域中读取信息并在文件中遍历查询,如果查询成功则将结果显示在 JTable 表格中,否则弹出查询失败对话框:
```java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
public class FileSearchDemo {
private JFrame frame;
private JTextArea textArea;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FileSearchDemo window = new FileSearchDemo();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FileSearchDemo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("Enter keyword:");
panel.add(lblNewLabel);
textArea = new JTextArea();
panel.add(textArea);
JButton btnNewButton = new JButton("Search");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
search();
}
});
panel.add(btnNewButton);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {},
new String[] {"File", "Line", "Text"}
));
scrollPane.setViewportView(table);
}
private void search() {
String keyword = textArea.getText();
List<String[]> results = new ArrayList<String[]>();
try {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.contains(keyword)) {
String[] result = new String[3];
result[0] = "data.txt";
result[1] = Integer.toString(lineNumber);
result[2] = line;
results.add(result);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (results.size() == 0) {
JOptionPane.showMessageDialog(frame, "No results found.");
} else {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
for (String[] result : results) {
model.addRow(result);
}
}
}
}
```
这个示例程序包括一个窗口,其中包含一个文本域、一个搜索按钮和一个 JTable 表格。当用户在文本域中输入关键字并点击搜索按钮时,程序会在文件 "data.txt" 中查找包含该关键字的行,并将结果显示在表格中。如果未找到任何结果,则会弹出查询失败对话框。
阅读全文