移动JScrollBar时显示行号

时间:2014-05-30 20:43:54

标签: java swing user-interface

在Linux文本编辑器中,Kate有一个很好的功能,当我单击并拖动滚动条时,它会显示文本组件中当前正在查看的当前行号。 enter image description here 我的问题是如何在Java中将此函数添加到包含JTextArea的滚动窗格中。我可以使用哪个组件来显示此通知?

1 个答案:

答案 0 :(得分:5)

显然,您可以使用JPopupMenu

执行此操作

enter image description here

我尝试过这个课,因为我知道它有方法show(Component, x, y)。但它可能与其他类有关,或试图实现该方法自己做的任何事情。

我在scrollBar上放了几个鼠标监听器,并在show()调用中使用值x,y玩弄了一点,直到我对绘制它的位置感到满意为止。

完整代码:

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class ScrollbarTest
{
    private JScrollPane scrollPane;
    private JScrollBar scrollBar;
    private JPopupMenu popupMenu;
    private JLabel popupLabel;

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run()
            {
                new ScrollbarTest();
            }
        });
    }

    public ScrollbarTest()
    {
        JFrame frame = new JFrame("Test");

        popupMenu = new JPopupMenu();
        popupLabel = new JLabel();
        popupMenu.add(popupLabel);

        scrollPane = new JScrollPane(buildTestTextArea());
        scrollBar = scrollPane.getVerticalScrollBar();
        scrollBar.addMouseMotionListener(new PopUpMouseMotionListener());
        scrollBar.addMouseListener(new PopUpMouseListener());

        frame.add(scrollPane);

        frame.setSize(new Dimension(400, 400));
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public JTextArea buildTestTextArea()
    {
        JTextArea textArea = new JTextArea();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 10000; ++i)
        {
            builder.append("X");
        }
        textArea.setText(builder.toString());
        textArea.setLineWrap(true);
        return textArea;
    }

    private class PopUpMouseMotionListener extends MouseMotionAdapter
    {
        @Override
        public void mouseDragged(MouseEvent e)
        {
            double value = scrollBar.getValue();
            double max = scrollBar.getMaximum() - scrollBar.getVisibleAmount();
            double h = scrollBar.getHeight();
            popupLabel.setText("" + (int) (100*value/max) + "%");
            popupMenu.show(scrollPane, scrollBar.getX() - popupMenu.getWidth() - 2, (int) ((h - popupMenu.getHeight())*value/max));
        }
    }

    private class PopUpMouseListener extends MouseAdapter
    {
        @Override
        public void mouseReleased(MouseEvent e)
        {
            popupMenu.setVisible(false);
        }
    }
}