Search code examples
javaswingjbutton

Button connecting with a JPanel


I am using Netbeans to create a Java desktop application. I have created two different JPanels. In one I have inserted a button, and in the other just some settings. How can I connect the JButton, in the other JPanel, to change the settings of the other one? What code should I use? (Keep in mind that I am a beginner.)


Solution

  • A very simple programm. It dosen't matter if the button and the label are in the same JPanel or not.

    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setBounds(100, 100, 300, 300);
    
    JPanel panel = new JPanel();
    panel.setPreferredSize(new Dimension(300, 150));
    
    JLabel label = new JLabel("Test string");
    
    JButton button = new JButton("Push me");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("change text");
        }
    });
    panel.add(label);
    panel.add(button);
    
    frame.add(panel);
    
    frame.setVisible(true);