How can I hide a JPanel?

I have some JPanels and using the mouse motion listeners you can scribble on them. I want to be able to switch between these panels but the problem is the drawings get wiped off when I use repaint() and frame.add(panel).
Any ideas how else I could try doing this?

Ok thanks everyone. I've taken the MyPanel class from here http://java.sun.com/docs/books/tutorial/uiswing/painting/step3.html
class MyPanel extends JPanel {
    private int squareX = 50;
    private int squareY = 50;
    private int squareW = 20;
    private int squareH = 20;
    public MyPanel() {
        setBorder(BorderFactory.createLineBorder(Color.black));
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                moveSquare(e.getX(),e.getY());
        addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                moveSquare(e.getX(),e.getY());
    private void moveSquare(int x, int y) {
        int OFFSET = 1;
        if ((squareX!=x) || (squareY!=y)) {
            repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
            squareX=x;
            squareY=y;
            repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
    public Dimension getPreferredSize() {
        return new Dimension(250,200);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);      
        g.drawString("This is my custom Panel!",10,20);
        g.setColor(Color.RED);
        g.fillRect(squareX,squareY,squareW,squareH);
        g.setColor(Color.BLACK);
        g.drawRect(squareX,squareY,squareW,squareH);
}Now if I use this class to make two panels, how can I hide one and bring the other one up and vice versa, using two buttons? setVisible() still doesn't work properly.
Here's the whole code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;
public class PanelTest extends JFrame {
    private MyPanel panelOne;
    private MyPanel panelTwo;
    private BorderLayout layoutManager;
    private PanelTest() {
        layoutManager = new BorderLayout();
        this.setLayout(layoutManager);
        panelOne = new MyPanel();
        panelTwo = new MyPanel();
        panelOne.add(new JLabel("This is Panel One"));
        panelTwo.add(new JLabel("This is Panel Two"));
        setCurrentPanel(panelOne);
        JButton switchButton = new JButton("Switch");
        switchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(getCurrentPanel() == panelOne) {
                    setCurrentPanel(panelTwo);
                } else {
                    setCurrentPanel(panelOne);
        this.getContentPane().add(switchButton, BorderLayout.SOUTH);
        this.pack();
        this.setVisible(true);
    private void setCurrentPanel(MyPanel panel) {
        this.getContentPane().add(panel, BorderLayout.CENTER);
        panel.revalidate();
        panel.repaint();
    private JPanel getCurrentPanel() {
        return (JPanel)layoutManager.getLayoutComponent(BorderLayout.CENTER);
    public static void main(String[] args) {
        new PanelTest();
class MyPanel extends JPanel {
    private int squareX = 50;
    private int squareY = 50;
    private int squareW = 20;
    private int squareH = 20;
    public MyPanel() {
        setBorder(BorderFactory.createLineBorder(Color.black));
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                moveSquare(e.getX(),e.getY());
        addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                moveSquare(e.getX(),e.getY());
    private void moveSquare(int x, int y) {
        int OFFSET = 1;
        if ((squareX!=x) || (squareY!=y)) {
            repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
            squareX=x;
            squareY=y;
            repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
    public Dimension getPreferredSize() {
        return new Dimension(250,200);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);      
        g.setColor(Color.RED);
        g.fillRect(squareX,squareY,squareW,squareH);
        g.setColor(Color.BLACK);
        g.drawRect(squareX,squareY,squareW,squareH);
}Edited by: atom.bomb on Mar 30, 2010 11:25 AM

Similar Messages

  • How can I hide the class file ??

    Hi !
    I has a question, when i write a program of Java, then use the command "javac" to compiler to class file for other people using, but the class file can be disassembled and convert to source code. How can I hide the class file and let people can not disassemble, or can not see the source code. Thinks

    See these....
    http://www.saffeine.com/
    http://www.jarsafe.com/
    I recently read this. This will help you.
    http://developer.java.sun.com/developer/qow/archive/160/index.jsp
    Enojy....
    Rajesh

  • How can i hide my extension number when i make outgoing calls

    Hi All,
    How can i hide my extension number when i make outgoing calls,what configuration should i make on the call manager server.
    Regards,
    Lester

    We use a Route Pattern that mimics the telco feature *67. The RP is *679.xxxxxxx with a Transformation mask of 000000000 (just to get beyond the individual blocking on some private lines.

  • How can I hide a field a table from SE16

    Hi all,
    I have an urgent requirement, can anyone help me? How can I hide or mask any field of a table from SE16. Also how can I restrict the user not to put a restriction on a particular field of a table so that this field should not be accessed for SQVI/SQ01.
    Awaiting for reply.
    Useful answers will be rewarded immediately with full points.
    Tnx.

    You could hide the column, by using the standard functinoality of the ALV output, you would need to hide the column, and save a default layout.  This way the next time you come into this display, the column will not be there.
    Regards,
    Rich Heilman

  • How can I hide a text label as I would a control or indicator?

    As I have multiple indicators that must have the same identifier to the operator I can not use the indicator label as the items identifier. At times I want to hide the indicator and label. How can I hide the label? Please recall a text label just sits on the front panel as desired. It isn't within a raised or lowered box. In the attached sample I would like to hide "MyLabel" when the date indicator is hidden.
    Attachments:
    Test_Label.vi ‏35 KB

    Here�s a way. Its a little involved, but it will work:
    1. Customize a control or indicator to remove the border (I used a string control)
    a. Right click on the control or indicator, go to �Advanced � Customize�
    b. Click on the wrench on the tool bar to enter edit mode
    c. Select the border and drag it off to the side
    d. Reduce the size of the border to a single pixel (it won�t let you delete it)
    e. Rubber band a box around the 1 pixel border to select it and use the cursor keys to move it within the �white space� of the string control. It will effectively disappear. You will NOT be able to move it with the mouse as LV will try to resize the border instead of moving it.
    f. Using the color tools �suck up� the background color of your vi and �paint� i
    t into the white space of the control.
    g. Make the control the correct size to hide your label(s). Make sure it is right as you will NOT be able to resize the control outside of the �customize� function (i.e.: while on your front panel)
    h. Click on the tweezers to go back to customize mode.
    i. Give your control a descriptive name
    j. Right click on the control, go to �Visible Items� and uncheck �label� to hide the label.
    k. Save your new control
    2. Back on your front panel, place your new control over what you want to hide and programmatically make it visible or invisible as desired.
    I have included a copy of your original vi, modified to hide and unhide your label. I have also included the customized string control that accomplishes this. You may resize the control as needed by �customizing it as described above.
    The only disadvantage to this method is that if you want to hide multiple labels they must be in the same area of the front panel. Otherwise you must have seve
    ral �hiding� controls.
    An advantage is that you will not have to make the original control or indicator (i.e.: the date indicator) visible or invisible as it can be hidden as well.
    Hope this does what you want.
    Good Luck.
    Attachments:
    Test_Label.vi ‏27 KB
    InvisibleString.ctl ‏6 KB

  • How can i hide a tex message on my screen? i have a 4s?

    how can i hide a tex message on my screen when my phone is locked? i have the 4s

    Settings>Notifications>Messages>View in Lock Screen>OFF
    Message was edited by: The Huntress

  • How can i hide a pages file from other users

    How can I hide a pages file so other users can't open or see it?

    My own tip is to save this kind of doc in an encrypted disk image (the .dmg items)
    Such item resemble to every downloaded installer so it doesn' take special attention and the encryption scheme is an efficient one.
    Yvan KOENIG (VALLAURIS, France) dimanche 21 août 2011 14:53:01
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • How can i hide a folder?

    how can i hide a folder?

    I know nothing about it, but you can get is an application for it.

  • How can i hide a column using personalization?

    Hi,
    Please help me how can i hide a one column in oracle forms using personalization?
    Thanks

    Hi,
    When you login to My Oracle Support website, enter "458786.1" or "468657.1" in the search box, and you should get the documents.
    Or, use the direct links below to access those documents.
    How To Do Forms Personalization (Doc ID 468657.1)
    https://supporthtml.oracle.com/ep/faces/secure/km/DocumentDisplay.jspx?id=468657.1
    RCVRCERC: When Using Personalization to Remove a Column Receive Error FRM-41017: Cannot set UPDATE ALLOWED (Doc ID 458786.1)
    https://supporthtml.oracle.com/ep/faces/secure/km/DocumentDisplay.jspx?id=458786.1
    Regards,
    Hussein

  • How can i hide a JFrame and then Show it again in runtime

    How can i hide a JFrame and then Show it again in runtime??
    Please, please help me
    Its URGENT

    Here's even an example:
    import javax.swing.*;
    public class HideAndShow extends JFrame
         public HideAndShow()
              super("Hello");
              setSize(200, 200);
              setVisible(true);
              try
                   Thread.sleep(2000);
              } catch(InterruptedException e) {}
              setVisible(false);
              try
                   Thread.sleep(2000);
              } catch(InterruptedException e) {}
              setVisible(true);
         public static void main(String[] args)
              new HideAndShow();
    The JFrame will show, then hide, then show again. This is at runtime.

  • How can I hide a worksheet in a workbook in Numbers 1.5 for iPad?

    How can I hide a worksheet in a workbook in Numbers 1.5 for iPad 2?

    Numbers for the pad, as near as I can tell, does not do hidden sheets.  There are some options though.
    1. You can narrow the columns to the point that they are unreadable.
    2 you can open and store those sheets is a different app, such as docs to go or quickoffice.  Bury that app in a folder that would not be found easily.
    To see the numbers help section, open numbers, tap the wrench and tap help. 

  • How can I hide early morning hours in iCal?

    how can I hide early morning hours in ical??? i'm sleeping at those hours and i really don't need to see them. it would give me a lot more space to see what really matters if i could define myself what hours i would like ical to show. i saw an old post that is locked and doesn't help. also searched the web and didn't find anything. i would be great to solve this very annoying problem. thanks!

    yes, it seems so. i guess we can't modify that.  =/  maybe some crazy script or programming thing... or something like that would do it, though.

  • How can i hide elements of a view?

    Hi,, i've got a question about, how can i hide an element of a view?, this element colud be a group, a label, an input field, any element that i can put in the view layout.
    My view has an ALV, an inputfield and a Table with a button, so when i click on a line of the alv, it shows data in the table and in the inputfield, and when i click on the button of the table, i want to hide the table and the inputfield, until i clik on the alv again to make appear  the table and the inputfield.
    how can i hide those element?,,,,,,,,thanks

    Hi Luis Garcia,
    It can be done easily by <b>context binding</b> the visibility property of the table and input field UI element to a node attribute whose type would be WDY_BOOLEAN.
    1. Initially the node attributes default value would be 'X'.
    2. When you click the button in the ALV, in the event handler of that button change the binded node attribute value to ' '.
    3. When on lead selection of the table again change the binded node attribute field value to 'X'.
    4. Below is the sample code to read the binded node attribute and toggle the visiblity attribute to 'X' if it is ' ' and vice versa.
      data:
        Node_If                             type ref to If_Wd_Context_Node,
        Elem_If                             type ref to If_Wd_Context_Element,
        Stru_If                             type If_Main=>Element_If ,
        Item_VISIBILITY                     like Stru_If-VISIBILITY.
    * navigate from <CONTEXT> to <IF> via lead selection
      Node_If = wd_Context->get_Child_Node( Name = IF_MAIN=>wdctx_If ).
    * get element via lead selection
      Elem_If = Node_If->get_Element(  ).
    * get single attribute
      Elem_If->get_Attribute(
        exporting
          Name =  `VISIBILITY`
        importing
          Value = Item_Visibility ).
    if Item_visibility is initial.
    item_visibility = 'X'.
    else.
    item_visibility = ' '.
    endif.
      Elem_If->set_Attribute(
          Name =  `VISIBILITY`
          Value = Item_Visibility ).
    endmethod.
    Hope it helps.
    Regards,
    Maheswaran.B

  • How can you hide a Continue button until all clickboxes are clicked?

    I have seen similar questions to this one, but none seemed to be the exact situation as mine.
    What I have: Several images on a screen.  When a user clicks an image it is replaced with another image.  I am using clickboxes for this task.  I do not wish for them to toggle back and forth. Once they click the original image it should stay changed.
    What I am trying to do: Once a learner clicks all the images (in no particular order) a Continue button appears that allows them to go to the next screen.
    If anyone has some suggestions on this situation please let me know, thanks.

    I cannot log in on the forum for the moment, so will try by answering by
    mail. I was aware of that problem (have presented those solutions so
    often), thought that since you left all images visible once the click box
    was clicked it wouldn't be a problem.
    Two possible solutions:
       1. Easiest one: add a statement in the Always decision that will Hide
       the click box just clicked. It has no sense to click it another time. That
       will mean that you still can do it with a shared action but that shared
       action will have two parameters now, the second one being the click box
       that has to adapted on each application of the shared action.
       2. If you don't want to make the click box hidden (which means at the
       same time disabled), you'll need a user variable for each click box,
       starting with a default value of 0, and toggle it in the Decision 'Always'
       to 1. The second decision will then need a condition that checks the value
       of all the user variables (with AND) and shows the Next button only when
       all variables have the value of 1.
    Sorry, but have to mail, cannot offer a screenshot in that case.
    Lilybiri
    2014-03-13 5:31 GMT+01:00 Joseph_McDonald <[email protected]>:
        Re: How can you hide a Continue button until all clickboxes are
    clicked?  created by Joseph_McDonald<http://forums.adobe.com/people/Joseph_McDonald>in *Advanced
    Adobe Captivate Users* - View the full discussion<http://forums.adobe.com/message/6205043#6205043

  • How can I hide file names in a photostream?

    How can I hide file names in a shared photo stream on icloud.  I don't want people to see how many pictures I take at an event.  Can this be done to pictures already posted?

    The Shared Photo Stream uses the filename of the original image file as the title that is shown in the stream.  If you want to hide the original filename, export the image to a folder in the Finder, rename it, then reimport it to share it.  You can rename the files directly when exporting.
    Or, if you do not mind to change the names of the originals in Aperture use the command "Metadata > Batch change" and change the title of the image, with the option "Apply to Original file" enabled and "Add metadata from" set to "None".
    To rename the photos already shared, delete them from the Shared Album and share them again.

Maybe you are looking for

  • Workbook funs from Disco Desktop but errors out in PLUS

    Hi, Let me start by saying that I read the previous thread on this topic from September 2008 but have not yet found a solution. There is an existing report of Unpaid Invoices that uses folders from Accounts Payable (AP Payment Schedules, Invoices, Su

  • HELP ! LCD DISPLAY IS ONLY BLACK AND WHITE ???

    Currently using a macbook pro, on startup the boot up screen is in colour, but when in the operating system everything becomes black and white, have tried all display settings can anyone shed some light on the situation ? Regards Marshy

  • Can you retrieve a conversation off a deleted acco...

    Can you pay Skype to retrieve deleted conversations off a deleted Skype account?

  • JComboBox listener problem

    Hi all, I have following problem, i use combobox and i need to write listener for selecting item. But both ActionListener and ItemListener are unusable for me, because i dont know how to differ between selecting item when combobox is poped up. I dont

  • Data Type  Binary Missing on ODI  for 101.3.4 for SYBASE IQ 12.5

    Hi All. Under Topology - Physical Architecture - Sybase IQ - there isn't datatype "binary". Any workaround ? I have to use this datatype because it is in many tables and it used for important data... Marco