javaswingnetbeansgui-buildermatisse

NetBeans Matisse - Access jframe component from another class


The Matisse code from Netbeans is blocked. The problem I have is that I have to setBackground to a JLabel from another Class in different package but I cannot do this because i have no access to the JLabel due to its private and blocked code.

Is thare any solution to this?


Solution

  • "The Matisse code from Netbeans is blocked"

    You can edit it as seen here

    "because i have no access to the JLabel due to its private and blocked code"

    Just write a getter method for the label in the other class

    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(...)
        }
    }
    

    "Access jframe component from another class"

    Sounds like you're using multiple frames. See The Use of Multiple JFrames, Good/Bad Practice?


    UPDATE

    " I have a MAIN frame made in matisse but due to some reasons i have to set the background of an textField inside matisse from another class when X validation happens in the other class"

    What you can do then is pass a reference of the Main frame to the other class, and have a setter in the Main frame. Something like (I will provide an interface for access)

    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);
        }
    }