1

I have constructed a class for the JPanel with several JButtons.Inside this class I want to construct another JPanel with JLabels that will change depending on the actionPerformed on the JButtons of the first JPanel.Finally, I want to add these 2 panels on the same Jframe. Can all these be done within the class of the first Panel?Otherwise, which is a better approach for this problem?

1 Answers1

0

Yes, you can. One way you could accomplish this is with anonymous inner classes (saves keystrokes):

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

public class Foo {
    JLabel one;
    JLabel two;

    public static void main(String[] args) {
        (new Foo()).go();
    }

    public void go() {
        JFrame frame = new JFrame("Test");

        // Panel with buttons
        JPanel buttonPanel = new JPanel();
        JButton changeOne = new JButton("Change One");
        changeOne.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                one.setText("New text for one");
            }
        }
        buttonPanel.add(changeOne);
        JButton changeTwo = new JButton("Change Two");
        changeTwo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                two.setText("New text for two");
            }
        }
        buttonPanel.add(changeTwo);
        frame.add(buttonPanel, BorderLayout.NORTH);

        // Panel with labels
        JPanel labelPanel = new JLabel();
        one = new JLabel("One");
        labelPanel.add(one);
        two = new JLabel("Two");
        labelPanel.add(two);

        // Set up the frame
        frame.add(labelPanel, BorderLayout.SOUTH);
        frame.setBounds(50, 50, 500, 500);
        frame.setDefaultCloseAction(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
APerson
  • 8,140
  • 8
  • 35
  • 49