0
我在CardLayout
上關注YouTube上的教程。我下載了the original code,它工作得很好。但對於我試圖製作的程序,我需要一個單獨的類來運行應用程序(即單獨的類僅使用main
方法),單獨的類爲JFrame
,並且至少有一個單獨的類用於JPanel
s。我嘗試分離代碼,但它爲我顯示一個空白JFrame
。CardLayout的問題
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class CardJPanel extends JPanel
{
JPanel panelCont = new JPanel();
JPanel panelFirst = new JPanel();
JPanel panelSecond = new JPanel();
JButton buttonOne = new JButton("Switch to second panel");
JButton buttonSecond = new JButton("Switch to first panel");
CardLayout cl = new CardLayout();
public CardJPanel()
{
panelCont.setLayout(cl);
panelFirst.add(buttonOne);
panelSecond.add(buttonSecond);
panelFirst.setBackground(Color.BLUE);
panelSecond.setBackground(Color.GREEN);
panelCont.add(panelFirst, "1");
panelCont.add(panelSecond, "2");
cl.show(panelCont, "1");
buttonOne.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
cl.show(panelCont, "2");
}
});
buttonSecond.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
cl.show(panelCont, "1");
}
});
}
}
import javax.swing.JFrame;
public class Frame extends JFrame
{
public Frame()
{
CardJPanel panel = new CardJPanel();
setContentPane(panel);
setVisible(true);
// if I do this it displays the panel just fine
JPanel panel2 = new JPanel();
panel.setBackground(Color.MAGENTA);
setContentPane(panel2);
}
}
import javax.swing.JFrame;
public class Main
{
public static void main(String[] args)
{
Frame startFrame = new Frame();
startFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
startFrame.setSize(450, 400);
startFrame.setVisible(true);
}
}