使用相同 class 数据类型的受保护方法时出错

Error using protected method of data type of the same class

我是 Java 的新手,我一直在尝试创建一个文本程序。我一直在尝试使用 JTextArea class 中的受保护方法 .getRowHeight() 并在 JTextArea 对象上调用它(如下面的代码),但我收到一条错误消息 "getRowHeight has protected access in javax.swing.JTextArea"。

我在网上看到,您只能在继承自 class 的 class 中使用受保护的方法。但是我正在尝试将它用于来自 class 的变量,所以我认为它会起作用吗?有没有一种方法可以使这项工作不必从 JTextArea 继承class,因为我真的只需要使用这个方法一次?

这是与 userText 有关的代码片段:

    public class Client extends JFrame {

        private JTextArea userText;

        public Client() {
            userText = new JTextArea(); //2, 2
            userText.setLineWrap(true);     // turns on line wrapping
            userText.setWrapStyleWord(true);
            add(userText, BorderLayout.SOUTH);
            System.out.println(userText.getRowHeight());
        }
    }

您只能从属于 javax.swing 包或扩展 JTextArea.

的 class 调用 getRowHeight()

不过看了JTextArea的代码,好像可以用这个方法,就是public:

public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
    switch (orientation) {
    case SwingConstants.VERTICAL:
        return getRowHeight(); // this is what you need
    case SwingConstants.HORIZONTAL:
        return getColumnWidth();
    default:
        throw new IllegalArgumentException("Invalid orientation: " + orientation);
    }
}

因此,userText.getScrollableUnitIncrement(null,SwingConstants.VERTICAL,0) 应该 return 与 userText.getRowHeight() 相同的输出。

在您的代码中:

    public Client() {
        userText = new JTextArea(); //2, 2
        userText.setLineWrap(true);     // turns on line wrapping
        userText.setWrapStyleWord(true);
        add(userText, BorderLayout.SOUTH);
        System.out.println(userText.getScrollableUnitIncrement(null,SwingConstants.VERTICAL,0));
    }