怎么做JTextArea
滚动以始终显示插入符号位置?
这对我来说似乎是一个愚蠢的问题,我觉得以前一定有人问过这个问题,但我已经搜索过,但找不到答案。
我有一个多行文本区域,嵌入在JScrollPane
. 如果用户一直打字直到填满文本区域,最终插入符号将变为不可见(在所示区域下方)并且用户无法看到他正在输入的内容。这似乎是默认行为,这似乎很奇怪。我需要做些什么来确保文本区域始终滚动到插入符号所在的行。
我应该提到在文本区域中启用了换行。
怎么做JTextArea
滚动以始终显示插入符号位置?
这对我来说似乎是一个愚蠢的问题,我觉得以前一定有人问过这个问题,但我已经搜索过,但找不到答案。
我有一个多行文本区域,嵌入在JScrollPane
. 如果用户一直打字直到填满文本区域,最终插入符号将变为不可见(在所示区域下方)并且用户无法看到他正在输入的内容。这似乎是默认行为,这似乎很奇怪。我需要做些什么来确保文本区域始终滚动到插入符号所在的行。
我应该提到在文本区域中启用了换行。
在我看来,setXxXSize()
方法应与有限数量的组件一起使用,并牢记Layout
后面使用的方法,具体取决于Layout Manager
程序员提供的大小提示。
因此,对于像和足够的组件来说JTextArea
,它不应该与硬编码的大小相关联,尽可能使用一些方法来计算其大小。Rows
Columns
Layout
setXxXSize()
在这里,我提供了相同的示例代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.EventHandler;
import javax.swing.*;
public class DialogWithScroller
{
private JFrame frame;
private JButton showButton;
private MyDialog myDialog;
private void displayGUI()
{
frame = new JFrame("Dialog ScrollPane Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
showButton = new JButton("Show Dialog");
showButton.addActionListener((ActionListener)
EventHandler.create(ActionListener.class,
DialogWithScroller.this, "buttonActions", ""));
contentPane.add(showButton);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void buttonActions(ActionEvent ae)
{
myDialog = new MyDialog(frame
, "TextArea with ScrollPane", true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
new DialogWithScroller().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class MyDialog extends JDialog
{
private JTextArea tArea;
private JButton hideButton;
private ActionListener buttonActions =
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
MyDialog.this.dispose();
}
};
public MyDialog()
{}
public MyDialog(Frame owner, String title, boolean modal)
{
super(owner, title, modal);
displayGUI();
}
private void displayGUI()
{
JPanel contentPane = new JPanel(
new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createTitledBorder(
"My Personal Text Area"));
/*
* Here one can simply initialize the
* JTextArea like this too, using the
* constructor itself for specifying
* the Rows and Columns, which will
* help the layout concern to determine
* its size
*/
tArea = new JTextArea(20, 20);
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true);
JScrollPane textScroller = new JScrollPane(tArea);
//textScroller.setViewportView(tArea);
hideButton = new JButton("Hide Dialog");
hideButton.addActionListener(buttonActions);
contentPane.add(textScroller, BorderLayout.CENTER);
contentPane.add(hideButton, BorderLayout.PAGE_END);
setContentPane(contentPane);
pack();
setLocationByPlatform(true);
setVisible(true);
}
}
在容器上调用Window.pack()始终被认为是一种明智的做法,这会导致此 Window 的大小适合其子组件的首选大小和布局。尽管像这样的调用,必须在程序员完成将所有组件添加到容器之后并且在将容器设置为可见状态之前进行。