50% Off/-

50% Off/-

Php

50% Off/-

50% Off/-

Web

50% Off/-

50% Off/-

Java JTextArea Üzerinde Sağ Tıklanıldığında İlgili Kelimeyi Bulmak

17-09-2014
JTextArea içeriği içerisinde bir kelimenin üstüne gelip sağ tıkladığımızda bu kelimeyi MessageDialog ile göstermek istiyorsak aşağıdaki kodları kullanabiliriz:

import javax.swing.*;
import javax.swing.text.BadLocationException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Gets word from right clicked area
 */
public class WordSelectionFromRightClick {

    public static void main(String[] args) {
        final JTextArea txtContent = new JTextArea(25, 30);
        JFrame frame = new JFrame("Word Selection From Right Click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(txtContent);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        txtContent.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //BUTTON3 represents right click
                if (e.getButton() == MouseEvent.BUTTON3) {
                    txtContent.setCaretPosition(txtContent.viewToModel(e.getPoint()));
                    int caretPosition = txtContent.getCaretPosition();
                    try {
                        String word = getWord(caretPosition, txtContent);
                        JOptionPane.showMessageDialog(null, word);
                    } catch (BadLocationException e1) {
                        e1.printStackTrace();
                    }

                }
            }
        });
    }

    private static String getWord(int caretPosition, JTextArea txtContent) throws BadLocationException {
        int startIndex;
        int endIndex;
        int i = 0;
        while (!txtContent.getText(caretPosition + i, 1).equals(" ")
                && !txtContent.getText(caretPosition + i, 1).equals("\n")) {
            i++;
        }
        endIndex = caretPosition + i;
        int j = 0;
        while (j < caretPosition && !txtContent.getText(caretPosition - j - 1, 1).equals(" ")) {
            j++;
        }
        startIndex = caretPosition - j;
        return txtContent.getText(startIndex, endIndex - startIndex);
    }
}

© 2019 Tüm Hakları Saklıdır. Codesenior.COM