Switching Panels and good swing practice..Swi

Hi all,
I have a GUI in which one of the panels needs to change, based on what "mode" the program is currently in.
I've written code to do this but am wondering if it is good practice and if there are any easier ways you can suggest.
In particular, the use of validate/+revalidate+ and repaint. And also how I can use pack, because last time I tried it didn't work that well.
Thanks,
KrimsonEagl
public class SwitchingPanels extends JFrame implements ActionListener {
     private JDesktopPane desktopPane;
     private JPanel buttonPanel;
     private JPanel buttonPanelMain;
     private JPanel currentPanel = new JPanel();
     private enum Mode {
          MODE1, MODE2, MODE3
     private Mode mode = Mode.MODE1;
     private Map<Mode, JPanel> buttonMap;
     public SwitchingPanels() {
          // Set up GUI.
          super("Switching Panels");
          setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
          setSize(1024, 768);
          desktopPane = new JDesktopPane();
          add(desktopPane, BorderLayout.CENTER);
          buttonPanel = new JPanel();
          buttonPanel.setBorder(BorderFactory.createEtchedBorder());
          BoxLayout layout = new BoxLayout(buttonPanel, BoxLayout.Y_AXIS);
          buttonPanel.setLayout(layout);
          buttonPanelMain = new JPanel();
          ButtonGroup buttons = new ButtonGroup();
          addToggleButton(buttonPanelMain, buttons, "Mode1");
          addToggleButton(buttonPanelMain, buttons, "Mode2");
          addToggleButton(buttonPanelMain, buttons, "Mode3");
          addButton(buttonPanelMain, "Quit");
          createButtonPanels();
          buttonPanel.add(buttonPanelMain);
          buttonPanel.add(new JSeparator(SwingConstants.HORIZONTAL));
          add(buttonPanel, BorderLayout.NORTH);
          setLocation(50, 50);
          setVisible(true);
          refreshButtons();
     private void createButtonPanels() {
          buttonMap = new HashMap<Mode, JPanel>();
          JPanel mode1Panel = new JPanel();
          addButton(mode1Panel, "1.1");
          addButton(mode1Panel, "1.2");
          buttonMap.put(Mode.MODE1, mode1Panel);
          JPanel mode2Panel = new JPanel();
          addButton(mode2Panel, "2.1");
          addButton(mode2Panel, "2.2");
          buttonMap.put(Mode.MODE2, mode2Panel);
          JPanel mode3Panel = new JPanel();
          addButton(mode3Panel, "3.1");
          addButton(mode3Panel, "3.2");
          buttonMap.put(Mode.MODE3, mode3Panel);
     private void refreshButtons() {
          buttonPanel.remove(currentPanel);
          currentPanel = buttonMap.get(mode);
          buttonPanel.add(currentPanel);
          buttonPanel.validate();
          buttonPanel.repaint();
     private JToggleButton addToggleButton(JPanel panel, ButtonGroup group,
               String name) {
          JToggleButton button = new JToggleButton(name);
          button.addActionListener(this);
          group.add(button);
          panel.add(button);
          return button;
     public void actionPerformed(ActionEvent e) {
          String cmd = e.getActionCommand();
          if (cmd.equals("Mode1")) {
               mode = Mode.MODE1;
               refreshButtons();
          } else if (cmd.equals("Mode2")) {
               mode = Mode.MODE2;
               refreshButtons();
          } else if (cmd.equals("Mode3")) {
               mode = Mode.MODE3;
               refreshButtons();
}

Look up the CardLayout as it is probably your best option here.
Best of luck!

Similar Messages

  • I just bought a Dell Precision M3800 laptop - screen res 3840 x 2160  when I open photoshop the task bar and tools and layers etc are in 4pts size   I changed my % in my image in my control panel and if I go to open file the drop down boxes are in good pt

    I just bought a Dell Precision M3800 laptop - screen res 3840 x 2160  when I open photoshop the task bar and tools and layers etc are in 4pts size   I changed my % in my image in my control panel and if I go to open file the drop down boxes are in good pt sizes  how do I make the layers and tool bars bigger?  Please help@

    Windows will scale applications display or windows will not scale application display depending on how the application is coded.  Photoshop is coded in a way that its display is not scaled by windows.  Photoshop knows about your displays high pixel count not its resolution  so it uses its pixels  however it does not scale its UI to make it usable on your display.  Other application let Windows  scale their display output.   For example Microsoft default for is Surface Pro 3, 216 ppi display is to scale applications display up 150% so the surface pro 3 display which has 2160x1440 pixels a 216 ppi resolution look like at display with the user is using with 1440x960 pixels.  The Application works like the display is 1440x960 and Windows scale those pixels to the displays using the displays  2160x1440 pixels the effectively changing it resolution to 144ppi rather than the actual 216ppi.
    The reg update  and external manifest file  effectively tells photoshop its working on such a size display display some number of pixel wide and some number photoshop uses that as the display size  in turn Windows scale those pixels to use the displays 2160x1440 pixels efector lowing its 216ppi resolution.  Photoshop CC 2014 2X UI would be like using windows 200% option applications would be shown the are working on a display 1080x720 instead of the Surface Pro 3 2160x1440. Note that 1080x720 does not meet PS requirement of 1024x768.  Photoshop UI would not fit on the Surface Pro 3 display..
    Since you have a 4k display if you have CC 2014 you can use its 2x UI effectively Photoshop will be running on a 1920x1080 display and have half the resolution of you 4K display  3840x2160 pixels four native pixels are use as a single pixel.   1920x1080 pixels exceed PS requirement.

  • Screen orientation locked despite correct settings in control panel and side switch

    Screen orientation locked despite correct settings in control panel and side switch

    Make sure this logo do not appear on top right of screen.

  • Control Panel and Sherlock in Panther

    Can someone please tell me how to find Sherlock and the Control Panel in Panther? Since I switched over from Classic 9. etc I can't find my way around as easily and have been informed about the Control Panel and Sherlock which I loved and used a lot on the Mac 9. etce but can't locate them on Panther. Do they exist there or not???? Please help. Thanks in advance.
    iMAc Special Edition   Mac OS X (10.3.9)  

    Hi Julie. The first thing you'd better remind yourself of, every time you sit down at your 'puter, is that Panther's a whole new breed of cat. You just can't assume any of the OS 9 things are the same—even if they look the same; aliases being an example—no matter how much you (and I) might want them to be. David Pogue's Missing Manual for OPanther was a h u g e help to my adjustment.
    One of the good things in Panther is that fat, bloated Sherlock2 was stripped of its Find… function. Command-F brings up an efficient System7-8.6 style dialogue, although it does have quirks: for one, it doesn't search the "System" folder unless specifically told to; "Search everywher" isn't enough. The internet part of Sherlock still shows up in my "Applications" folder. As X is more candid than OS9 about classifying things near and dear to Apple as apps like any other, you may find a few other faves there or in Utilities. In case the thought occurs to you, do NOT move them elsewhere, or establish subfolders in Applications to sort them—work w/ aliases—as X counts on finding such stuff where it expects, in a simple alpha list.
    Control Panels—which used to proliferate like mad, due to 3d party items—are now Panes (and Panes within Panes) within System Preferences. Most often 3d parties' add-ons are written as Applications or Utilities, though there are some written as Panes. It's actually quite efficient, though annoyingly harder to get to than the old cascading menus under the Apple.
    As you might expect, there are 3d party products that 'restore' old-world faves like the Apple menu and disable the sheet-spitter, but that's stretching this topic.
    Best wishes for your Panthering; I'm sure you'll find some stuff you come to love, along with thing you'll miss, but isn't that life in a nutshell?

  • Switching back and forth between 2 JFrames, rendering the other non-visable

    This seems to be my last problem with this assignment thankfully, everything else is completed. As per topic description, My assignment is to create a calculator like the windows XP calculator. It must have a 'standard view' on start up and the option to switch to a scientific calculator and switch back and forth as needed.
    As you most likely are aware the scientific calculator is approximately 1.3x the size of the standard calculator. I did look into CardLayout and TabLayout but from what I can gather these can't change sizes. I found this post: [http://forums.sun.com/thread.jspa?threadID=623561] Which is the same methods I had already tried. None of them worked.
    Being this is my first experience with swing, I naturally followed my books design which was to extend JFrame and implement other classes. I feel this may be the wrong course of action now.
    public class Calculator extends JFrame implements ActionListener,
                KeyListener, WindowListener
      private JMenuBar menuBar;
      private JMenu mEdit, mView, mHelp;
      private JMenuItem copyItem, pasteItem, helpItem, aboutItem;
      public Calculator()
        ... add(menu);
      public JMenuBar createMenu()
        ButtonGroup group = new ButtonGroup();
        rbStandard = new JRadioButtonMenuItem("Standard");
        rbStandard.setSelected(true);
        group.add(rbStandard);
        mView.add(rbStandard);
        rbScientific = new JRadioButtonMenuItem("Scientific");
        rbScientific.addActionListener(this);
        group.add(rbScientific);
        mView.add(rbScientific);
        menuBar.add(mView);
        return menuBar;
      @Override
      public void actionPerformed(ActionEvent e)
        if (e.getActionCommand().equals("Standard"))
          if (! isStandard)
            if (this.isDisplayable())
              this.requestFocus();
              this.setVisible(true);
              rbStandard.setSelected(true);
              sc.setVisible(false);
              isStandard = true;
            else
              JOptionPane.showMessageDialog(null,
                        "Something is wrong this WILL NOT SHOW !!!\n",
                        "It's STUFFED!\n", JOptionPane.INFORMATION_MESSAGE);
        else if (e.getActionCommand().equals("Scientific"))
          if (isStandard)
            sc.setVisible(true);
            rbScientific.setSelected(true);
            this.setVisible(false);
            isStandard = false;
      private class Scientific extends JFrame
        public Scientific()
          add(menuBar);
    }Ok that is a very basic overview of what the class looks like, the Standard calc hides itself and goes into Scientific mode very well, however when trying to switch back to Standard nothing happens, as you can see from that Action method I have tried numerous things, including dispose(). I need the standard view to become the scientific view and change it's size. I have read a lot of the swing tutorials and I can not think how to do this. Keep in mind that when Standard calc switches to scientific it does not open a new window, the window simply morphs. (this happens at the same orientation to desktop as well).
    2 questions:
    1. Does anyone know how I can switch back to standard calc?
    2. Should I redesign my project (which is currently sitting at 1200 lines and a single class(with inner classes)) and how?
    What is a good way to design a swing application such as this? (or is having the class extend JFrame perfectly normal?)
    Edited by: Gcampton on Sep 19, 2010 7:47 AM
    Additionally, I forgot to mention, I use the menu bar already defined in standard calculator(outer class) inside my scientific(inner class), all the options within scientific mode work exactly as they do in standard. Except of course for switching back to standard. Also the boolean variable isStandard, is not the problem as I have tested without it. the "About Calculator" "Help Topics" "copy" "paste" menu buttons all work and perform the actions as implemented in the Standard Calculator actionPerformed(ActionEvent e), The scientific actionPerformed() method IS BLANK!!!
    I was somewhat surprised at this, yet thankful as well. I didn't want to have so much repeat code in the inner class.

    I shouldn't have been so quick to think I won't run into any more problems...
    I've copied code straight from java tutorials [http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html]
                JEditorPane editorPane = new JEditorPane();
                editorPane.setEditable(false);
                java.net.URL helpURL = About.class.getResource("Doc2.html");
                if (helpURL != null)
                    try
                        editorPane.setPage(helpURL);
                    catch (IOException e)
                        System.err.println(
                                "Attempted to read a bad URL: " + helpURL);
                else
                    System.err.println(
                            "Couldn't find file: About.html");
                //Put the editor pane in a scroll pane.
                JScrollPane editorScrollPane = new JScrollPane(editorPane);
                editorScrollPane.setVerticalScrollBarPolicy(
                                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                editorScrollPane.setPreferredSize(new Dimension(250, 145));
                editorScrollPane.setMinimumSize(new Dimension(10, 10));
                return editorScrollPane;I have the html document in root eclipse folder, in bin and src. yet it does not display. I also have icons in my root folder and they display fine:
    this.setIconImage(new ImageIcon("about.png").getImage());Is this way depreciated? or is there somewhere else I should have the document?

  • Can I switch back and forth between DSL ethernet modem and AirPort ?

    I use Earthlink DSL connected direct to my iMac by ethernet cable from my modem and the service is very good . . . ever since I installed Leopard I noticed up in the top menu bar that AirPort is ON and usually shows 4 or 5 names listed and only 2 or 3 have the Lock icon . . . I have to assume AirPort is detecting signals from the apartments above and next to me . . . I do not need a wireless connection but I am curious to see if my iMac will actually join one of those networks so how do I temporarily try that and then go back to my regular wired DSL service ? . . . also, I may start renting out a room in my place and the girl will undoubtedly have either a Windows or hopefully a Mac laptop and will need wireless so I would appreciate advice on the best equipment to buy that both Windows and Mac laptops can connect to wirelessly . . . thanks in advance for any advice

    Yes you can. Just unplug your DSL modem and then go to your airport menu and try to connect to one of the networks taht's available there. To switch back, reconnect your DSL modem and connect as you usually do.
    Any wireless "802.11x" router (where x is "b","g", or "n") will work for both Macs and PCs. Practically all routers these days are compatible with every platform out there.

  • Switching panels in diffrent states

    Hi all,
    I have a lot of panels which I'm switch between them using card layout.
    My problem is that the switching between the panels isn't constant and it is depent of the application current state.
    For example:
    STATE1: Screen1 (next -->) Screen2 (next -->)Screen3 (next -->) Screen1
    STATE2: Screen1 (next -->) Screen2 (next -->) Screen3 (next -->) Screen2
    STATE3: Screen2 -(next -->) Screen1 (next -->) Screen3 (next -->) Screen1
    Each STATE is the user choise from the main-menu and and the Screens are the panels which displayed using the CardLayout and (next -->) represent the order they displayed
    and so on...
    At the moment i'm using a lot of if-else but this is not a good technigue when adding new panels and states.
    Does any one can give me advise how to make this simplier ?
    Thank,
    hanoch

    Use a 2D array to store the screen switch info.
    String[][] switchBoard = new String[stateNum][stepNum];
    // ToDo: Initialize the array here ...
    switchBoard[2][3] = "Screen 3";
    // Flip screen
    yourCardLayout.show(yourPanel, switchBoard[state][step]);

  • Source code of a good swing application

    Hi,
    Can someone provide me a link to a good application with available source code based on swing (a database one with forms would be great). I'm trying to get some good implementation practice but I can't find any application one the net.
    thank you

    Hi Geoffrey,
    You can download a Web dynpro ABAP component into a Nuggest file using SAPLINK. You can download it from site http://groups.google.com/group/saplink  or http://www.saplink.org
    There is a plug-in for Web Dynpro.
    If you have a very small piece of code(Like only code in WDDOINIT method),  then you can copy and paste the code into a notepad or word file too.
    Hope it helps.

  • Good programming practice - Abstract class

    Hi all,
    I have been trying to help another soul in this forum, and came to the conclusion that I don't know good
    programming practice when it comes to abstract classes.
    Is this correct?
    You CAN implement methods in an abstract class, but it's not recommended.
    I have NEVER done this...when is there possibly a need to?
    Regards.
    / k

    Yes, absolutely, you can implement methods in an abstract class. Any method that all subclasses will perform in the same way can be implemented in the abstract base class. If subclasses perform similiar functions depending on their type you declare those as abstract in the base class. Here is a contrived example that I have seen on job interviews.
    Suppose your developing an application that draws on a panel. We want to provide some canned shapes such as a circle, a square and a triangle. We want to be able to draw the shape set or get its color and calculate its area.
    Let's define an abstract base class Shape
    public abstract class Shape{
        private Color myColor;
       //  since color has nothing to do with what kind of shape we're working with, create concrete implementation
       public Color getColor(){
            return myColor;
    public void setColor(Color newColor){
       myColor = newColor;
    // however, drawing the shape and calculation its area are depending on the actual shape.
    public abstract void draw();
    public abstract double getArea();
    // so then Square would be something like
    public class Square extends Shape{
       public double get Area()
          return sideLength * sideLength  // assumes somehow we know sideLength
    public void draw(){
                  // concrete implementation
    }we can do the same things for Circle class and Triangle class.
    And, if you think about it you'll notice that we could have made a Rectangle class and then Square would be a subclass of Rectangle where both dimensions are equal.
    I hope that somewhat strained example helps answer your question.
    DB

  • Comparing switch control and switch output and setting switch control accordingly

    Hello,
            i am developing a GUI for a system which contains relays to control the motors. For the same purpose i am using switch control on my GUI to control these relays.when these relay  are turned ON by the switch control on my GUI, they give back status to the GUI, which i am displaying as a switch status .
    Now the switch control and switch status on GUI must be same every time so that user can know the actual state of relay and control it.
    Now i have a condition when i have already turned ON switch from my GUI but due to some reason (may be communication fault or anything else) rellay is not turned ON and i get status of relay as OFF on my switch indicator. So the situation is" the switch control is in ON state and switch indicator displays OFF state".  which is practically wrong.
    I want that in this case the GUI should detect the status of the switch indicator and if the switch control is not the same , the switch control should be set as per the switch indicator so that user can use the switch again to turn the switch ON

    Hello Mike,
                        Thanks for the response!!
    As i have described the situation above, in any case if switch control fails to send message to relay due to some hardware fault , in that case relays will be off and the switch on GUI will be ON , and user will think that the relay is ON.Which is false condition.
    i tried to use property value(signl)   to give back the status of switch indicator to the switch control.
    You can have a look at attached files which i have made as demo.
    Now the problem is when i run my GUI for the first time all the switch on the front panel are off by default which creates a conflict to control the switches.
    Besides i am unaware of the timing events and how to implement it in my application . It would be great if you could provide some more details about it.
    Thanks & Regards,
    Shivkant Paswan
    Attachments:
    switch control trial.zip ‏16 KB

  • My wifi will not turn on. The button is settings seems to be locked. I tried turning it on from the control panel, and also with Siri, but it still does not turn on in settings, so i cannot access wifi. Please help ASAP

    Wifi will not work. The button in settings seems to be locked. Tried control panel and siri to turn it on, doesnt work because the settings wont turn it on. Need help ASAP cause my data limit is approaching.

    If the battery was completely drained the iPad will not respond for some time after connecting it to the charger. Connect the iPad to the charger that came with it and plug that into a good wall outlet. Wait 30 minutes. Then reset the iPad.Press and hold both the Home button and the Sleep/Wake button continuously until the Apple logo appears. Then release the button and let the device restart. You will not lose data doing this. It's like a computer reboot.
    If the iPad restarts let it continue to charge until it's battery shows fully charged. If the iPad still does not start Make an appointment at an Apple Store to have your device examined by a technician. Or contact Apple Support. Be sure to back up your device before taking or sending it to Apple.

  • Remote panel and selective control access through Security with DSC

    Hi Everyone,
    I looked around to see what labview had to offer concerning security of remote panel and all the solutions I've found only propose full access to a remote panel, or none. The login page is not an option for me as everyone on the intranet can access the remote panel for monitoring but not everyone can have control to the buttons on it.
    With the DSC module, I can give securities to the different controls and it works great with the exe, if I log in or out, the controls appears or disapears. Unfortunately, with remote panels, those controls are always visibles. Furthermore, when I log in from a remote panel, all the other remote panels get logged in with the same username and priviledges. When I log out, same thing, it logs out all the other remote panels. So the last guy who logs in gives its priviledges to every one else who is monitoring the remote panel at that time. when he logs out, he logs everyone out. I used a reentrant vi hoping that this would solve the problem but it didnt.
    I would like to do what my colleague does with Advantech without any problem. He has only 1 .exe is running on the server and whoever connects to it through webserver, just needs to log in and he has all the priviledges of an guest, operator, admin, etc.. with access to controls and features accordingly. All this without interfering with the other people using the remote panels. This colleague has always been doubtful about the capabilities of labview to do SCADA systems and uptil now, I've been able to prove him wrong.. please help me continue
    There are workarounds, using remote desktop to the server instead of webserver but it definitely is not as practical for the client and it will need quite some work to to synchronise all the exes open from the differents sessions, through the use of shared variables, binding and securities.
    Thank you for your help.
    Solved!
    Go to Solution.

    Thank you very much for your reply Jordan.
    The NI security info is on the server (local domain with groups and users), and the running exes as well. The remote panel is not supposed to be accessed by internet, at least not yet, but just by the computers on the network and thinkline computers who are directly connected to the servers. the remote panel is accessed through the simple url: http://serverip/Application.html
    There is no problem with accessing the remote panel of the exes on the server from another computer on the network. But there are several security issues when logging in and out with the NI Security Programmatic Login and logout VIs through the remote panel..
    The 1st problem occurs when several people access the remote panel at the same time. In my setup, everyone is allowed to check what's happening on the front panel of the running exe, go through the tabs, check the graphs, the tables, etc.. , but only the administrators and the operators can send commands to the machines and the production line through this remote panel. Hence some buttons are accessible to all users, while others are only accessible depending  on the privileges of the person logged in.
    So like I said in the 1st post, I configured some buttons to be accessible only by the users of the admin group. When the exe runs, it's perfect, if I log in and out with an admin account, the buttons appears and disappear accordingly. But when I check the remote panel, those admin buttons are always visible, even if I am logged in as a guest or even logged out. Is it because the remote panel only needs minimum runtime engine and doesnt use the dsc runtime engine? if so, any work around?
    Furthermore, another big problem is that if I login as an admin in one remote panel, then login as an guest in another remote panel, and then logout back from the first remote panel, it says: "User Domain/Guest logged out". Hence, my second login logged out my first user. I can actually see the admin buttons appearing and disappearing on the exe when login as admin and guest from the different remote panels.
    So that's it, I would like my remote panel to behave like a normal scada system, with one exe running in the back (on the server) and with all the users accessing it through web server. Several users might/will access the remote panel at the same time and each of the users have a login/password that grant some of them the privileges to take some actions while giving the others only monitoring rights.
    I hope that I have been more clear in this 2nd post,
    Thank you again for your time.
    Best Regards,
    Tom.

  • I have a pc running windows 7.  I got an Airport Extreme 802.11n Wi-Fi and the printer is now plugged into the Airport.  The wireless router works fine but the printer shows as offline in control panel and in word. The printer is a HP LaserJet CP1525nw.

    I have a pc running windows 7.  I got an Airport Extreme 802.11n Wi-Fi and the printer is now plugged into the Airport.  The Airport works fine but the printer shows as offline in control panel and in word. The printer is a HP LaserJet CP1525nw.

    +For now I have it set to Share Public IP address - Is this correct for my Network Setup with The Airport Extreme being the only router being used ?+
    This would be the correct setting if the AirPort Extreme is connected to a simple modem (one ethernet port).
    *Settings I have Enabled*
    5 GHz name indicates that you have elected to use the option to assign a separate name to the 5 GHz network. This will allow you to "tell" compatible computers to connect to that network, rather than the slower 2.4 GHz network
    Use Wide Channels is recommended for 5 GHz operation.
    Interference Robustness often does more harm than good and should not be used unless you know you are in a area with a lot of wireless networks and you feel that your network is experiencing interference issues from a nearby network.

  • Switch back and forth from Chinese and English in Forms and Reports 6i

    How do you switch back and forth from Chinese and english in forms and reports 6i? Tried changing regional settings in the control panel. Tried changing registry entry for nls_lang from american and chinese, none of them work! Can anyone help?
    Chinese version of forms and reports 6i is installed. Only way I can change between english and chinese is to keep installing the version I want. Is there any other way?

    Check Forms Help for National Language Support.
    Monica

  • My name is Mike. I live in New Zealand. My username is waipukurau1. I downloaded MacBook booster from the prompts. Was this a good idea and good for my MacBook Pro? Please answer.

    My name is Mike. I live in New Zealand. My username is waipukurau1. I downloaded MacBook booster. I write to ask was this a good idea? Was this good and correct for my MacBook Pro. Please answer.

    ashish35,
    No one from Apple here - we're just users like you. All I can tell you is that electronic fail and with MacBook Pros (and most notebooks) the components are so integrated as to make a repair to the logic board practically impossible, hence the high prices charged for repairs.
    Only you can decide if you want to have your computer repaired or put the money towards the purchase of a new computer. If you do decide to purchase a new unit I would suggest that you also purchase the AppleCare Protection Plan which increases your warranty from one year to three years.
    Sorry and good luck,
    Clinton

Maybe you are looking for