我正在创建一个GUI来显示数据库的输出。
目前,我正在向CoursePanel extends JPanel
添加JScrollPane
,以模拟列表中的行。我无法将JList
与ListCellRenderer
一起使用,因为我需要每一行都能获得超出简单点击的功能。
每个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));
}
点击之前:
点击Bobby按钮后,请注意与'测试'相同尺寸的间隙。每行下面的一行: