我有一个大约四帧的JFrame。在给定动作之后,我想在同一位置将一个面板替换为另一个面板。我切换它们的方法看起来像这样(this
对象是一个扩展JFrame
的类):
public void switchPanel(){
mainPanel.remove(introPanel);
mainPanel.add(questionPanel);
this.repaint();
}
窗口的原始创建如下所示:
mainPanel.add(titlePanel);
mainPanel.add(sidePanel);
mainPanel.add(introPanel);
答案 0 :(得分:7)
你问:
如何将一个JPanel替换为同一位置的另一个JPanel?
非常容易:使用CardLayout,因为此工具是针对这种情况而构建的。
如果你有以下常数:
public static final String INTRO_PANEL = "intro panel";
public static final String QUESTION_PANEL = "question panel";
并添加了你的JPanel
mainPanel.setLayout(cardLayout);
mainPanel.add(introPanel, INTRO_PANEL);
mainPanel.add(questionPanel, QUESTION_PANEL);
cardLayout.show(mainPanel, INTRO_PANEL);
然后你可以用以下方式交换JPanel:
cardLayout.show(mainPanel, QUESTION_PANEL);
将显示交换所需的全部内容,假设QUESTION_PANEL是在将questionPanel添加到mainPanel时使用的String常量,并且mainPanel使用CardLayout。
例如:
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class SwapPanels extends JPanel {
public static final String INTRO_PANEL = "intro panel";
public static final String QUESTION_PANEL = "question panel";
private static final int PREF_W = 500;
private static final int PREF_H = 400;
private CardLayout cardLayout = new CardLayout();
private JPanel introPanel;
private JPanel questionPanel;
private Random random = new Random();
public SwapPanels() {
introPanel = createPanel("Introduction");
questionPanel = createPanel("Question");
setLayout(cardLayout);
add(introPanel, INTRO_PANEL);
add(questionPanel, QUESTION_PANEL);
int delay = 3 * 1000; // show intro for 3 seconds
new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(SwapPanels.this, QUESTION_PANEL);
((Timer) e.getSource()).stop();
}
}).start();
}
private JPanel createPanel(String title) {
int rgb = random.nextInt();
Color color = new Color(rgb);
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createLineBorder(color, 60));
panel.add(new JLabel(title));
return panel;
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
SwapPanels mainPanel = new SwapPanels();
JFrame frame = new JFrame("SwapPanels");
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();
}
});
}
}
答案 1 :(得分:0)
在remove方法之后,你必须运行所有的validate方法。代码将是这样的:
public void switchPanel(){
mainPanel.remove(introPanel);
mainPanel.add(questionPanel);
mainPanel.validate();
}
我希望有所帮助。萨拉姆