Swing实现搜索框
时间: 2024-02-01 19:03:47 浏览: 27
要在Swing中实现搜索框,你可以使用JTextField和JButton。
首先,创建一个JTextField对象,用于用户输入搜索关键字。然后,创建一个JButton对象,用于触发搜索操作。在JButton的ActionListener中,你可以使用JTextField获取用户输入的关键字,并进行搜索操作。
下面是一个简单的Swing搜索框代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SearchBox extends JFrame implements ActionListener {
private JTextField searchField;
private JButton searchButton;
public SearchBox() {
setTitle("搜索框");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
searchField = new JTextField(20);
searchButton = new JButton("搜索");
searchButton.addActionListener(this);
add(searchField);
add(searchButton);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == searchButton) {
String keyword = searchField.getText();
// 进行搜索操作
System.out.println("搜索关键字:" + keyword);
}
}
public static void main(String[] args) {
new SearchBox();
}
}
```
在这个示例中,我们创建了一个JFrame窗口,并在窗口中添加了一个JTextField和一个JButton。当用户点击搜索按钮时,程序会获取JTextField中用户输入的关键字,并输出到控制台中。你可以根据自己的需要修改这个示例代码,以实现自己的搜索框。