我正在开展一个学期的项目,我想知道是否可以存储3-4个JPanel而不是一个" main" JPanel的。我之所以这样问是因为我试图制作一个GUI支票簿程序而且我的支票簿有7个按钮,一旦我点击它就应该打开一个新窗口。要在每个窗口之间切换,我将不得不使用CardLayout,但我对CardLayout的理解是我只能将一个JPanel分配给该卡,因此我无法将多个JPanel分配给一张卡布局,所以当用户点击不同的卡时,会出现3-4个不同的JPanel。
我问这个的原因是因为我之前请求帮助并获得了在这个项目中创建我的第一个窗口的帮助,它产生了我想要的输出,但是使用了多个JPanel。由于这阻止我继续使用我的7 GUI窗口的其他步骤,我被卡住了。
以下是代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
为了向我展示上面的例子,信用到了Hovercraft Full Of Eels
如果我的问题有任何不清楚的地方,请询问,我会尽我所能来解决它。
以下是代码生成的内容 :