在框架中切换面板的最佳方法



我已经开始使用JFrames,我正在创建一个简单的程序,有3个不同颜色的面板,我只是想知道什么是在我的程序面板之间切换的最好方法。当选择具有颜色名称的JMenuItem时,将更改面板。我在看卡片,想知道它们是否是一个好的解决方案,是否有可能将它们应用到我的程序中?如有其他建议,我将不胜感激。抱歉,如果我做错了什么,我只是开始堆栈溢出,我是一个相当新的Java:)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Colour extends JFrame
{
CardLayout card;
JPanel childPanel =  new JPanel(), redPanel, bluePanel, greenPanel;
Container c;
public Colour(){
// Get Container
c=getContentPane();
//Create Menu and items
childPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu customer = new JMenu("Colour");
customer.setMnemonic(KeyEvent.VK_U);
JMenuItem blue = new JMenuItem("Blue");
JMenuItem red = new JMenuItem("Red");
JMenuItem green = new JMenuItem("Green");
customer.add(blue);
customer.add(red);
customer.add(green);
menuBar.add(customer);
this.setJMenuBar(menuBar);
//Adding panel to container
c.add(childPanel);
childPanel.setBackground(Color.PINK);
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
} 
} );
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
} 
} );
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
} 
} );}
//Creating my different panels and adding them to childPanel
public void redC() {

redPanel = new JPanel();
redPanel.setBackground(Color.RED);
childPanel.add(redPanel, "Red");


}
public void blueC() {
bluePanel = new JPanel();
bluePanel.setBackground(Color.BLUE);
childPanel.add(bluePanel, "Blue");

}
public void  greenC() {
greenPanel = new JPanel();
greenPanel.setBackground(Color.GREEN);
childPanel.add(greenPanel, "Green");
}
public static void main(String[] args) {
Colour cl=new Colour();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

代码差不多完成了。下面是工作代码。你需要在添加/删除面板后重新验证childPanel,以便它将被重新绘制:

//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() >0)
childPanel.remove(0);
blueC();
childPanel.revalidate();
}
});
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.removeAll();
redC();
childPanel.revalidate();
}
});
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.remove(0);
greenC();
childPanel.revalidate();
}
});

相关内容

  • 没有找到相关文章

最新更新