column Numbe-6ren">
gpt4 book ai didi

java - 在 JTextArea 中的特定位置插入字符串

转载 作者:行者123 更新时间:2023-11-30 04:40:55 24 4
gpt4 key购买 nike

Java中是否有任何函数可以在指定的JTextArea列号处插入字符串。

例如,

String str = "This is a sample text"

String => column Number

This => at 0

is => at 10

a => at 14

sample => at 20

text => at 25

最佳答案

请看一下这个示例,它使用 JTextComponent viewToModel() 方法。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextAreaExample extends JFrame
{
private JTextArea tarea = new JTextArea(10, 10);
private JTextField tfield = new JTextField(10);
private Object[] possibleValues = { "First", "Second", "Third" };

private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tarea.setText("Hello there\n");
tarea.append("Hello student://");
JScrollPane scroll = new JScrollPane(tarea);

tfield.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tarea.append(tfield.getText() + "\n");
}
});

tarea.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
int x = me.getX();
int y = me.getY();
System.out.println("X : " + x);
System.out.println("Y : " + y);
int startOffset = tarea.viewToModel(new Point(x, y));
System.out.println("Start Offset : " + startOffset);
String text = tarea.getText();
String firstPart = text.substring(0, startOffset);
String secondPart = text.substring(startOffset, text.length());

Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);

if (selectedValue != null)
{
String newText = firstPart + " "
+ (String) selectedValue
+ " "
+ secondPart;
tarea.setText(newText);
}
}
});

getContentPane().add(scroll, BorderLayout.CENTER);
getContentPane().add(tfield, BorderLayout.PAGE_END);
pack();
setLocationByPlatform(true);
setVisible(true);
}

public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaExample().createAndDisplayGUI();
}
});
}
}

关于java - 在 JTextArea 中的特定位置插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12331544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com