actionPerformed立即对所有自定义JPanel进行操作

时间:2016-11-12 00:20:17

标签: java swing actionlistener

我正在创建一个GUI来显示数据库的输出。

目前,我正在向CoursePanel extends JPanel添加JScrollPane,以模拟列表中的行。我无法将JListListCellRenderer一起使用,因为我需要每一行都能获得超出简单点击的功能。

每个CoursePanel上都有一个JButton。单击时,该按钮会向CoursePanel添加一个新行并显示一些额外信息。

但是,当我将ActionListener绑定到按钮以增加GridLayout中的行数时,它会向CoursePanel的每个实例添加一行。但是,只有当前CoursePanel个额外行可见。任何人都可以提供有关出错的建议吗?

public class CoursePanel extends JPanel{
    public CoursePanel(){

        this.setLayout(new GridLayout(1, 1);

        JPanel infoPanel = new JPanel();

        JPanel extraPanel = new JPanel();
        extraPanel.add(new JLabel("test"));
        extraPanel.setVisible(false);

        JButton revealBtn = new JButton("Reveal");

        revealBtn.addActionListener(e -> {

            //this line happens for every CoursePanel in the scroll pane
            //meaning every row suddenly doubles in width
            ((GridLayout)this.getLayout()).setRows(2);


            //this only happens for the instance of CoursePanel who's button is clicked!
            //i.e. the JLabel with "test" only appears in the row who's button is clicked
            this.add(extraPanel);
            extraPanel.setVisible(true);
        });

        infoPanel.add(revealBtn);                     

        this.add(infoPanel);
    }
}

//where the scroll panel is built
JPanel contentPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(contentPanel);

for(rows in database){
    //...some code to add new rows to the scrollpane...

    contentPanel.add(new CoursePanel(row));    

}

点击之前:

Before clicking anything

点击Bobby按钮后,请注意与'测试'相同尺寸的间隙。每行下面的一行:

After clicking Bobby's button

0 个答案:

没有答案