[英]How to switch between lines in JTextArea in swing
我正在尝试设置goto行号以在我的swing应用程序中的行之间切换。 我使用getLineCount()
获得了JTextArea
实例中的行数,但不知道如何getLineCount()
之间切换?
有人可以建议我吗?
您可以使用textArea.setCaretPosition
设置插入符位置。 这样的事情会起作用
textArea.setCaretPosition(textArea.getDocument().getDefaultRootElement()
.getElement(index).getStartOffset());
在下面的示例中,我只使用一个JComboBox
,并使用JTextArea
的行号填充索引。 当您在组合框中选择一个数字时,插入符号将移动到JTextArea
那一行。
该程序虽然不是一个很好的程序。 您可能希望通过添加和删除行来动态填充ComboBoxModel
。 但这应该为您提供所需的答案。
免责声明
我没有添加任何功能来使滚动窗格聚焦于当前行。 您可能需要查看下面的@Balder评论,以寻求帮助。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestCaret {
public TestCaret() {
JTextArea textArea = createTextArea();
JComboBox cBox = createComboBox(textArea);
JFrame frame = new JFrame();
frame.add(new JScrollPane(textArea));
frame.add(cBox, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JComboBox createComboBox(final JTextArea textArea) {
DefaultComboBoxModel<Integer> model = new DefaultComboBoxModel<>();
int lines = textArea.getLineCount();
for (int i = 0; i < lines; i++) {
model.addElement(i);
}
final JComboBox cBox = new JComboBox(model);
cBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int index = (Integer)cBox.getSelectedItem();
textArea.setCaretPosition(
textArea.getDocument().getDefaultRootElement().getElement(index).getStartOffset());
textArea.requestFocusInWindow();
}
});
return cBox;
}
private JTextArea createTextArea() {
JTextArea textArea = new JTextArea(10, 50);
textArea.setMargin(new Insets(15, 15, 15, 15));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
String text
= "0 Hello World\n" +
"1 Hello World\n" +
"2 Hello World\n" +
"3 Hello World\n" +
"4 Hello World\n" +
"5 Hello World\n" +
"6 Hello World\n" +
"7 Hello World\n" +
"8 Hello World\n" +
"9 Hello World\n";
textArea.setText(text);
return textArea;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestCaret();
}
});
}
}
一种方法是通过以下方式建立while语句:
String line = null;
while ((line = text.readLine())!=null && line.getLineNumber() < desiredNumber) {}
最后,行将引用具有所需行号的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.