【发布时间】:2014-05-25 06:05:15
【问题描述】:
来自 Netbeans 的 Matisse 代码被阻止。我遇到的问题是,我必须将 setBackground 从另一个包中的另一个类转换为 JLabel,但我不能这样做,因为我无法访问 JLabel,因为它的私有和被阻止的代码。
有什么解决办法吗?
【问题讨论】:
标签: java swing netbeans gui-builder matisse
来自 Netbeans 的 Matisse 代码被阻止。我遇到的问题是,我必须将 setBackground 从另一个包中的另一个类转换为 JLabel,但我不能这样做,因为我无法访问 JLabel,因为它的私有和被阻止的代码。
有什么解决办法吗?
【问题讨论】:
标签: java swing netbeans gui-builder matisse
【讨论】:
“来自 Netbeans 的马蒂斯代码被阻止”
你可以编辑它here
“因为我无法访问 JLabel,因为它的私有和被阻止的代码”
只需为其他类中的标签写一个getter方法
public class OtherClass .. {
private JLabel jLabel1;
public JLabel getLabel() {
return jLabel1;
}
}
import otherpackage.OtherClass;
public class MainFrame extends JFrame {
private OtherClass otherClass;
...
private void jButtonActionPerformed(ActionEvent e) {
JLabel label = otherClass.getLabel();
label.setBackground(...)
}
}
“从另一个类访问jframe组件”
听起来您正在使用多个帧。见The Use of Multiple JFrames, Good/Bad Practice?
更新
“我有一个用 matisse 制作的主框架,但由于某些原因,当另一个类中发生 X 验证时,我必须在另一个类中设置 matisse 内的 textField 的背景”
然后您可以做的是将Main 框架的引用传递给另一个类,并在Main 框架中拥有一个setter。类似的东西(我会提供一个访问接口)
public interface Gettable {
public void setLabelBackground(Color color);
}
public class Main extends JFrame implements Gettable {
private JLabel jLabel1;
private OtherPanel otherPanel;
public void initComponents() {
otherPanel = new OtherPanel(Main.this); // see link above to edit this area
}
@Override
public void setLabelBackground(Color color) {
jLabel1.setBackground(color);
}
}
public class OtherPanel extends JPanel {
private Gettable gettable;
public OtherPanel(Gettable gettable) {
this.gettable = gettable;
}
private void jButtonActionPerformed(ActionEvent e) {
gettable.setLabelBackground(Color.RED);
}
}
【讨论】:
initComponents()里的代码怎么编辑