Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用同一类的数据类型的受保护方法时出错_Java_Swing_User Interface - Fatal编程技术网

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

Java 使用同一类的数据类型的受保护方法时出错,java,swing,user-interface,Java,Swing,User Interface,我是Java新手,我一直在尝试创建一个文本程序。我一直在尝试使用JTextArea类中的protected方法.getRowHeight(),并在JTextArea对象上调用它(如下面的代码中所示),但我收到一个错误,即“getRowHeight在javax.swing.JTextArea中具有受保护的访问权限” 我在网上读到,您只能在从类继承的类中使用受保护的方法。但是我试着在那个类的变量上使用它,所以我认为它会起作用?有没有一种方法可以不必从JTextArea类继承,因为我只需要使用这个方法

我是Java新手,我一直在尝试创建一个文本程序。我一直在尝试使用JTextArea类中的protected方法.getRowHeight(),并在JTextArea对象上调用它(如下面的代码中所示),但我收到一个错误,即“getRowHeight在javax.swing.JTextArea中具有受保护的访问权限”

我在网上读到,您只能在从类继承的类中使用受保护的方法。但是我试着在那个类的变量上使用它,所以我认为它会起作用?有没有一种方法可以不必从JTextArea类继承,因为我只需要使用这个方法一次

以下是有关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
的类中调用
getRowHeight()

但是,查看
JTextArea
的代码,您似乎可以使用此方法,它是公共的:

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)
应返回与
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));
    }