写了个小程序,就一个类,代码如下:
现在遇到个很困惑的问题,查找到要高亮显示的词后,清空jpane,再次输入的时候有时候会改变style,全部成了需要高亮显示的style。该如何解决?如何重置style?急等! 谢谢!!!!!!public class TextCheckerV1 extends JFrame implements MouseListener {
private JMenuBar bar = null;
private JMenu clearMenu = null;
private JMenu exitMenu = null;
private JMenu checkMenu = null;
private JMenu fileMenu = null;
private String strText = null;
private JTextPane pane = null;
private DefaultStyledDocument doc = null;
private StyleContext sc = null; private Style defaultStyle = null;
private Style frankStyle = null; List <String > chars = null; public TextCheckerV1() {
this.sc = new StyleContext();
this.doc = new DefaultStyledDocument(sc);
this.pane = new JTextPane(doc); defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);
frankStyle = sc.addStyle( "FrankStyle ", defaultStyle);
StyleConstants.setForeground(frankStyle, Color.red);
StyleConstants.setBackground(frankStyle, Color.yellow);
StyleConstants.setLeftIndent(frankStyle, 8);
StyleConstants.setRightIndent(frankStyle, 8);
StyleConstants.setFirstLineIndent(frankStyle, 8);
StyleConstants.setFontFamily(frankStyle, "Arial ");
StyleConstants.setFontSize(frankStyle, 12); bar = new JMenuBar();
this.setJMenuBar(bar); fileMenu = new JMenu( "About ");
fileMenu.setMnemonic( 'A '); checkMenu = new JMenu( "Check ");
checkMenu.setMnemonic( 'C '); clearMenu = new JMenu( "Clear ");
clearMenu.setMnemonic( 'R '); exitMenu = new JMenu( "Exit ");
exitMenu.setMnemonic( 'E '); fileMenu.addMouseListener(this);
checkMenu.addMouseListener(this);
clearMenu.addMouseListener(this);
exitMenu.addMouseListener(this); bar.add(fileMenu);
bar.add(checkMenu);
bar.add(clearMenu);
bar.add(exitMenu); this.getContentPane().add(new JScrollPane(pane));
this.setSize(600, 500);
this.setTitle( "Text Checker (ver 1.0) ");
this.setLocation(200, 300);
this.setVisible(true);
} public void mouseClicked(MouseEvent e) {
if (e.getSource() == exitMenu) {
exitSys();
} else if (e.getSource() == clearMenu) {
clearText(this.pane, this.doc);
} else if (e.getSource() == checkMenu) {
checkText(this.pane);
} else if (e.getSource() == fileMenu) {
showFile();
}
} public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub } public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub } public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub } public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub } public void exitSys() {
dispose();
System.exit(0);
} public void showFile() {
JOptionPane.showMessageDialog(this,
"version 1.0\nauthor: franksinger ",
"test ", 1);
} public void clearText(JTextPane jpane, DefaultStyledDocument ddoc) {
if (jpane.getText() != null && (!jpane.getText().equals( " "))) {
jpane.setText( " ");
} jpane.setEditable(true);
jpane.requestFocus();
} public void checkText(JTextPane jpane) {
if (jpane.getText() == null ¦ ¦ jpane.getText().equals( " ")) {
return;
} else {
strText = getText(pane.getText()); if (jpane.getText() != null && (!jpane.getText().equals( " "))) {
try {
chars = getCharArray(); for (int n = 0; n < chars.size(); n++) {
int charLen = chars.get(n).length();
for (int j = 0; j < strText.length() - (charLen - 1); j++) {
String ch = strText.substring(j, j + charLen); if (chars.get(n).compareTo(ch) == 0) {
try {
doc.setCharacterAttributes(j, charLen,
frankStyle, false);
} catch (Exception ble) { // BadLocationException
System.out
.println( "Exception happens while highlighting! ");
ble.printStackTrace();
}
}
}
}
} catch (Exception e) { // BadLocationException
// System.out.println( "Exception happens while
// highlighting! ");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
jpane.setEditable(false);
}
} public List <String > getCharArray() {
ArrayList <String > charArray = new ArrayList <String >();
charArray.add( "color ");
charArray.add( "labor ");
charArray.add( "maximize ");
charArray.add( "minimize ");
charArray.add( "prioritize ");
charArray.add( "specialized ");
charArray.add( "customize ");
charArray.add( "theater ");
charArray.add( "analyzes ");
charArray.add( "optimize ");
charArray.add( "favor ");
charArray.add( "zation ");
charArray.add( "utilize ");
charArray.add( "center ");
charArray.add( "program ");
charArray.add( "organize ");
return charArray;
} public String getText(String str) {
String strNew = str.replaceAll( "[\n] ", " ").toLowerCase();
return strNew;
} public static void main(String[] args) {
TextCheckerV1 myTest = new TextCheckerV1();
}
}
现在遇到个很困惑的问题,查找到要高亮显示的词后,清空jpane,再次输入的时候有时候会改变style,全部成了需要高亮显示的style。该如何解决?如何重置style?急等! 谢谢!!!!!!public class TextCheckerV1 extends JFrame implements MouseListener {
private JMenuBar bar = null;
private JMenu clearMenu = null;
private JMenu exitMenu = null;
private JMenu checkMenu = null;
private JMenu fileMenu = null;
private String strText = null;
private JTextPane pane = null;
private DefaultStyledDocument doc = null;
private StyleContext sc = null; private Style defaultStyle = null;
private Style frankStyle = null; List <String > chars = null; public TextCheckerV1() {
this.sc = new StyleContext();
this.doc = new DefaultStyledDocument(sc);
this.pane = new JTextPane(doc); defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);
frankStyle = sc.addStyle( "FrankStyle ", defaultStyle);
StyleConstants.setForeground(frankStyle, Color.red);
StyleConstants.setBackground(frankStyle, Color.yellow);
StyleConstants.setLeftIndent(frankStyle, 8);
StyleConstants.setRightIndent(frankStyle, 8);
StyleConstants.setFirstLineIndent(frankStyle, 8);
StyleConstants.setFontFamily(frankStyle, "Arial ");
StyleConstants.setFontSize(frankStyle, 12); bar = new JMenuBar();
this.setJMenuBar(bar); fileMenu = new JMenu( "About ");
fileMenu.setMnemonic( 'A '); checkMenu = new JMenu( "Check ");
checkMenu.setMnemonic( 'C '); clearMenu = new JMenu( "Clear ");
clearMenu.setMnemonic( 'R '); exitMenu = new JMenu( "Exit ");
exitMenu.setMnemonic( 'E '); fileMenu.addMouseListener(this);
checkMenu.addMouseListener(this);
clearMenu.addMouseListener(this);
exitMenu.addMouseListener(this); bar.add(fileMenu);
bar.add(checkMenu);
bar.add(clearMenu);
bar.add(exitMenu); this.getContentPane().add(new JScrollPane(pane));
this.setSize(600, 500);
this.setTitle( "Text Checker (ver 1.0) ");
this.setLocation(200, 300);
this.setVisible(true);
} public void mouseClicked(MouseEvent e) {
if (e.getSource() == exitMenu) {
exitSys();
} else if (e.getSource() == clearMenu) {
clearText(this.pane, this.doc);
} else if (e.getSource() == checkMenu) {
checkText(this.pane);
} else if (e.getSource() == fileMenu) {
showFile();
}
} public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub } public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub } public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub } public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub } public void exitSys() {
dispose();
System.exit(0);
} public void showFile() {
JOptionPane.showMessageDialog(this,
"version 1.0\nauthor: franksinger ",
"test ", 1);
} public void clearText(JTextPane jpane, DefaultStyledDocument ddoc) {
if (jpane.getText() != null && (!jpane.getText().equals( " "))) {
jpane.setText( " ");
} jpane.setEditable(true);
jpane.requestFocus();
} public void checkText(JTextPane jpane) {
if (jpane.getText() == null ¦ ¦ jpane.getText().equals( " ")) {
return;
} else {
strText = getText(pane.getText()); if (jpane.getText() != null && (!jpane.getText().equals( " "))) {
try {
chars = getCharArray(); for (int n = 0; n < chars.size(); n++) {
int charLen = chars.get(n).length();
for (int j = 0; j < strText.length() - (charLen - 1); j++) {
String ch = strText.substring(j, j + charLen); if (chars.get(n).compareTo(ch) == 0) {
try {
doc.setCharacterAttributes(j, charLen,
frankStyle, false);
} catch (Exception ble) { // BadLocationException
System.out
.println( "Exception happens while highlighting! ");
ble.printStackTrace();
}
}
}
}
} catch (Exception e) { // BadLocationException
// System.out.println( "Exception happens while
// highlighting! ");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
jpane.setEditable(false);
}
} public List <String > getCharArray() {
ArrayList <String > charArray = new ArrayList <String >();
charArray.add( "color ");
charArray.add( "labor ");
charArray.add( "maximize ");
charArray.add( "minimize ");
charArray.add( "prioritize ");
charArray.add( "specialized ");
charArray.add( "customize ");
charArray.add( "theater ");
charArray.add( "analyzes ");
charArray.add( "optimize ");
charArray.add( "favor ");
charArray.add( "zation ");
charArray.add( "utilize ");
charArray.add( "center ");
charArray.add( "program ");
charArray.add( "organize ");
return charArray;
} public String getText(String str) {
String strNew = str.replaceAll( "[\n] ", " ").toLowerCase();
return strNew;
} public static void main(String[] args) {
TextCheckerV1 myTest = new TextCheckerV1();
}
}
帮你解决一切问题
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.GroupLayout;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;public class TextFieldDemo extends JFrame implements DocumentListener { private JTextField entry;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
private JLabel status;
private JTextArea textArea; final static Color HILIT_COLOR = Color.RED/*Color.LIGHT_GRAY*/;
final static Color ERROR_COLOR = Color.PINK;
final static String CANCEL_ACTION = "cancel-search"; final Color entryBg;
final Highlighter hilit;
final Highlighter.HighlightPainter painter; public TextFieldDemo() {
initComponents(); InputStream in = getClass().getResourceAsStream("content.txt");
try {
textArea.read(new InputStreamReader(in), null);
} catch (IOException e) {
e.printStackTrace();
} hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
textArea.setHighlighter(hilit); entryBg = entry.getBackground();
entry.getDocument().addDocumentListener(this); InputMap im = entry.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = entry.getActionMap();
im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION);
am.put(CANCEL_ACTION, new CancelAction());
} /**
* This method is called from within the constructor to initialize the form.
*/ private void initComponents() {
entry = new JTextField();
textArea = new JTextArea();
status = new JLabel();
jLabel1 = new JLabel(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("TextFieldDemo"); textArea.setColumns(20);
textArea.setLineWrap(true);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
jScrollPane1 = new JScrollPane(textArea); jLabel1.setText("Enter text to search:"); GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout); // Create a parallel group for the horizontal axis
ParallelGroup hGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING); // Create a sequential and a parallel groups
SequentialGroup h1 = layout.createSequentialGroup();
ParallelGroup h2 = layout.createParallelGroup(GroupLayout.Alignment.TRAILING); // Add a container gap to the sequential group h1
h1.addContainerGap(); // Add a scroll pane and a label to the parallel group h2
h2.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
h2.addComponent(status, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE); // Create a sequential group h3
SequentialGroup h3 = layout.createSequentialGroup();
h3.addComponent(jLabel1);
h3.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED);
h3.addComponent(entry, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE); // Add the group h3 to the group h2
h2.addGroup(h3);
// Add the group h2 to the group h1
h1.addGroup(h2); h1.addContainerGap(); // Add the group h1 to the hGroup
hGroup.addGroup(GroupLayout.Alignment.TRAILING, h1);
// Create the horizontal group
layout.setHorizontalGroup(hGroup); // Create a parallel group for the vertical axis
ParallelGroup vGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
// Create a sequential group v1
SequentialGroup v1 = layout.createSequentialGroup();
// Add a container gap to the sequential group v1
v1.addContainerGap();
// Create a parallel group v2
ParallelGroup v2 = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
v2.addComponent(jLabel1);
v2.addComponent(entry, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE);
// Add the group v2 tp the group v1
v1.addGroup(v2);
v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
v1.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE);
v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
v1.addComponent(status);
v1.addContainerGap(); // Add the group v1 to the group vGroup
vGroup.addGroup(v1);
// Create the vertical group
layout.setVerticalGroup(vGroup);
pack();
} public void search() {
hilit.removeAllHighlights(); String s = entry.getText();
if (s.length() <= 0) {
message("Nothing to search");
return;
} String content = textArea.getText();
int index = content.indexOf(s, 0);
if (index >= 0) { // match found
try {
int end = index + s.length();
hilit.addHighlight(index, end, painter);
textArea.setCaretPosition(end);
entry.setBackground(entryBg);
message("'" + s + "' found. Press ESC to end search");
} catch (BadLocationException e) {
e.printStackTrace();
}
} else {
entry.setBackground(ERROR_COLOR);
message("'" + s + "' not found. Press ESC to start a new search");
}
} void message(String msg) {
status.setText(msg);
} // DocumentListener methods public void insertUpdate(DocumentEvent ev) {
search();
} public void removeUpdate(DocumentEvent ev) {
search();
} public void changedUpdate(DocumentEvent ev) {
} class CancelAction extends AbstractAction {
public void actionPerformed(ActionEvent ev) {
hilit.removeAllHighlights();
entry.setText("");
entry.setBackground(entryBg);
}
} public static void main(String args[]) {
// Schedule a job for the event dispatch thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
new TextFieldDemo().setVisible(true);
}
});
}}
看看我这个例子,有关高亮显示问题的,也许能帮助你解决问题。