我为欢迎屏幕设计了一个界面,其中一个JFrame包含两个JPanels(右边是JPanel1,左边是JPanel2)。左侧的按钮用于切换JPanel1中的面板。我想按一个按钮将JPanel1内容替换为另一个JPanel,但我不知道如何。请帮忙。
答案 0 :(得分:3)
这是一个非常简单的示例,应该与您的描述近似。在左侧,我们有一个拥抱按钮来切换右侧面板的内容。在右侧,您有一个带有给定边框和标签的面板。按下按钮时,右侧的内容将与另一个面板交换。
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestCardLayout2 {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel leftPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Left panel");
leftPanel.add(label, BorderLayout.NORTH);
JButton button = new JButton("Toggle right panel");
leftPanel.add(button);
frame.add(leftPanel, BorderLayout.WEST);
final CardLayout cardLayout = new CardLayout();
final JPanel rightPanel = new JPanel(cardLayout);
rightPanel.setPreferredSize(new Dimension(200, 500));
JPanel rightPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
rightPanel1.setBorder(BorderFactory.createLineBorder(Color.RED));
JPanel rightPanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
rightPanel2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JLabel label1 = new JLabel("Right panel 1 with a red border");
JLabel label2 = new JLabel("Right panel 2 with a blue borer");
rightPanel1.add(label1);
rightPanel2.add(label2);
rightPanel.add(rightPanel1, "panel1");
rightPanel.add(rightPanel2, "panel2");
frame.add(rightPanel, BorderLayout.EAST);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(rightPanel);
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestCardLayout2().initUI();
}
});
}
}
答案 1 :(得分:2)
CardLayout
的替代方法是JRootPane
及其JRootPane.setContentPane()
方法。这是一个例子:
final JPanel panel1 = ...;
final JPanel panel2 = ...;
boolean showingPanel1 = true;
final JRootPane rootPane = new JRootPane();
rootPane.setContentPane(panel1);
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (showingPanel1) {
rootPane.setContentPane(panel2);
} else {
rootPane.setContentPane(panel1);
}
showingPanel = !showingPanel;
}
});
将rootPane
和switchButton
组件添加到您的窗口,然后点击switchButton
将关闭面板。
这是一个tutorial。您应该主要关注JRootPane.setContentPane
,本教程中的其他内容不相关。
答案 2 :(得分:0)
我发现最好的答案是我只会创建一个JFrame,并且会让一个大的JPanel包括两个JPanel(JPanelLeft包含按钮,JPanelRight包含按钮的功能)然后我将复制每个JButton的主要JPanel。 当我按下任何按钮时,我将(JFrame.getContentPane.removeAll)删除旧的JPanel(JFrame.getContentPane.Add(NewJPanel)。
这对我有用,并保持我想要的设计。谢谢你的每一个人。