Java如何在JTextArea中选择所有文本?
JTextArea可以使用selectAll()方法选择组件中的所有文本。在下面的示例中,我们使用按钮动作来进行选择。选择文本后,我们将焦点移回到,JTextArea以便显示突出显示的文本。
package org.nhooo.example.swing;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextAreaSelectAll extends JPanel {
public TextAreaSelectAll() {
initializeUI();
}
private void initializeUI() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 200));
final JTextArea textArea = new JTextArea(
"The quick brown fox jumps over the lazy dog.");
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane pane = new JScrollPane(textArea);
pane.setPreferredSize(new Dimension(500, 200));
pane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
final JButton button1 = new JButton("Select All");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.selectAll();
// 将焦点转移到JTextArea以显示所选内容
// 文本。
button1.transferFocusBackward();
}
});
final JButton button2 = new JButton("Get Selected Text");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = textArea.getSelectedText();
System.out.println("Text = " + text);
}
});
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(button1);
buttonPanel.add(button2);
this.add(pane, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public static void showFrame() {
JPanel panel = new TextAreaSelectAll();
panel.setOpaque(true);
JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TextAreaSelectAll.showFrame();
}
});
}
}
这是上面代码片段的屏幕截图:
以上是 Java如何在JTextArea中选择所有文本? 的全部内容, 来源链接: utcz.com/z/343192.html