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