用JAVA编写一段哈希表数据结构GUI代码
时间: 2024-05-13 09:16:46 浏览: 96
实现数据结构的哈希表
以下是一个简单的哈希表数据结构的GUI代码,使用Java Swing库:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HashTableGUI extends JFrame implements ActionListener {
private JTextField keyField, valueField;
private JButton insertButton, removeButton, searchButton;
private JTextArea outputArea;
private HashTable<String, String> hashTable;
public HashTableGUI() {
super("Hash Table GUI");
hashTable = new HashTable<String, String>(10);
JPanel inputPanel = new JPanel(new GridLayout(2, 2));
inputPanel.add(new JLabel("Key:"));
keyField = new JTextField();
inputPanel.add(keyField);
inputPanel.add(new JLabel("Value:"));
valueField = new JTextField();
inputPanel.add(valueField);
insertButton = new JButton("Insert");
insertButton.addActionListener(this);
removeButton = new JButton("Remove");
removeButton.addActionListener(this);
searchButton = new JButton("Search");
searchButton.addActionListener(this);
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
buttonPanel.add(insertButton);
buttonPanel.add(removeButton);
buttonPanel.add(searchButton);
outputArea = new JTextArea(15, 40);
outputArea.setEditable(false);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.CENTER);
mainPanel.add(outputArea, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(mainPanel);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == insertButton) {
String key = keyField.getText();
String value = valueField.getText();
hashTable.insert(key, value);
outputArea.append("Inserted: (" + key + ", " + value + ")\n");
keyField.setText("");
valueField.setText("");
} else if (e.getSource() == removeButton) {
String key = keyField.getText();
String value = hashTable.remove(key);
if (value != null) {
outputArea.append("Removed: (" + key + ", " + value + ")\n");
} else {
outputArea.append("Key not found: " + key + "\n");
}
keyField.setText("");
valueField.setText("");
} else if (e.getSource() == searchButton) {
String key = keyField.getText();
String value = hashTable.search(key);
if (value != null) {
outputArea.append("Found: (" + key + ", " + value + ")\n");
} else {
outputArea.append("Key not found: " + key + "\n");
}
keyField.setText("");
valueField.setText("");
}
}
public static void main(String[] args) {
new HashTableGUI();
}
}
```
此代码使用了 `HashTable` 类,该类实现了哈希表数据结构。GUI界面包括一个输入面板用于输入键和值,一个按钮面板用于插入、删除和搜索操作,以及一个文本区域用于输出结果。每个按钮都注册了一个 `ActionListener`,以便在用户单击按钮时执行适当的操作。
阅读全文