Hans Schwimmer
Hans Schwimmer

Reputation: 139

Can I manipulate specific grids in gridlayout?

I created my own Custom panel with gridlayout(1,3) with 3 JComponents

JLabel || some component || JCheckBox

I want to disable the component in the second grid if I check JCheckBox. Is there a way to access it? What if I don't know what kind of component it is?

package View.Components;

import java.util.Calendar;
import java.util.Date;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerNumberModel;

public class CustomPanel extends JPanel
{

    private static final long serialVersionUID = 1L;
    private JLabel label;
    public JSpinner spinner;
    public JCheckBox box;
    private String labelContent;
    public JTextField textField;
    private JComboBox<String> comboBox;

    public void setLabelContent(String labelContent)
    {
        this.labelContent = labelContent;
    }

    public String getLabelContent()
    {
        return labelContent;
    }

    public void getLabel()
    {
        label = new JLabel(getLabelContent());
        label.setHorizontalAlignment(JLabel.LEFT);
        this.add(label);
    }

    public void getSpinner()
    {
        Date todaysDate = new Date();

        spinner = new JSpinner(new SpinnerDateModel(todaysDate, null, null, Calendar.DAY_OF_MONTH));
        JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(spinner, "dd/MM/yy");
        spinner.setEditor(dateEditor);
        this.add(spinner);
    }

    public void getSpinner(int defValue, int minValue, int maxValue, int step)
    {
        SpinnerNumberModel spinnerSettings = new SpinnerNumberModel(defValue, minValue, maxValue, step);        
        spinner = new JSpinner(spinnerSettings);
        this.add(spinner);
    }

    public void getCheckBox()
    {
        box = new JCheckBox();
        box.setHorizontalAlignment(JLabel.CENTER);
        box.setSelected(true);
        this.add(box);
    }

    public void getTextField()
    {
        textField = new JTextField();       
        this.add(textField);
    }

    public void getComboBox(String[] panelArray)
    {
        comboBox = new JComboBox<String>(panelArray);
        comboBox.setSelectedIndex(4);
        this.add(comboBox);
    }

}

My Gui shows everything perfectly as I want. I just don't know know how to access the second grid because it may be JTextField but JSpinner as well. Should I place all irregular components within another JPanel and force all JPanels to disable themselves on check?

Upvotes: 0

Views: 69

Answers (1)

camickr
camickr

Reputation: 324157

Is there a way to access it?

Your custom panel is a Container. You can access any component added to the panel using the Container.getComponent(...) method.

Upvotes: 2

Related Questions