【问题标题】:NetBeans Matisse - Access jframe component from another classNetBeans Matisse - 从另一个类访问 jframe 组件
【发布时间】:2014-05-25 06:05:15
【问题描述】:

来自 Netbeans 的 Matisse 代码被阻止。我遇到的问题是,我必须将 setBackground 从另一个包中的另一个类转换为 JLabel,但我不能这样做,因为我无法访问 JLabel,因为它的私有和被阻止的代码。

有什么解决办法吗?

【问题讨论】:

    标签: java swing netbeans gui-builder matisse


    【解决方案1】:
    • 使用 JLabel 为类创建一个监听器,并使用更改标签背景的方法
    • 在使用JLabel的类中实现
    • 使用 JLabel 将其他类(您要从中更改 BG)的侦听器设置为类的侦听器
    • 在您想要的任何功能之后更改背景。

    【讨论】:

      【解决方案2】:

      “来自 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);
          }
      }
      

      【讨论】:

      • 不使用多个框架...我有一个用 matisse 制作的主框架,但由于某些原因,当另一个类中发生 X 验证时,我必须从另一个类中设置 matisse 内的 textField 的背景...这不是解决方案:P
      • 您能否提供一些示例代码来更详细地说明问题
      • 这是整个项目mediafire.com/download/559r2joiqmc752n/TransferenciaBancaria.7z查看类Fecha,有评论
      • 查看我的 UPDATE 我认为您正在寻找类似的东西。看问题开头的链接看看initComponents()里的代码怎么编辑
      • 1- 我建议人们可以编辑表单生成的受保护块,因为它可能会在下次打开表单时重新生成。 2-我也会小心通过 getter 公开 UI 组件,这会留下可能不想要的修改(包括代码删除的能力),就个人而言,我会使用属性设置器
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 2012-09-02
      • 2014-10-07
      • 1970-01-01
      • 2012-09-07
      • 2014-04-06
      • 1970-01-01
      相关资源
      最近更新 更多