Reputation:
The code below shows my program that, when switches between methods home(), plus, minus(), times()
and divide()
, they removeAll()
of the corresponding JPanel
s , addPnl()
subPnl()
and so on - these being stores in a JDesktopPane
.
I'm quite new to Java, and the idea behind my code is so that it is a maths program: you press a button, the JFrame
removes the content from the JPanel
that was displaying at that moment, then display the correct JPanel
depending on what type of sum you want: addition, multiplication etc.
My issue is that, as you flip to the menu, then to another JPanel
, and back, and forth, it becomes slower and slower to flip to the new screen/JPanel
. Is there a way to avoid this?
There may be some bad practice in my code but, like I said, I'm fairly new and need to learn these things!
Many thanks.
I added JPanels
to a JDesktopPane
so I could have a background image on my 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 );
The different buttons link to different methods, all in my Class called 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; }
Each of the methods start with some declarations that removeAll()
of the content that are in JPanel
s: panels that would be linking to the method
public void plus(){
mainPnl.removeAll(); mainG.removeAll(); addPnl.removeAll();
Upvotes: 1
Views: 144
Reputation: 36423
Have you thought about a CardLayout, you can then create each different JPanel
and simply flip between your JPanel
s, it is better practice then removing all components from the JPanel
each time and adding new ones:
//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
Upvotes: 2