我正在尝试让多个CardLayout并排显示,所有这些都在FlowLayout中。一切运行良好,但窗口中没有任何显示。如何使 FlowLayout 显示 CardLayout 及其组件?
我已经阅读了我能找到的所有相关文档,但发现它们对这个问题没有多大帮助。
这是我的示例代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class RenderTest extends JPanel{
private JFrame window;
private FlowLayout topLevelLayout;
private Slot[] slots;
public static void main(String[] args) {
RenderTest instance = new RenderTest();
instance.init();
}
private void init(){
window = new JFrame("Render Test");
topLevelLayout = new FlowLayout();
window.setLayout(topLevelLayout);
window.setResizable(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
slots = new Slot[]{new Slot(0), new Slot(2)};
window.add(slots[0]);
window.add(slots[1]);
window.pack();
window.setVisible(true);
}
private class Slot extends JPanel{
JPanel panel;
CardLayout cardLayout;
public Slot(int index){
RemoveButton remove = new RemoveButton(index);
AddButton add = new AddButton(index);
cardLayout = new CardLayout();
panel = new JPanel();
panel.setLayout(cardLayout);
cardLayout.addLayoutComponent(add.getPanel(), "add");
cardLayout.addLayoutComponent(remove.getPanel(), "show");
topLevelLayout.addLayoutComponent("card"+index, panel);
}
private JPanel getPanel(){
return this.panel;
}
private CardLayout getCardLayout(){
return this.cardLayout;
}
}
private class AddButton extends JPanel{
JPanel panel;
private AddButton(int index){
panel = new JPanel();
JButton addButton = new JButton("+");
addButton.setVerticalTextPosition(AbstractButton.CENTER);
addButton.setHorizontalTextPosition(AbstractButton.CENTER);
addButton.setActionCommand("add"+index);
addButton.addActionListener(new Button());
panel.add(addButton);
}
private JPanel getPanel(){
return this.panel;
}
}
private class RemoveButton extends JPanel{
JPanel panel;
private RemoveButton(int index){
panel = new JPanel();
JButton removeButton = new JButton("-");
removeButton.setVerticalTextPosition(AbstractButton.CENTER);
removeButton.setHorizontalTextPosition(AbstractButton.CENTER);
removeButton.setActionCommand("remove"+index);
removeButton.addActionListener(new Button());
panel.add(removeButton);
}
private JPanel getPanel(){
return this.panel;
}
}
class Button implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("add0")){
slots[0].getCardLayout().show(getParent(), "show");
}
if (e.getActionCommand().equals("add1")){
slots[1].getCardLayout().show(getParent(), "show");
}
if (e.getActionCommand().equals("remove0")){
slots[0].getCardLayout().show(getParent(), "hide");
}
if (e.getActionCommand().equals("remove1")){
slots[1].getCardLayout().show(getParent(), "hide");
}
}
}
}
更新了代码以使用 this
而不是 new JPanel
s: https://pastebin.com/e0fhkaen
让它工作:pastebin 5XrFYarD
在Slot
类中,不要创建新的JPanel
,你应该只使用
this.setLayout(cardLayout);
由于此类扩展了JPanel
.
就像现在一样,你只是在框架中添加两个空JPanel
。
其他类(AddButton
和RemoveButton
)也是如此