Best way to add and remove JPanels?

I have a question on the best practice in removing and then adding JPanels. I know a few ways about doing it but it never seems to work just how I want it to. Any help would be great. Also if anyone wants to give tips on better ways of writing this code I am out your any ideas.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
class test2 extends JFrame implements ActionListener {
    private static final int FRAME_WIDTH    = 575;
    private static final int FRAME_HEIGHT   = 500;
    private static final int FRAME_X_ORIGIN = 150;
    private static final int FRAME_Y_ORIGIN = 250;
    //jbutton
    String [] foodButton = {"Tofu Burger",   "Cajun Chicken",
                            "Buffalo Wings", "Rainbow Fillet",
                            "Rice Cracker",  "No Salt Fries",
                            "Zucchini",      "Brown Rice",
                            "Cafe Mocha",    "Cafe Latte",
                            "Espresso",      "Oolong Tea"};
    JButton b[]          = new JButton[foodButton.length];
    JButton orderButton  = new JButton("Order");
    JButton cancelButton = new JButton("Cancel");
    JButton backButton   = new JButton("Back");
    int [] foodCount     = new int [12];
    double [] foodCost   = {3.49, 4.59,
                            3.99, 2.99,
                            0.79, 0.69,
                            1.09, 0.59,
                            1.99, 1.99,
                            2.49, 0.99};
    double subtotal;
    JPanel outPut         = new JPanel();
    JLabel test           = new JLabel ("Subtotal: ");
    //constructor
    public test2() {
        setContentPane(outPut);
        foodButton();
        frame();
        setVisible(true);
    //frame
    public void frame() {
        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setResizable(true);
        setTitle("Welcome to Low Fat Burger");
        setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
    //button builder
    public void foodButton() {
        ImageIcon myIcon = new ImageIcon("C:/Documents and Settings/Keith/My Documents/My Pictures/Clip Art/lowFatBurger.jpg");
        JPanel header    = new JPanel();
        JPanel menu      = new JPanel();
        JPanel bottom    = new JPanel();
        JPanel subtotal  = new JPanel();
        JPanel itemCount = new JPanel();
        JPanel control   = new JPanel();
        outPut.setLayout(new BorderLayout(0, 0));
        //outPut.setBorder(BorderFactory.createLineBorder(Color.red));
        outPut.add(header,   BorderLayout.NORTH);
        outPut.add(menu,     BorderLayout.CENTER);
        outPut.add(bottom,   BorderLayout.SOUTH);
        header.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        header.add(new JLabel(myIcon));
        menu.setLayout(new GridLayout(4, 3));
        //test.setLayout(new FlowLayout());
        //test.setBorder(BorderFactory.createLineBorder(Color.red));
        for(int i=0; i<foodButton.length; i++) {
            b[i] = new JButton (foodButton);
//work area
b[i].addActionListener(this);
menu.add(b[i]);
//add actionlistener to control buttons
orderButton.addActionListener(this);
cancelButton.addActionListener(this);
backButton.addActionListener(this);
bottom.setLayout(new BorderLayout(0, 0));
bottom.add(subtotal, BorderLayout.NORTH);
bottom.add(itemCount, BorderLayout.CENTER);
bottom.add(control, BorderLayout.SOUTH);
subtotal.add(test);
control.add(orderButton);
control.add(cancelButton);
public void actionPerformed(ActionEvent event) {
String straction = event.getActionCommand();
//format
DecimalFormat df = new DecimalFormat("0.00");
for(int j=0; j<foodButton.length; j++) {;
if(event.getSource() == b[j]) {
int count = ++foodCount[j];
double itemSubtotal = count * foodCost[j];
for(int i=0; i<foodButton.length; i++) {
subtotal = (foodCount[i] * foodCost[i]);
test.setText("Subtotal: $" + df.format(subtotal));
if(straction.equals("Cancel")) {
}else if(straction.equals("Order")) {
//menu.removeAll();
//control.removeAll();
//control.add(orderButton);
//control.add(backButton);
//menu.revalidate();
//menu.repaint();
}else if(straction.equals("Back")) {
public static void main (String[] args) {
new test();

If you want a really cheap way to go about it, you could try setVisible(false) instead of removing the panel. It will result in the same visual effect, and if you ever need to add the component back, you just need to setVisible(true) again.
But make sure you do it inside the event loop...
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        panel.setVisible(false);
});

Similar Messages

  • How do I delete music from my iPhone and what is the best way to add and delete music?

    How do I delete music from my iPhone and what is the best was to add and delete music to the iPhone?

    See Here...
    iPhone User Guide
    and here
    http://www.apple.com/support/iphone/syncing/

  • Best way to backup and remove an iMovie Project?

    Hi all,
    i am curious of the best way to backup (to external drive) and then remove an iMovie Project from the Mac laptop?

    still curious about this...

  • What is the best way to add and use custom fonts with Eloqua?

    We have a custom font that we'd like to use with Eloqua and were wondering how others might have successfully approached this.

    ~~Disclaimer: This answer refers to email fonts only - landing page font imports are discussed below~~
    Hi Brett,
    I took a look at these two posts: Re: Tips for getting the E10 email editor to change the email font for Outlook & other old-school email clients? and Re: E10 Fonts
    It seems that there are reasons as to why only a few of the fonts are supported. You can drill down into the source code to edit the font type, but I'm not sure that will get you anywhere.
    To drill down:
    To get the desired font & size in various clients (Gmail, Hotmail, Yahoo, Outlook) I found that specifying in the html works best.
    So whether it’s a P or TD, tag I add the style attribute & specify the font along with color & size.
    e.g.:
    <td style="LINE-HEIGHT: 18px; FONT-FAMILY: Arial, Helvetica, sans-serif; COLOR: #000000; FONT-SIZE: 12px;">
    Of course if you use the WYSIWYG editor you will have to view the html source & add this.

  • What is the best way to find and remove unneeded language files from Mac OS X 10.8.4?

    I have tried Spring Cleaning and it finds the files and then quits!

    You can do this with a *FREE* utility called Monolingual.  Another app that apparently does all the work for you.  I’ve used it since Tiger w/never any problems.  Just make sure you read all of the instructions.
    However, there is a warning for *native English speakers*. Make sure you keep BOTH English and English (United States).
    Works on OS X 10.8 (Mountain Lion)

  • Best practice for adding and removing eventListeners?

    Hi,
    What is the best practice in regards to CPU usage and performance for dealing with eventListeners when adding and removing movieclips to the stage?
    1. Add the eventListeners when the mc is instantiated and leave them be until exiting the app
    or
    2. Add and remove the eventListeners as the mc is added or removed from the stage (via an addedToStage and removedFromStage listener method)
    I would appreciate any thoughts you could share with me. Thanks!
    JP

    Thanks neh and Applauz78.
    As I understand it, the main concern with removing listeners is to conserve memory. However, I've tested memory use and this is not really an issue for my app, so I'm more concerned if there will be any effect on CPU (app response) if I'm constantly adding and removing a list of listeners every time a user loads an mc to the stage, as compared to just leaving them active and "ready to go" when needed.
    Is there any way to measure CPU use for an AIR app on iOS?
    (It may help to know my app is small - I'm talking well under 100 active listeners total for all movieclips combined.)

  • HT1364 I just bought a new PC and now have ample space on my C drive to house my music Library which is currenlty installed on a external drive.  What is the best way to install and move the itunes library to my C Drive?

    I just bought a new PC and now have ample space on my C drive to house my music Library which is currenlty installed on a external drive.  What is the best way to install and move the itunes library to my C Drive?

    If the entire library is on the external drive then simply copy the iTunes folder into <User's Music> on the new computer, then install iTunes. If you've already installed iTunes you will want to remove the empty iTunes folder in <User's Music> first.
    If it turns out you only have the media folder on the external drive then take a look at this post...
    tt2

  • What is the best way to add text to an image

    I used the draw ap div to add text to an image.  will that cause any problems?  If so, what is the best way to add text to an image?  Thanks!

    APDivs will kill your design unless you fully understand the css behind the scenes and plan accordingly. They really are completely unnecessary in the vast majority of situations.
    An easy way to add "web text over an image" would be to use the background-image attribute in css for a standard <div> tag, then just add the text within that same <div>.
    Something like this in the css (if you are using a 300x300 pixel image)...
    #yourdiv {
         background-image:url(yourpic.jpg);
         width:300px;
         height:300px;
    And then this in the html...
    <div id="yourdiv">Your text here</div>
    You would then position the <div> using css margins, floats and padding. Using position:absolute (APDivs) is typically something that will blow your design to pieces if the viewer changes their browser settings.

  • What is the best way to add hard disk space to macbook pro?

    I'm running out of disk space on my macbook pro. What is the best way to add disk space?

    another way of doing it is to replace your hard drive with a larger one.
    if you're technically capable, it takes 10 minutes for the swap and an hour minimum to clone your hard drive or do a data transfer.  all depends on how much data there is to trandfer or to clone.
    good luck.

  • UDO: Add and Remove rows to/from Matrix.

    Hi all,
    Yes, I know there are lots of topics about adding and removing rows but I was having trouble with these and I need some expert's opinion.
    I'm working with a Document type UDO, with 1 header table (ADAT_ONR) and 1 child table (ADAT_NR1 -  MatrixUID = "mtx_NR").
    I add the first row when the user chooses the business partner.
    If oMatrix.RowCount = 0 Then
         oMatrix.AddRow()
          oMatrix.AutoResizeColumns()
         oMatrix.Columns.Item("V_LineId").Cells.Item(1).Specific.Value = 1
    End If
    Then, the user has to press the AddRow button to add new rows, and the user can only add 1 new blank row. Later I'll change the row adding behavior to mimic B1s.
                If pVal.BeforeAction = False Then
                    Select Case pVal.ItemUID
                        Case "AddRow"
                            'ItemHandler_Click = AddRow(oCompany, oApplication, oForm, oForm.Items.Item("mtx_NR").Specific.RowCount())
                            oMatrix = oForm.Items.Item("mtx_NR").Specific
                            If oMatrix.RowCount > 0 Then
                                If Trim(oMatrix.Columns.Item("V_PltCode").Cells.Item(oMatrix.RowCount).Specific.Value) = "" Then
                                    oApplication.StatusBar.SetText(TranslateStr(oApplication, MustChoosePallet), BoMessageTime.bmt_Short)
                                    Exit Function
                                End If
                            End If
                            ItemHandler_Click = NewLine(oCompany, oApplication, oForm)
                            Exit Function
        Private Function NewLine(ByRef oCompany As SAPbobsCOM.Company, ByRef oApplication As SAPbouiCOM.Application, _
            ByRef oForm As SAPbouiCOM.Form) As Boolean
            NewLine = False
            Try
                oMatrix = oForm.Items.Item("mtx_NR").Specific
                Dim Index As Integer = oMatrix.RowCount
                With oForm.DataSources.DBDataSources.Item("@ADAT_NR1")
                    .Clear()
                End With
                oMatrix.AddRow()
                oMatrix.Columns.Item("V_LineId").Cells.Item(Index + 1).Specific.Value = (Index + 1).ToString
                oMatrix.FlushToDataSource()
                oMatrix.LoadFromDataSource()
                oForm.Refresh()
                NewLine = True
            Catch ex As Exception
                oApplication.MessageBox("NewLine(): " & oCompany.GetLastErrorCode.ToString & ", " & ex.Message)
            End Try
        End Function
    When I Add or Update the data, I clear the last blank row, if it exists.
               '// In the Click Event
               If pVal.BeforeAction = True Then
                    Select Case pVal.ItemUID
                        Case "1"
                            If oForm.Mode <> BoFormMode.fm_FIND_MODE Then
                                oMatrix = oForm.Items.Item("mtx_NR").Specific
                                oMatrix.FlushToDataSource()
                                oMatrix.LoadFromDataSource()
                                If Trim(oMatrix.Columns.Item("V_PltCode").Cells.Item(oMatrix.RowCount).Specific.Value) = "" Then
                                    oForm.DataSources.DBDataSources.Item("@ADAT_NR1").RemoveRecord(oMatrix.RowCount - 1)
                                    oMatrix.DeleteRow(oMatrix.RowCount)
                                    'oMatrix.FlushToDataSource()
                                End If
                            End If
                    End Select
    My question is, Is there an easier way to Add and Delete Rows??
    BTW, I still have a problem so solve. With this code, when the user deletes a row the row numbering is incorrect. Example: if I have to rows in a matrix and I delete row nº1, row nº2 will hold the same number...
    Any Ideas?
    Thanks in advanced,
    Vítor Vieira

    Hi Victor,
    there is a Form Data event which you ca use in that try to write the code for adding a row after updating and delete a row while inserting and add a row while traversing.
    sample code.
    Sub FormDataEvent(ByRef BusinessObjectInfo As SAPbouiCOM.BusinessObjectInfo, ByRef BubbleEvent As Boolean)
            Try
                Select Case BusinessObjectInfo.EventType
                    Case SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD, SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE
                        If BusinessObjectInfo.BeforeAction = True Then
                            objForm = objMain.objApplication.Forms.Item(BusinessObjectInfo.FormUID)
                            oDBs_Head = objForm.DataSources.DBDataSources.Item("@Header")
                            oDBs_Detail= objForm.DataSources.DBDataSources.Item("@Line")
                            objMatrix = objForm.Items.Item("83").Specific
                            If objMatrix.VisualRowCount <> 0 Then
                                objMatrix.DeleteRow(objMatrix.VisualRowCount)
                                objMatrix.FlushToDataSource()
                            End If
                            If BusinessObjectInfo.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD Then
                                End If
                        ElseIf BusinessObjectInfo.ActionSuccess = True Then
                            objForm = objMain.objApplication.Forms.Item(BusinessObjectInfo.FormUID)
                            If BusinessObjectInfo.EventType =                    SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE Then
                                objMatrix = objForm.Items.Item("83").Specific
                                objMatrix.AddRow()
                                SetNewLineCharge(objForm.UniqueID, objMatrix.VisualRowCount)
                                objMatrix.FlushToDataSource()
                              End If
                        End If
                    Case SAPbouiCOM.BoEventTypes.et_FORM_DATA_LOAD
                        If BusinessObjectInfo.ActionSuccess = True Then
                            oDBs_Head = objForm.DataSources.DBDataSources.Item("@Header")
                           oDBs_Detail = objForm.DataSources.DBDataSources.Item("@Line")
                            objMatrix = objForm.Items.Item("83").Specific
                            objMatrix.AddRow()
                            SetNewLineCharge(objForm.UniqueID, objMatrix.VisualRowCount)
                            objMatrix.FlushToDataSource()
                           End If
                End Select
                End Sub
    Hope this helps,
    OM Prakash

  • Add and Remove rows

    Hi,
    I have 2 tables, and I needed to add/remove some rows from the first table to the second.
    I've followed the tutorial: Link: [Add and Remove from a List|http://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/927d8c3c-0a01-0010-57b4-e89f505e2bff] and it works great!
    But the user can add two or more times the same row, so I need to avoid that. The user should be able to add every row only once!!
    I thought about some condition on button Add (for example, disable the ADD button if the same row is present in both tables, but it didnt work).
    Any ideas to achieve that?
    Thanks in advance!
    Best Regards
    Marcelo.

    Hi again Ahmed
    I've solved my problem, but now I'm facing a new issue about the same topic. 
    Following your tips, I've found a solution, but now, I need to copy a complete field of a table to the data store.
    For example, my table has 4 field (country, key, name and city), and I need to copy ALL the key values to the data store. So, if I have 4 rows in the table, let's say "key1", "key2", "key3", "key4"
    I've reached a solution, but it involves to walk throught the entire table, selecting every row automatically (I use a spinner) and "copying" every key field of every row to the data store. When I say "copying" I mean adding it to the same virtual field of the data store, that is to say, concatenating the key values one after another.
    The problem arises when the table has more than 100 records, because 100 is the top value that a spinner can reach.
    Any ideas about can bypass that limit?
    Thanks in advance, your help is really appreciated.
    Best regards
    Marcelo

  • Add and Remove Publishers from Replication Monitor using T SQL

    Is there any possibility to add an Publishers from Replication Monitor using T SQL.i am trying to configure the replication using T SQL..i can create all other steps but didn't find any way to add publisher to the replication monitor..kindly suggest..

    Hi Snehasis,
    Tom is correct, there is no T-SQL command to add a publisher to Replication Monitor.  However, the server from which you launch Replication Monitor will automatically be added to Replication Monitor if it is a Publisher.  Also, you can add additional
    Publishers using the Add Publisher dialog.
    This is covered in
    Add and Remove Publishers from Replication Monitor
    Brandon Williams (blog |
    linkedin)

  • Uninstall firefox after trying add and remove akso Mozilla,s instructions

    I am using Mozilla Firefox version !8.0(x86 en gb on windows Xp) I wish to un-install Mozilla Firefox. I tried the usual "Add and Remove" from Control Panel, this did not work which in its self is odd. I then tried the Mozilla site and followed those instructions which failed also.It makes me feel uncomfortable that removing a program is made so difficult
    Please advise
    Mike R

    Seeing a couple of errors in the system log is not that unusual, but the number you are seeing is indicating a real problem.
    Did you double-click any of the errors in System Events? It would open a pop-up and give more detailed information on the error and usually has a link to the Microsoft help website concerning that specific error. It is likely the "msi" error is significant, as that is a Microsoft installer file (often used for uninstall also). It seems that either Control Panel is messing up or the msi process is crashing for some reason. The information in that error may contain the answer. If there are error numbers, you could do a search for that error number.
    When you say you "re-formatted" your computer, what exactly do you mean? Did you re-install Windows?
    SparkTrust PC Cleaner could possibly be the culprit. Security software, by design, watches for processes that try to make changes to your computer. Along with cleaning, it also claims to "optimize" the registry, which can lead to big trouble if a critical key is removed by accident. I use Registry Mechanic, but with any cleaner, I never allow it to make changes until I have a chance to examine each proposed change. The first "automatic" registry cleaner I used 15 years ago did severe damage to my machine. Windows became unbootable because of registry damage. I ended up having to re-install Windows from scratch.
    PC Cleaner should not have disabled System Restore. If you haven't made any large installs or changes, System Restore simply may not have created a restore point. But there should have been at least the original when you installed Windows. To verify the settings, right click on "My Computer" and choose "Properties". There should be a System Restore tab where you can verify the allowed size and whether or not it is active.
    It is generally a good idea to manually tell System Restore to create a restore point on occasion, on a day when everything is working as it should.
    Is there a way to temporarily disable SparkTrust? It might be possible it sees the uninstall action as some kind of malware and won't allow it to run. That is simply a guess, but it is generally good policy to disable active security software during an installation (of trusted software), as the security software may interfere with the processes.
    I really don't believe Firefox is the culprit here. I think there is a problem with Windows. I have been using Firefox for well over a decade and have never had an uninstall problem.
    If you can copy and paste error details for the event log, I may be able to learn more.

  • Trouble with parallel add and remove effect in TileList

    We have a TileList of images.  As the user drags a new image along the list (deciding where to drop it) a blank frame drops in to show them where it will be inserted when they drop it.  Therefore, I have to add and remove simultaneously, while still dragging.  For example if they are at index zero, a blank frame is in index zero.  As they move to 1, the blank frame appears to move from index zero, to index one, as the image that was at index one appears to move to index zero.  But what I'm really doing is just removing and then adding the blank frame.
    I think the following code should accomplish this.  And it works, most of the time.  Every so often, there is a delay where is does the REMOVE, and then waits until the Back.easeOut tween is complete, and then does the ADD.   It is intermittent.  Any ideas, or is there a better way to do it?  Thanks
    MXML code:
        <mx:Sequence id="myEffect">
            <mx:Parallel>
                <mx:Move
                    duration="600"
                    easingFunction="{Back.easeOut}"
                    />
                <mx:RemoveItemAction id="dcmRemoveItemActionTag"
                                     />
                <mx:AddItemAction  id="dcmAddItemActionTag"
                                   />
            </mx:Parallel>
        </mx:Sequence>
    actionscript code:
                    _sharedMedia.removeItemAt(_sharedMedia.getItemIndex(_dropPlaceHolderimage));
                    _sharedMedia.addItemAt(_dropPlaceHolderimage,dropIndex);

    hi,
    You could do this a couple of ways, you could have a slight delay set on the remove effect so that it doesn't interfere with the ease function.
    or
    You could add the item instead of an empty frame, on the dragdrop event you don't need to do anything if you get a dragexit triggered then you simply remove the item completely.
    David

  • Best way to add a new section in the middle of a tune?

    hi,
    what's best way to add a new section in the middle of a tune? I think I came up with an interesting transition to a tune... what's the best way to try it out?
    please be specific. if it's just select all and cut and move - I already know that one. somehow, I bet there's a better way.
    thanks in advance...

    You should be able to enter the "in" and out" points in the transport bar. And then under the Region menu, choose "Cut/Insert time."
    So if, for instance, you go up to bar 32, and want to add 8 bars, enter 32 1 1 1 in the top transport place, and 40 1 1 1 in the second. Then select "Cut/Insert Time", and an 8 bar whole will be added to your song.
    Be aware that if there are overlapping MIDI notes found at that cut point, Logic will warn you about it, and give you some options. In this case, I think "Keep" would be what you'd want, but every situation is different...
    Hope that helps....

Maybe you are looking for

  • How to get the customized value of a Report portlet in a page

    Hi , I have a report portlet and it has a bind variable which users can customize when added to a page. There is a link to a Form page in the report , to which I need to pass the value of bind variable customized by the user. I used : portal30.wwv_na

  • All applications were "?" On the dashboard after time machine restore to new hard drive...what went wrong?

    Hi folks I used the cmd R option on booting the MBP and did a disk scan and it reported errors that could not be fixed/repaired. So I opted to install a brand new 1Tbyte Seagate hybrid hard drive and restore from my time machine backup. So I installe

  • Urgent Help - in using Escape character

    hai, i have problem in using escape character.. can anyone help me out in the same... sb.append(<jsp:getProperty name="resume_main" property="name"/>); //error i am getting is -- Missing term, ')' expected. pl help me out in using the escape characte

  • How to startup the iasconsole with R12.1.1

    Hi Guys, Platform: Linux Version: 12.1.1 I need to start the IASconsole with R12 as I need to do deployments. So I login as appsuser Set environment and run emctl start iasconsole. But after logging into the ias console.. I dont see anything or any a

  • Scenarios in BPM

    Guys, I have posted in SDN regarding what all scenarios i have to practice to work in a real time project, i got a good response.....Thanks for all of them. I have worked on File, Mail,JDBC,IDOC adaptors. Worked on Message mapping. Worked on File -fi