是否可以在一条语句中向JPanel添加多个组件



问题很简单。我意识到,如果允许我在JPanel中添加组件,我的代码可以稍微清理一下:

//north panel
JPanel northPanel = new JPanel(new GridLayout(0,3));
btnAdd = new JButton("Add");
btnEdit = new JButton("Edit");
btnDelete = new JButton("Delete");
northPanel.add(btnAdd, btnEdit, btnDelete);

而不是这样:

//north panel
JPanel northPanel = new JPanel(new GridLayout(0,3));
btnAdd = new JButton("Add");
btnEdit = new JButton("Edit");
btnDelete = new JButton("Delete");
northPanel.add(btnAdd);
northPanel.add(btnEdit);
northPanel.add(btnDelete);

有办法做到吗?我查阅了SO和互联网,包括Oracle的文档,我知道没有针对这种特定语法构建.add()方法,但我想知道是否还有其他方法具有这种功能。

好的解决方案:

感谢大家的反馈。如果按照我描述的方式完成,一句话实际上会更复杂,这确实是有道理的。L.Mehmeti建议将组件存储在一个数组中,并创建一种将所有组件添加到数组中的方法,这非常适合这个问题。这样,当有很多组件时,就可以很容易地跟踪顺序,而不必搜索一堆单独的构造函数和添加语句。

我很抱歉,但我想没有办法这么做。我认为唯一的办法就是写你自己的方法。例如:

public static void main(String[] args) {
    Example main = new Example("Example");
}
public Example(String title) {
    super(title);
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    JComponent[] components = new JComponent[3];
    components[0] = new JLabel("Hello!");
    components[1] = new JLabel("How are you?");
    components[2] = new JLabel("I am fine. Thanks");
    addComponents(panel, components);
    add(panel);
    setVisible(true);
}
public void addComponents(JComponent target, JComponent[] components) {
    for(JComponent component : components) {
        target.add(component);
    }
}

希望我能帮忙。

您可以创建一个方法并在init方法中调用它。

public void addComponentsJ()
{
     northPanel.add(btnAdd);
     northPanel.add(btnEdit);
     northPanel.add(btnDelete);
}

这将允许您使用

addComponentsJ()// to add all the components..

但是,这与你正在做的事情相对来说是一样的。。。只是将add方法调用重新定位到另一个方法。从而允许您"将它们全部添加到一个语句中"Swing不支持在一个语句中添加组件。。。唯一的方法是将调用重新定位到另一个方法。

最新更新