下面的代码显示了我的程序,当在方法home(),加号minus(),times()divide()之间切换时,它们分别是对应的removeAll() s,JPanel addPnl()等的subPnl() on-这些存储在JDesktopPane中。

我是Java的新手,我的代码背后的想法是让它成为一个数学程序:按下按钮,JFrame将从当时显示的JPanel中删除​​内容,然后显示正确的JPanel取决于所需的总和类型:加法,乘法等。

我的问题是,当您转到菜单,然后转到另一个JPanel并来回移动时,转到新屏幕/ JPanel的速度越来越慢。有办法避免这种情况吗?

我的代码中可能有一些不好的做法,但是,就像我说的那样,我还很新,需要学习这些东西!

非常感谢。

我在JPanels上添加了JDesktopPane,所以我的JFrame上可以有背景图片:

desk.add( bgImg , new Integer( 50 ) );
desk.add( mainPnl , new Integer( 350 ) );
desk.add( mainG , new Integer( 350 ) );
desk.add( addPnl , new Integer( 350 ) );
desk.add( subPnl , new Integer( 350 ) );
desk.add( mulPnl , new Integer( 350 ) );
desk.add( divPnl , new Integer( 350 ) );
setLayeredPane( desk );


不同的按钮链接到不同的方法,所有这些在我的类中都称为MiniMain

public void actionPerformed( ActionEvent event ){

if( event.getSource() == addBtn ) { plus(); }
if( event.getSource() == subBtn ) { minus(); }
if( event.getSource() == mulBtn ) { times(); }
if( event.getSource() == divBtn ) { divide(); }
if( event.getSource() == menuBtn ) { home(); }
if( event.getSource() == noteBtn ) { MiniPad.pad(); return; }


每个方法都以一些声明开始,这些声明声明了removeAll()内容的JPanel:将链接到该方法的面板

public void plus(){
mainPnl.removeAll(); mainG.removeAll(); addPnl.removeAll();

最佳答案

考虑过CardLayout之后,您可以创建每个不同的JPanel并在JPanel之间进行切换,这是一种更好的做法,那就是每次从JPanel中删除​​所有组件并添加新的组件:

//Where instance variables are declared:
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";

//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...

//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
...

getContentPane().add(cards, BorderLayout.CENTER);//add card panel to frame
setVisible(true);//show frame

CardLayout cl = (CardLayout)(cards.getLayout());//get cards
cl.show(cards, BUTTONPANEL);//switch cards to button JPanel

09-30 15:49
查看更多