同时在2个JTextarea中选择文本 [英] Select text in 2 JTextarea at the same time

查看:130
本文介绍了同时在2个JTextarea中选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个小型应用程序,比较2 JTextarea 中包含的两个类似的文本。我想知道是否可以从第一个 JTextarea 中选择文本,并自动选择第二个 JTeaxtarea 上的文本认为现在保证2 JTextarea 将具有相同的文本?
我应该分享事件还是听众?
谢谢

解决方案

如果 JTextComponent 支持选择模型...



基本上,您可以做的是将 ChangeListener 附加到 JTextArea 插入并监视对 Caret 的更改,更改其他 JTextArea 的选择作为回应...

  import java.awt.BorderLayout中; 
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;

public class MirrorTextSelection {

public static void main(String [] args){
new MirrorTextSelection();
}

public MirrorTextSelection(){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
尝试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex){
}

JFrame框架= new JFrame(Testing);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane扩展JPanel {

private JTextArea left;
private JTextArea right;

private DefaultHighlighter.DefaultHighlightPainter highlightPainter;

public TestPane(){

highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor(TextArea.selectionBackground));

left = new JTextArea(20,20);
left.setWrapStyleWord(true);
left.setLineWrap(true);
right = new JTextArea(20,20);
right.setWrapStyleWord(true);
right.setLineWrap(true);

left.setText(我试图做一个比较两个JTextarea中包含的两个类似文本的小应用程序,我想知道是否可以从第一个JTextarea中选择文本,并自动选择文本第二个JTeaxtarea(让我们考虑保证2 JTextarea现在有相同的文本)?我应该分享事件或听众吗?谢谢);
right.setText(我正在尝试一个比较两个JTextarea中包含的两个类似文本的小应用程序,我想知道是否可以从第一个JTextarea中选择文本,并自动选择第二个JTeaxtarea上的文本让我们考虑这是保证2 JTextarea现在有相同的文本)?我应该分享事件或听众吗?谢谢);

setLayout(new GridLayout(0,2));

add(new JScrollPane(left));
add(new JScrollPane(right));

left.getCaret()。addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
int dot = left.getCaret ).getDot();
int mark = left.getCaret()。getMark();

right.setCaretPosition(mark);
right.moveCaretPosition(dot);
}
});
}
}
}

现在,当你运行这个,你会发现右边似乎没有被突出显示...什么?!



选择正在改变,它只是没有被渲染,因为组件不没有焦点...



相反,您可以使用荧光笔突出显示文本...

  private DefaultHighlighter.DefaultHighlightPainter highlightPainter; 
// ...
highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor(TextArea.selectionBackground));

left.getCaret()。addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
int dot = left.getCaret ).getDot();
int mark = left.getCaret()。getMark();

right.getHighlighter()。removeAllHighlights();
try {
int start = Math.min(dot,mark);
int end = Math.max(dot,mark);
right.getHighlighter()。addHighlight(start,end,highlightPainter);
} catch(BadLocationException ex){
ex.printStackTrace();
}
}
});

好的,这是现在工作,你可以控制突出显示的背景颜色...

还有另一个选择...我们可以替换 right Caret c $ c> JTextArea 与焦点丢失时不会隐藏选择的...

  public class HighlightCaret extends DefaultCaret {

@Override
public void install(JTextComponent c){
super.install(c);
setSelectionVisible(true);
}

@Override
public void focusGained(FocusEvent e){
JTextComponent component = getComponent();
if(component.isEnabled()){
if(component.isEditable()){
setVisible(true);
}
setSelectionVisible(true);
}
}

@Override
public void focusLost(FocusEvent e){
setVisible(false);
}
}

然后我们设置 to right ...

  right .setCaret(nwe HighlightCaret()); 

这意味着我们不需要荧光笔代码,我们可以坚持原来的,我们不仅可以控制背景选择颜色,还可以控制前景选择颜色...


I am trying to do a small app that compares two similar texts contained in 2 JTextarea. I am wondering if it's possible to select text from the first JTextarea and automatically select the text on the second JTeaxtarea (lets consider that it's guarantee that the 2 JTextarea will have the same text for now) ? Should I share events or listeners ? Thank you

解决方案

This would be so much easier if JTextComponent supported a selection model...

Basically, what you can do is attach a ChangeListener to the JTextArea's Caret and monitor for changes to the Caret, changing the selection of the other JTextArea in response...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;

public class MirrorTextSelection {

    public static void main(String[] args) {
        new MirrorTextSelection();
    }

    public MirrorTextSelection() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextArea left;
        private JTextArea right;

        private DefaultHighlighter.DefaultHighlightPainter highlightPainter;

        public TestPane() {

            highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));

            left = new JTextArea(20, 20);
            left.setWrapStyleWord(true);
            left.setLineWrap(true);
            right = new JTextArea(20, 20);
            right.setWrapStyleWord(true);
            right.setLineWrap(true);

            left.setText("I am trying to do a small app that compares two similar texts contained in 2 JTextarea. I am wondering if it's possible to select text from the first JTextarea and automatically select the text on the second JTeaxtarea (lets consider that it's guarantee that the 2 JTextarea will have the same text for now) ? Should I share events or listeners ? Thank you");
            right.setText("I am trying to do a small app that compares two similar texts contained in 2 JTextarea. I am wondering if it's possible to select text from the first JTextarea and automatically select the text on the second JTeaxtarea (lets consider that it's guarantee that the 2 JTextarea will have the same text for now) ? Should I share events or listeners ? Thank you");

            setLayout(new GridLayout(0, 2));

            add(new JScrollPane(left));
            add(new JScrollPane(right));

            left.getCaret().addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    int dot = left.getCaret().getDot();
                    int mark = left.getCaret().getMark();

                    right.setCaretPosition(mark);
                    right.moveCaretPosition(dot);
                }
            });
        }
    }
}

Now, when you run this, you will find that the right side doesn't seem to get highlighted...what?!

The selection is changing, it's just not been rendered because the component doesn't have focus...

Instead, you could use a Highlighter to highlight the text...

private DefaultHighlighter.DefaultHighlightPainter highlightPainter;
//...
highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));

left.getCaret().addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        int dot = left.getCaret().getDot();
        int mark = left.getCaret().getMark();

        right.getHighlighter().removeAllHighlights();
        try {
            int start = Math.min(dot, mark);
            int end = Math.max(dot, mark);
            right.getHighlighter().addHighlight(start, end, highlightPainter);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }
});

Okay, this is now working and you can control the background color of the highlight...

There is another alternative...We can replace the Caret of the right JTextArea with one that doesn't hide the selection when focus is lost...

public class HighlightCaret extends DefaultCaret {

    @Override
    public void install(JTextComponent c) {
        super.install(c);
        setSelectionVisible(true);
    }

    @Override
    public void focusGained(FocusEvent e) {
        JTextComponent component = getComponent();
        if (component.isEnabled()) {
            if (component.isEditable()) {
                setVisible(true);
            }
            setSelectionVisible(true);
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        setVisible(false);
    }
}

Then we set the Caret to right...

right.setCaret(nwe HighlightCaret());

This means we don't need the Highlighter code, we can stick with the original and we get control over not only the background selection color but also the foreground selection color as well...

这篇关于同时在2个JTextarea中选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆