最簡單的方法是創建一個小的搜索JPanel
,其定位文本JPanel
以上。兩個JPanel
s將在另一個JPanel
之內。我會使用JTextField
和JButton
,因爲我喜歡用戶控制何時搜索。
下面是我的一個GUI搜索JPanel
。
下面是創建搜索JPanel
的代碼。請注意,我使用了JPanel
。當您想覆蓋某個組件方法時,只能擴展Swing組件。
package gov.bop.cobol.paragraph.structure.view;
import gov.bop.cobol.paragraph.structure.model.ParagraphStructureModel;
import gov.bop.cobol.paragraph.structure.thread.SearchActionThread;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SearchPanel {
protected JPanel panel;
protected JTextField findTextField;
protected ParagraphStructureFrame frame;
protected ParagraphStructureModel model;
public SearchPanel(ParagraphStructureFrame frame,
ParagraphStructureModel model) {
this.frame = frame;
this.model = model;
createPartControl();
}
protected void createPartControl() {
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
JLabel findLabel = new JLabel("Search:");
panel.add(findLabel);
panel.add(Box.createRigidArea(new Dimension(6, 0)));
findTextField = new JTextField(30);
panel.add(findTextField);
panel.add(Box.createRigidArea(new Dimension(6, 0)));
JButton findButton = new JButton("Search");
findButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String s = findTextField.getText().toUpperCase().trim();
if (!s.equals("")) {
findTextField.setText(s);
Thread thread = new Thread(new SearchActionThread(frame,
model, s));
thread.start();
}
}
});
panel.add(findButton);
}
public JPanel getPanel() {
return panel;
}
}