Multiple buttons (Jbutton) with the same function in different Jpanels

Asked

Viewed 586 times

1

I’m making a program (using the Netbeans GUI Builder and Cardlayout) with multiple screens (multiple Jpanels) and they’ll all have a start button, which obviously goes back to the home screen.

I want to make the code cleaner, so I created a new class, buttons.java (already planning to use it for other buttons that should be repeated), and a method:

static void inicio(){
    CardLayout c1 = (CardLayout) root.getLayout();
    c1.show(root, "pInicio");
}

When I have the button run this method, it works normally as I expected, but netbeans indicates an error that is bothering me: "root has private access in Telaprincipal", where root is the main Jpanel (or parent) and Telaprincipal is the Jframe.

How do I fix it?

EDIT:

Part of the Telaprincipal code:

root = new javax.swing.JPanel();
pInicio = new javax.swing.JPanel();
bInicio1 = new javax.swing.JButton();

root.setLayout(new java.awt.CardLayout());

root.add(pInicio, "pInicio");

private void bInicioActionPerformed(java.awt.event.ActionEvent evt) {                                        
        Botoes.inicio();
}
  • It has how to include the code of the TelaPrincipal?

  • As I am using the Netbeans GUI Builder, the full Telaprincipal code is more than 300 lines (automatically generated, contains a lot of formatting and design only), but I tried to filter out the important part / that relates to the problem, edited the question and added it.

  • root = new javax.swing. "root" is which object?

  • Oops! A thousand apologies! I just copied the code wrong, I fixed it! It’s a Jpanel...

1 answer

1

It might be a little late, but maybe it’ll help someone else. When you generate the interface using the Netbeans GUI Builder, the components are generated with private access in the class, i.e., it is not possible to reference this object from another class. To solve this problem, tab the component properties root (your Jpanel) and, on the tab Código look for Modificadores de Variável (Variable Modifiers) and change the value of this field to public. Thus, the component root can be accessed and modified from any class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.