当Netbeans扩展JPanel时,在引用自动生成的类的实例时是否会产生问题,因为它使用的是继承而不是组合?
因为Netbeans将JPanel声明为private javax.swing.JPanel overview;
,所以实例的类型为JPanel,而它应该具有类型的概述。
如何调用setGroup方法并将Overview保留为自动生成的JPanel?我这样试试:
Main.java
private void groupsPropertyChange(java.beans.PropertyChangeEvent evt) {
String s = evt.getNewValue().toString();
LOG.fine("new group: " + s);
overview.setGroup(s);
}
with Overview.java:
public class Overview extends javax.swing.JPanel {
...
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
但是得到了这个编译错误:
init:
Deleting: /home/thufir/NetBeansProjects/SwingNNTP/build/built-jar.properties
deps-jar:
Updating property file: /home/thufir/NetBeansProjects/SwingNNTP/build/built-jar.properties
Compiling 1 source file to /home/thufir/NetBeansProjects/SwingNNTP/build/classes
warning: [options] bootstrap class path not set in conjunction with -source 1.5
/home/thufir/NetBeansProjects/SwingNNTP/src/net/bounceme/dur/nntp/view/Main.java:59: error: cannot find symbol
overview.setGroup(s);
symbol: method setGroup(String)
location: variable overview of type JPanel
1 error
1 warning
/home/thufir/NetBeansProjects/SwingNNTP/nbproject/build-impl.xml:628: The following error occurred while executing this line:
/home/thufir/NetBeansProjects/SwingNNTP/nbproject/build-impl.xml:285: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 1 second)
答案 0 :(得分:4)
对于一个或多个JPanel
实例,具有合适layout的Container
是方便的JComponent
。它提供了(基本的)UI委托和双缓冲,但很少。自定义组件应该直接扩展JComponent
。 (可选)UI委托的基础结构显示为here。您可以按照here所述,将此类自定义组件添加到设计器选项板中。
答案 1 :(得分:2)
好吧,我猜Netbeans没有这样的选择,可以将使用GUI创建的JPanel声明为除JPanel以外的任何类型,这有点奇怪。为什么要扩展JPanel,如果继续使用Netbeans GUI构建器,则无法使用该扩展类型实例化JPanel的子类?并不是说扩展JPanel本质上是个好主意......
解决方案代码:
package net.bounceme.dur.nntp.view;
import java.util.logging.Logger;
import javax.swing.JTabbedPane;
public class MyTabs extends JTabbedPane {
private static final Logger LOG = Logger.getLogger(MyTabs.class.getName());
private Overview overview = new Overview();
private Detail details = new Detail();
private Groups groups = new Groups();
public MyTabs() {
this.add("groups", groups);
this.add("overview", overview);
this.add("detail", details);
groups.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String s = evt.getNewValue().toString();
LOG.fine(s);
overview.setGroup(s);
}
});
}
}
我很好奇是否有更好的方法可以做到这一点,除了不使用GUI构建器。