展开全部
/**
* 这个是最简单的实现 具体如何匹配 可以在actionListener里重写
* @author Jeky
*/
public class HighlightFrame extends JFrame {
private JButton searchButton;
private JTextArea area;
private JTextField key;
public HighlightFrame() {
key = new JTextField(20);
searchButton = new JButton("search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String keyword = key.getText();
int index = text.indexOf(keyword);
if (index != -1) {
try {
while (index != -1) {
area.getHighlighter().addHighlight(index, index + keyword.length(), DefaultHighlighter.DefaultPainter);
index = text.indexOf(keyword, index + keyword.length());
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(HighlightFrame.this, "Can't find keyword:" + keyword);
}
}
});
area = new JTextArea("This is a sample of highlighter.\n"
+ "You can enter a keyword and press search button.\n"
+ "Then the word will be highlighted in the text.\n"
+ "\n"
+ "For more information,\n"
+ "you can check javax.swing.text package.");
JPanel north = new JPanel();
north.add(key);
north.add(searchButton);
this.getContentPane().add(new JScrollPane(area));
this.getContentPane().add(north, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(350, 350);
this.setVisible(true);
}
public static void main(String[] args) {
new HighlightFrame();
}
}
* 这个是最简单的实现 具体如何匹配 可以在actionListener里重写
* @author Jeky
*/
public class HighlightFrame extends JFrame {
private JButton searchButton;
private JTextArea area;
private JTextField key;
public HighlightFrame() {
key = new JTextField(20);
searchButton = new JButton("search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String keyword = key.getText();
int index = text.indexOf(keyword);
if (index != -1) {
try {
while (index != -1) {
area.getHighlighter().addHighlight(index, index + keyword.length(), DefaultHighlighter.DefaultPainter);
index = text.indexOf(keyword, index + keyword.length());
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(HighlightFrame.this, "Can't find keyword:" + keyword);
}
}
});
area = new JTextArea("This is a sample of highlighter.\n"
+ "You can enter a keyword and press search button.\n"
+ "Then the word will be highlighted in the text.\n"
+ "\n"
+ "For more information,\n"
+ "you can check javax.swing.text package.");
JPanel north = new JPanel();
north.add(key);
north.add(searchButton);
this.getContentPane().add(new JScrollPane(area));
this.getContentPane().add(north, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(350, 350);
this.setVisible(true);
}
public static void main(String[] args) {
new HighlightFrame();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询