Handling focus on components within JPanel

I have a custom component called a DmsField which extends JPanel. "Dms" means degrees/minutes/seconds. It's a JPanel with a two-button JRadioButton group for the sign, and three JFormattedTextFields for degrees (int), minutes (int), and seconds (float, 2 dec places). It's later subclassed into LatField and LonField so I can enter latitudes and longitudes into an application. When I put a LatField or a LonField into my dialog's JPanel, tabbing through the various components in the larger panel shifts the focus to the whole LatField (or LonField) object first, then through the subobjects in the *Field.  How can I get the focus traversal to NOT focus on the DmsField itself, but to go straight to the first component inside the DmsField?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

I have tried putting a FocusListener on the JPanel which would set the focus to its first component. Works fine tabbing forward, but gets stuck on first component when back-tabbing.
Disabling FOCUS_EVENT_MASK on the JPanel didn't change anything.
The odd thing is, I don't see any other JPanels exhibiting this behavior.

Similar Messages

  • How can we prevent JTabbedPanes from transferring focus to components outside of the tabs during tab traversal?

    Hi,
    I noticed a strange focus traversal behavior of JTabbedPane.
    During tab traversal (when the user's intention is just to switch between tabs), the focus is transferred to a component outside of the tabs (if there is a component after/below the JTabbedPane component), if using Java 6. For example, if using the SSCCE below...
    import java.awt.BorderLayout;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TabbedPaneTest extends JPanel {
        public TabbedPaneTest() {
            super(new BorderLayout());
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            add(new JScrollPane(panel));
        private JPanel buildPanelWithChildComponents() {
            JPanel panel = new JPanel();
            BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
            panel.setLayout(boxlayout);
            panel.add(Box.createVerticalStrut(3));
            for (int i = 0; i < 4; i++) {
                panel.add(new JTextField(10));
                panel.add(Box.createVerticalStrut(3));
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneTest());
                    frame.pack();
                    frame.setVisible(true);
    ... Then we can replicate this behavior by following these steps:
    1) Run the program in Java 6; and then
    2) Click on a child component in any of the tabs; and then
    3) Click on any other tab (or use the mnemonic keys 'ALT + 1' to 'ALT + 4').
    At step 3 (upon selecting any other tab), the focus would go to the component below the JTabbedPane first (hence the printed message in the console), before actually going to the selected tab.
    This does not occur in Java 7, so I'm assuming it is a bug that is fixed. And I know that Oracle suggests that we should use Java 7 nowadays.
    The problem is: We need to stick to Java 6 for a certain application. So I'm looking for a way to fix this issue for all our JTabbedPane components while using Java 6.
    So, is there a way to prevent JTabbedPanes from passing the focus to components outside of the tabs during tab traversal (e.g. when users are just switching between tabs), in Java 6?
    Note: I've read the release notes between Java 6u45 to Java 7u15, but I was unable to find any changes related to the JTabbedPane component. So any pointers on this would be deeply appreciated.
    Regards,
    James

    Hi Kleopatra,
    Thanks for the reply.
    Please allow me to clarify first: Actually the problem is not that the child components (inside tabs) get focused before the selected tab. The problem is: the component outside of the tabs gets focused before the selected tab. For example, the JButton in the SSCCE posted above gets focused when users switch between tabs, despite the fact that the JButton is not a child component of the JTabbedPane.
    It is important for me to prevent this behavior because it causes a usability issue for forms with 'auto-scrolling' features.
    What I mean by 'auto-scrolling' here is: a feature where the form automatically scrolls down to show the current focused component (if the component is not already visible). This is a usability improvement for long forms with scroll bars (which saves the users' effort of manually scrolling down just to see the focused component).
    To see this feature in action, please run the SSCCE below, and keep pressing the 'Tab' key (the scroll pane will follow the focused component automatically):
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    public class TabbedPaneAutoScrollTest extends JPanel {
        private AutoScrollFocusHandler autoScrollFocusHandler;
        public TabbedPaneAutoScrollTest() {
            super(new BorderLayout());
            autoScrollFocusHandler = new AutoScrollFocusHandler();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            button.addFocusListener(autoScrollFocusHandler);
            JScrollPane scrollPane = new JScrollPane(panel);
            add(scrollPane);
            autoScrollFocusHandler.setScrollPane(scrollPane);
        private JPanel buildPanelWithChildComponents(int numberOfChildComponents) {
            final JPanel panel = new JPanel(new GridBagLayout());
            final String labelPrefix = "Dummy Field ";
            final Insets labelInsets = new Insets(5, 5, 5, 5);
            final Insets textFieldInsets = new Insets(5, 0, 5, 0);
            final GridBagConstraints gridBagConstraints = new GridBagConstraints();
            JTextField textField;
            for (int i = 0; i < numberOfChildComponents; i++) {
                gridBagConstraints.insets = labelInsets;
                gridBagConstraints.gridx = 1;
                gridBagConstraints.gridy = i;
                panel.add(new JLabel(labelPrefix + (i + 1)), gridBagConstraints);
                gridBagConstraints.insets = textFieldInsets;
                gridBagConstraints.gridx = 2;
                textField = new JTextField(22);
                panel.add(textField, gridBagConstraints);
                textField.addFocusListener(autoScrollFocusHandler);
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6 with auto-scrolling");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneAutoScrollTest());
                    frame.setSize(400, 300);
                    frame.setVisible(true);
    * Crude but simple example for auto-scrolling to focused components.
    * Note: We don't actually use FocusListeners for this feature,
    *       but this is short enough to demonstrate how it behaves.
    class AutoScrollFocusHandler extends FocusAdapter {
        private JViewport viewport;
        private JComponent view;
        public void setScrollPane(JScrollPane scrollPane) {
            viewport = scrollPane.getViewport();
            view = (JComponent) viewport.getView();
        @Override
        public void focusGained(FocusEvent event) {
            Component component = (Component) event.getSource();
            view.scrollRectToVisible(SwingUtilities.convertRectangle(component.getParent(),
                    component.getBounds(), view));
    Now, while the focus is still within the tab contents, try to switch to any other tab (e.g. by clicking on the tab headers, or by using the mnemonic keys 'ALT + 1' to 'ALT + 4')...
    ... then you'll notice the following usability issue:
    1) JRE 1.6 causes the focus to transfer to the JButton (which is outside of the tabs entirely) first; then
    2) In response to the JButton gaining focus, the 'auto-scrolling' feature scrolls down to the bottom of the form, to show the JButton. At this point, the tab headers are hidden from view since there are many child components; then
    3) JRE 1.6 transfers the focus to the tab contents; then
    4) The 'auto-scrolling' feature scrolls up to the selected tab's contents, but the tab header itself is still hidden from view (as a side effect of the behavior above); then
    5) Users are forced to manually scroll up to see the tab headers whenever they are just switching between tabs.
    In short, the tab headers will be hidden when users switch tabs, due to the Java 6 behavior posted above.
    That is why it is important for me to prevent the behavior in my first post above (so that it won't cause usability issues when we apply the 'auto-scrolling' feature to our forms).
    Best Regards,
    James

  • Modifying Components within a cell table not working

    Hello,
    I am displaying JTextFields within JPanels in each cell of a JTable, but when I select a cell I am unable to enter text into the text boxes. Why has this been disabled now that these components are withing a JTable cell?
    Thanks,
    Emily

    Do I have the CellEditor just return the same Panel the renderer returns?It depends and I suppose rather not.. The JTable invokes editor to provide editing component with cell object as parameter. The editor method is then expected, in your case, to set appropiate values to all components in panel and return this panel. However, JTable may also need to draw another cells while you are editing. It will then ask renderer to provide panel for that - if you use exactly same object you may have a "crostalk" between renderer and editor.
    Whatever you will do, the behaviour of JPanel build in JTable cell will be litle different than standalone JPanel - if for example user double clicks in JTextField in cell, this click won't select JTextField - it will start editor only. Single click may not work at all. I did experimented with JComboBox as an editor and found, that to not confuse user too much it is better to have different view for renderer and editor - this way user will be aware about switching between edit and select/view mode.
    Also, any listeners may get confused in JPanel embeded in JTable - they will recive extra events when you prepre panel to display/edit and may miss many mouse events since they will be attached to event pump only while JTable keeps cell in edit mode.
    You need some experiments, I think. I would start from having two instances of same JPanel subclass - one which will work as a renderer and second, which will work as an editor.

  • Can't show J components on JPanel

    Because I'm a begineer, I'm not sure I can explain my problem correctly.
    The problem is quite simple.
    I'd like to show some J components on JPanel but I can't.
    I made a JFrame which has 5 JPanels.
    Each JPanel has some components and calls paint method to draw some lines.
    public void paint(Graphics g){
         g.setColor(Color.black );
         drawDisplay(g);
    When I put AWT componts such as Label, Button etc, there's no problem.
    But when I put J components like JLabel, JButton,
    I cannot see the components. Sometimes I can click JCombo box....
    Interestingly, when I remove the paint method, J components show up on interface.
    Anybody understand this situation?
    Do I have to know something for this?
    Thank-you.

    I second camickr's recommendation for you to study the tutorials. A few specifics:
    public void paint(Graphics g){
       g.setColor(Color.black );
       drawDisplay(g);
    }* Don't override the paint method of a JPanel, override the paintComponent method.
    * You will need to call super.paintComponent(g) within your paintComponent override. This may need to be the first line in fact.
    * As noted by camickr, do not place AWT components on a Swing component (JPanel).

  • Using Flex components within Flash CS3

    I'm new to Flex and I enjoy all of the components that it has
    to offer, but I am wondering about their availability within Flash.
    My plan is to make a highly animated and interactive menu and
    I have reached a point where I have to ask two questions:
    1. Is is possible to use any of the Flex components within
    Flash CS3?
    2. If the first is not possible, then if I make my menu and
    specify "containers" within the Flash file then is it possible to
    populate these "containers" with Flex components by making the
    Flash (.swf) file of my menu into a Flex component itself?

    No, Flex components cannot be used in Flash 8.

  • Webdynpro components within SRM

    Hello all
        I want to access the webdynpro components within SRM Portal . How do I do that?
      Regards,
    Sanjeet

    Hi,
    > 1. Is it necessary to deploy webdynpro components SAP
    > ESS 600, SAP MSS 600 and SAP PCUI_GP 600 ?
    PCUI_GP is mandatory for both ESS and MSS,..
    So , if its ESS .. ESS 600 and PCUI_GP 600 should do.
    > 2. If in case these already deployed where i have to
    > check for thesde components ?
    You can check this in SDM. ess~component names..
    > 3. If in case these components are not deployed what
    > are the effects ?
    You will only have the webdynpro iviews in portal,, but the actual webdynpro application these iviews use wont be there.. So it wont work.
    Regards
    Bharathwaj

  • How can we add components to JPanel so that they can be resizeable

    Is it possible to add components to JPanel so that we can resize them or drag them.

    You could try searching the forums, but I'll save you the trouble. tjacobs has oft posted code which does what you want, both dragging and resizing.
    You can find an example here or here.

  • Highlighting text fieldon focus with components

    Is there a way to highlight a text field when the focus is in that field. I know on a web page you can do this with JS, but wasn't sure about with AS. I am using components also.

    If you just want to highlight one word at a time then you can use:
    textComponent.setSelectionStart(...);
    textComponent.setSelectionEnd(...);
    The above code will use the default selection background/foreground font colours.
    Here is an example of a Find/Replace dialog that uses this approach.
    http://www.discoverteenergy.com/files/FindReplace.java
    If you want to get fancier and use different styles of fonts and colours for different words then you have to use JTextPane which supports StyledDocuments.
    The basic approach is to create attribute sets as follows:
    MutableAttributeSet comment = new SimpleAttributeSet();
    StyleConstants.setForeground(comment, Color.gray);
    StyleConstants.setItalic(comment, true);
    Document doc = textPane.getDocument();Insert new text into the document with the 'comment' attribute:
    doc.insertString( doc.getLength(), "comment text", comment);
    Change the attribute of existing text in the document with the 'comment' attribute:
    doc.setCharacterAttributes( 0, 3, comment, false );
    Here is a simple Java syntax highlighter that uses this approach:
    http://www.discoverteenergy.com/files/SyntaxDocument.java
    Note, most is the above code is devoted to handling multi-line comments. The main highlighting code is in the 'checkForTokens()' method.

  • Requesting focus for JTextField inside JPanel

    I have an application with following containment hierarchy.
    JFrame --> JSplitPane --> JPanel.
    JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
    regards,
    Nirvan.

    I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.

  • Updating components in jpanel

    Hi, all
    I have a report application which will update me system utilization in several jpanel. Those panels stored in a hashtable and I programmed it refresh each 5 minutes. Here is how I do it.
    Step 1: remove all
    mypanel=(JPanel)panels.get("1");
    mypanel.removeAll();
    mypanel.validate();
    Step 2: show progress
    mypanel.add(<updating message in jlabel>);
    mypanel.add(<a progressbar>);
    mypanel.validate();
    Step 3: add new content
    mypanel.removeAll();
    mypanel.add(<a graph in jlabel>);
    mypanel.add(<a jtable with data>);
    The problem is the old content still remains when progress bar appeared. Didn't I just remove all components in step 1? How can I have a empty panel with only progress bar?
    Thanks,
    Vincent Chen

    Damn, I found what the problem is, but if I gave the solution to the OP, that would mean confessing I have followed the link, and admitting to belong to the "not worth mentioning" category!Well, since my cover's blown anyway, let's caugh it up:
    Your have an attrubute searchType of type SearchType, you initialize it to reference a new SeearchType() , and you use its status for the search, however you never add the instance in the panel's widget hierarchy. Instead you add a new SearchType() .
    Same for attribute style :
    searchType = new SearchType();
    style = new Style();
    this.add(new SearchType(), c);
    this.add(new Style(), c);
    // in event handler
    search(txfQuery.getText(),searchType.getSelected(),style.caseSensitive(),limitation.getLimNum());
                                    ^
                                    *At this point, the instance referenced by searchType has never been displayed, so the checkbox, combobox, and whatnot that the user has interacted with are not the ones whose state you read.

  • Handling events outside components..

    Hi there,
    I would like to handle mouse events outside a components.
    After that my application is started, I want to run another thread
    when mouse is pressed.
    Is it possible?

    you can add mouse listener to frame itself or if you are using jpanel to add your components than you can add mouse listener to jpanel too

  • Zooming causes components on JPanel to displace

    Hi friends,
    my english is somewhat weak, but i am trying to clear my point.
    I have a prob regarding zoom. In my application I have A JPanel which is drawing some rectangles on it and having some JLabels. My prob is when i zoomin my JPanel through my zooming code and try to select any of JLabel ,I am not actually selecting labels by just clicking on the label but i have to make some random guess on JPanel to select that label.
    I am not getting what mistake i m making there. may be i would have to move my labels by some distance on zooming(but its only my view). if any of you have some ideas then please do tell me.
    thankyou

    I second camickr's recommendation for you to study the tutorials. A few specifics:
    public void paint(Graphics g){
       g.setColor(Color.black );
       drawDisplay(g);
    }* Don't override the paint method of a JPanel, override the paintComponent method.
    * You will need to call super.paintComponent(g) within your paintComponent override. This may need to be the first line in fact.
    * As noted by camickr, do not place AWT components on a Swing component (JPanel).

  • Sticking components in JPanel to GridLayout

    Could please anyone help in the following.
    I have an application where some JPanel with several Swing components
    positioned with help of GridLayout. What I need is to
    remove and place components during runtime,
    but the problem is that when I remove component placed somewhere
    inbetween with use of the method remove() of the class JPanel,
    all components are shifted so that the empty space is filled and
    even one can see that the initial GridLayout is destroyed.
    How can I stick all components to the initial grid cells of GridLayout?
    I mean I do not want components to shift anywhere from their original
    cells.
    Thank you in advance.

    Well, that solution is what I came to also.
    I mean I replacing removed compenent with some other invisible component.
    But is this indeed the only way?
    I tryied the method removeLayoutComponent() in the class GridLayout, but
    I have not understood how it works and what it is for.
    When I tryied it instead of remove() (of JPanel) it did not remove anything,
    but it looks like something relevant to my situation.
    PS The second line of my orginal poster should be read
    "I have an application where some JPanel is created with several Swing components
    positioned with help of GridLayout in it".
    Sorry...

  • Initializing JDialogs or Other GUI Components within SwingWorker

    Hello Every one,
    I have been using SwingWorker class heavily in my application and recently I noticed that If I click on a button twice or thrice the third or 4th it takes more time to perform the action in which SwingWorker is being used. So I started reading more about SwingWorker and after reading number of articles and posts on this forum I believe I am not using SwingWorker correctly. But, I am not still sure ( or may be I am afriad or I am not ready to change my code in so many files and so many locations :(
    So I thought to ask some gurus following questions, in this forum before I proceeed with the code refactoring.
    Question 1:* I am performing GUI operations in doInBackground() is it ok to perform swing operations or create swing components in this method of SwingWorker?
    Example Code :
    jbtnModifyUser Action Event
    private void jbtnModifyUserActionPerformed(java.awt.event.ActionEvent evt) {
    setButtonsState(false);
    final SwingWorker worker = new SwingWorker() {
    protected Object doInBackground() {
    try {
    openUserModifierDialog(SELECTED_PROFILE);
    } catch (Exception ex) {
    ex.printStackTrace();
    } finally {
    return null;
    public void done()
    setButtonsState(true);
    worker.execute();
    }Open Dialog Method wich I call from several other Swing Components Action performed event
    private void openUserModifierDialog(UserProfile profile) throws ServerException {
    UserModifierDialog modifier = new UserModifierDialog(_frame, true, profile);
    modifier.pack();
    modifier.setVisible(true);
    if (modifier.isModified()) {
    resetFields();
    populateUserTable();
    } If I click 3 to 4 times same button the 4th or 5th time the dialog opens after soem delay like 10 seconds. But in first two three click it opens quickly like in 2 to 3 seconds. Is it due to the fact that I am perfoming Swing GUI operations in doInBackgroundMethod()?
    Question 2: Should I use EventQueue.invokeLater() but as far as I have learned from the articles, the actionPerformed events already run on EDT.
    Question 3:_ Each dialog has multiple swing components like combo boxes, tables, tress which it populates after fetching data from the Database in its constructor. It takes like 1 to 2 seconds to bring data and initialize all swing components. Once the Dialog is initialized in the constructor I call my own function to set the existing user details ( As shown below ).
    I need to set all the details before I show the Dialog to the user. To achieve this what is the best practice? Where should I use SwingWorker in current scenario? in Dialog's PostInitialize()? In Dialog's Constructor()? or in the Frame's openModifierDialog()?
    public UserModifierDialog(java.awt.Frame parent, boolean modal, UserProfile userprofile)
    throws ServerException {
    super(parent, modal);
    if (userprofile != null) {
    SELECTED_USER_PROFILE = userprofile;
    }else{
    //throw new Exception("Invalid user record. User profile cannot be null. ");
    initComponents();
    postInitialize(); // my function called to set the user details on the screen
    private void postInitialize() throws ServerException {
    _userManager = new UserManager();
    initializeAllPermissions();
    initializeUserGroups();
    setFields(SELECTED_USER_PROFILE);
    private void initializeUserGroups() throws ServerException {
    _jcbUserGroup.removeAllItems();
    _jcbUserGroup.setModel(new ArrayListModel(_userManager.getAllUserGroups ()));
    _jcbUserGroup.setSelectedIndex(0);
    private void setFields(Userprofile profile) throws ServerException{
    _jlblUserID.setText(profile.getUserid().toString());
    _jtfUserName.setText(profile.getUsername());
    _jtfFirstName.setText(profile.getFirstname());
    _jtfLastName.setText(profile.getLastname());
    _jtfPassword.setText(profile.getPassword());
    _jtfConfirmPassword.setText(profile.getPassword());
    _jtaDescription.setText(profile.getDescription());
    _jcbUserGroup.setSelectedItem(_userManager.getUserGroup(profile.getUserGroupID()));
    } Question 4: I noticed that if I use following code in my openModifierDialog function to execute the worker rather then its own execute method the dialog opens quickly each time.
    Is it good idea to use the following to execute a SwingWorker or I shouldn't as I may fall in some threading issues later on which I am not aware of?
    Thread t = new Thread(worker);
    t.start();Hope to hear some useful comments / answers to my queries.
    Thanks in advance.
    Regards

    Thanks for your prompt reply and answers to my queries.
    Well, I know there are enormous faults in this code. Thats why I am seeking guru's advice to clean the mess. Let me give you breif background of the code. The current code was written by some one else using old version of SwingWorker and I am just trying to clean the mess.
    All the JDialog or Swing Components intialization code was in construct() method of previous SwingWorker. Later on when the SwingWorker became the part of Java SE 6 all application code was refactored and the GUI components initialization was moved to the new function doInBackground().
    The sample code represents the current condition of the code. All I needed was a shortcut to clean the mess or to avoid changes at so many places. But it seems that there is no easy workout for the current situation and I have to change the entire application code. I have gone through the SwingWorker API and tutorial @ [http://java.sun.com/developer/technicalArticles/javase/swingworker] and I am doing following to clean this mess.
    Well the following code is proposed refactoring of the previous code. Hope to hear your comments on it.
    private void jbtnModifyUserActionPerformed(java.awt.event.ActionEvent evt) {
    try{
    openUserModifierDialog(SELECTED_PROFILE);
    } catch (Exception ex) {
    logger.error(ex);
    //show some message here
    } finally {
    private void openUserModifierDialog(UserProfile profile) throws ServerException {
    UserModifierDialog modifier = new UserModifierDialog(_frame, true, profile);
    modifier.pack();
    modifier.setVisible(true);
    if (modifier.isModified()) {
    resetFields();
    //UserModifierDialog Constructor
    public UserModifierDialog(java.awt.Frame parent, boolean modal, UserProfile userprofile)
    throws ServerException {
    super(parent, modal);
    if (userprofile != null) {
    SELECTED_USER_PROFILE = userprofile;
    } else {
    //throw new Exception("Invalid user record. User profile cannot be null. ");
    initComponents();
    postInitialize(); // My function called to set the user details on the screen
    private void postInitialize() {
    _userManager = new UserManager();
    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
    final SwingWorker worker = new SwingWorker() {
    protected Object doInBackground() {
    try {
    return _userManager.getAllUserGroups(); //returns ArrayList of all user groups from database
    } catch (ServerException ex) {
    //Show Message here
    return null;
    protected void done() {
    try {
    if (get() != null) {
    _jcbUserGroup.setModel(new ArrayListModel((ArrayList) get()));
    _jcbUserGroup.setEditable(false);
    setFields(SELECTED_USER_PROFILE);
    else
    //show some error to user that data is empty
    } catch (InterruptedException ex) {
    //show message here
    } catch (ExecutionException ex) {
    //show message here
    } finally {
    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
    worker.execute();
    private void setFields(Userprofile profile) throws ServerException {
    _jlblUserID.setText(profile.getUserid().toString());
    _jtfUserName.setText(profile.getUsername());
    _jtfFirstName.setText(profile.getFirstname());
    _jtfLastName.setText(profile.getLastname());
    _jtfPassword.setText(profile.getPassword());
    _jtfConfirmPassword.setText(profile.getPassword());
    _jtaDescription.setText(profile.getDescription());
    _jcbUserGroup.setSelectedItem(_userManager.getUserGroup(profile.getUserGroupID()));
    }In some places where data is way too huge I am going to use process and publish methods of SwingWorker.
    Now I have another question, how I can notify/throw any exceptions occured inside SwingWorker doInBackground method or done method to the function who executed SwingWorker. Currenlty I am catching the excpetions in the done method and showing a dialog box. But I want to throw it to the postInitialize method the method who created and executed the Worker. What is the best practice of handling exceptions in SwingWorker methods.
    Do you see any problems in proposed refactoring?
    Hope to hear your comments.
    Regards

  • Automatic handling of BW hierarchies within infopackages

    Within BW there are infosources and
    within infosources there are infopackages. You can create time
    versioned hierarchies within a infopackage.  We create the hierarchies
    for each month. When you do this, in order to load the data into the
    correct hierarchy, there is radio button that you have to select. I
    would like to know if there is a automatic way, weather with ABAP
    calling BAPI's or some other program(s) to first create the hierarchy
    for the month and then select the radio button so that the data is
    loaded to the correct hierarchy.
    thanks in advance.

    hi pavan,
          No automatic handling of BW heirarchies , i guess.
    Just go thru it , it may helpful to you.
    Activities for generating a DataSource for a set hierarchy:
    1. Enter the table that the set uses (for example, an FI-SL totals table GLFUNCT) and then select the table field (for example, RBUSA Business Area) for the set.
    2. If the characteristic is compounded in the BW, which the hierarchy is based on, and if you want to transfer its compounding information on the source system to BW, select BW Characteristic is compounded. Enter the data element to which the hierarchy is compounded. When the hierarchy is loaded, the compounding information is taken into account in BW. If you want to extract the FI-SL set of a characteristic compounded in BW, you have to run the compounding process in a customer exit. In transaction CMOD, create a project for SAP enhancement RSAP0001 and program EXIT_SAPLRSAP_004 (ZXRSAU04).
    3. Run the program to generate the DataSource for the set hierarchy.
    4. The new DataSource is called 4R_GSBER_0000_HIER. GSBER is the data element of the field GLFUNCT-RBUSA and 0000 specifies the set class.
    hope IT Helps.. !!
    Regards
    Varun CN

Maybe you are looking for