[英]Error using protected method of data type of the same class
I'm new to Java and I've been trying to create a text program. 我是Java的新手,我一直在尝试创建一个文本程序。 I've been trying to use a protected method .getRowHeight() from the JTextArea class and call it on an JTextArea object (like in the code below) but I'm getting an error saying "getRowHeight has protected access in javax.swing.JTextArea".
我一直在尝试使用JTextArea类中的受保护方法.getRowHeight()并在JTextArea对象上调用它(如下面的代码中所示),但我收到一条错误消息“getRowHeight在javax.swing中具有受保护的访问权限。 JTextArea中”。
I read online that you can only use protected methods in classes that inherit from the class. 我在网上读到,你只能在从类继承的类中使用受保护的方法。 But I'm trying to use it on a variable that is from that class, so I thought it would work?
但我试图在一个来自该类的变量上使用它,所以我认为它会起作用? Is there a way of making this work without having to inherit from the JTextArea class, because I only really need to use this method once?
是否有一种方法可以在不必继承JTextArea类的情况下完成这项工作,因为我只需要使用此方法一次?
Here's a snippet of the code pertaining to userText: 这是与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());
}
}
You can only call getRowHeight()
from a class that belongs to javax.swing
package or extends JTextArea
. 您只能
getRowHeight()
javax.swing
包的类中调用getRowHeight()
或扩展JTextArea
。
However, looking at the code of JTextArea
, it looks like you can use this method, which is public : 但是,查看
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);
}
}
So, userText.getScrollableUnitIncrement(null,SwingConstants.VERTICAL,0)
should return the same output as userText.getRowHeight()
. 因此,
userText.getScrollableUnitIncrement(null,SwingConstants.VERTICAL,0)
应返回与userText.getRowHeight()
相同的输出。
And in your code : 在你的代码中:
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.