我可以在gridlayout中操纵特定网格吗?

时间:2015-12-07 21:50:04

标签: java swing

我使用gridlayout(1,3)

创建了我自己的自定义面板3 JComponents
JLabel || some component || JCheckBox

如果我检查JCheckBox,我想在第二个网格中禁用该组件。有没有办法访问它?如果我不知道它是什么类型的组件怎么办?

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);
    }

}

我的Gui按照我的要求完美展示了一切。我只是不知道如何访问第二个网格,因为它可能是JTextField,但也是JSpinner。我应该将所有不规则组件放在另一个JPanel中并强制所有JPanels在检查时自行禁用吗?

1 个答案:

答案 0 :(得分:2)

  

有没有办法访问它?

您的自定义面板是Container。您可以使用Container.getComponent(...)方法访问添加到面板的任何组件。