Question

I have one "main" panel. I'd like to have a "side" panel inside the main one. The side is composed of two other panels, let's call one graphicPanel and one supportPanel. I'm trying to add labels to the SupportPanel from the main one, but no changes happen.

Here is my side panel:

public class LateralSupportPane extends JPanel{

private final static int WIDTH = 240;
private final static int HEIGHT = 740;
private GraphicPanel gp;
private SupportPanel sp;


public LateralSupportPane(){
    this.gp = new GraphicPanel();
    this.sp = new SupportPanel();
    this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    this.setLayout(new GridLayout(2, 1));
    //this.setBorder(BorderFactory.createLineBorder(Color.black));
    this.add(gp);
    this.add(sp);

    this.setVisible(true);
}

    public void addLabel(String label){
    sp.addLabel(label);
}


public void paintComponent(Graphics g){
    super.paintComponent(g);
    gp.paintComponent(g);
}

public void addLabel(String label){
    sp.addLabel(label);
}

Here my supportPanel:

public class SupportPanel extends JPanel{
private JLabel label;
private final static int WIDTH = 240;
private final static int HEIGHT = 370;

public SupportPanel(){

    this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    label = new JLabel();
    label.setText("<html>BlaBla</html>");
    this.setLayout(new GridLayout(10, 1));
    this.add(label);
    this.setVisible(true);
}

public JLabel getLabel() {
    return label;
}

public void addLabel(String text){
    JLabel label = new JLabel(text);
    if(this.getComponentCount() < 10){
        this.add(label);
    } else {
        this.remove(0);
        this.add(label);
    }
}

From the main panel I call the addLabel of the side panel.

EDIT: Here is the frame with all panels. The board itself is a panel added into a frame. The board also has another panel, that are the black rectangle and the area where the string is, together. Then the side panel is composed by 2 other panels, the GraphicPanel (the black rectangle) and the supportPanel, that is the area where I'd like to have my labels.

Board

Validating all panels made no progress.

Was it helpful?

Solution

Not sure if i undurstend it correctly, but it seams, that you have to validate your panels after inserting new label;

public static void main(String[] args) {
    JFrame frame = new JFrame("test");
    frame.setSize(900, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new CardLayout());
    frame.setVisible(true);
    LateralSupportPane p = new LateralSupportPane();
    frame.add(p);
    frame.validate();
    p.addLabel("test 2");
    p.validate();
}

as you see, after adding a label, validation is performed and object is painted on form. your method addLabel(String label) should have this method called at end of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top