我的文本文件包含以下內容:選中第一行中的JTextPane
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
我想強調的第一行public class MyC{
紅當我加載在JTextPane
文本文件。有人可以指導我嗎?我試着看着http://docs.oracle.com/javase/7/docs/api/javax/swing/text/Highlighter.html,但它正在使用職位。我不知道該怎麼做。
這是我到目前爲止有:
public class ReadDemo {
// read the file into the pane
static void readin(String fn, JTextComponent pane) {
try {
FileReader fr = new FileReader(fn);
pane.read(fr, null);
fr.close();
}
catch (IOException e) {
System.err.println(e);
}
}
public static void main(String args[]) {
final JFrame frame = new JFrame("Testing");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// set up the text pane, either a JTextArea or JTextPane
final JTextComponent textpane = new JTextArea();
//final JTextComponent textpane = new JTextPane();
// set up a scroll pane for the text pane
final JScrollPane pane = new JScrollPane(textpane);
pane.setPreferredSize(new Dimension(600, 600));
// set up the file chooser
String cwd = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(cwd);
final JLabel elapsed = new JLabel("Elapsed time: ");
JButton filebutton = new JButton("Choose File");
filebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jfc.showOpenDialog(frame) !=
JFileChooser.APPROVE_OPTION)
return;
File f = jfc.getSelectedFile();
// record the current time and read the file
final long s_time = System.currentTimeMillis();
frame.setCursor(Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR));
readin(f.toString(), textpane);
// wait for read to complete and update time
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setCursor(Cursor.
getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
long t = System.currentTimeMillis() -
s_time;
elapsed.setText("Elapsed time: " + t);
}
});
}
});
JPanel buttonpanel = new JPanel();
buttonpanel.add(filebutton);
buttonpanel.add(elapsed);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add("North", buttonpanel);
panel.add("East", pane);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
[例如]( http://stackoverflow.com/a/9022901/714968) – mKorbel
是的是這樣的,但我怎麼能突出顯示行1,2,3當我加載窗格中的文件。 – Deathstar
這正是在代碼中,從File的一個新行是字體改變,依賴於,回答一個從File說起的行,從視圖回答關於行的第二個talkind,不要忘記up_vote(都是???)正確的答案並接受,這兩個都是正確的,由你決定 – mKorbel