Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / March 2008

Tip: Looking for answers? Try searching our database.

Text component not focusable (tabbed pane switching involved) try 2:     SSCCE

Thread view: 
Karsten Wutzke - 22 Mar 2008 13:30 GMT
Hello,

I'm referring to

http://groups.google.de/group/comp.lang.java.gui/browse_thread/thread/0adb1e99ab
16aca6
#

I have pasted a small self contained compilable example demonstrating
what I need.

The program appears big (200 lines), but the only interesting lines
are the stateChanged method ~40-50 lines, the rest is ONLY GUI setup.

I'd very much appreciate if some people could try this out.

Is there a solution? What is it?

Karsten

-----------------------------------------------------------------

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class JChatsTabbedPane extends JTabbedPane implements
ChangeListener, ContainerListener
{
    public static void main(String[] strArgs)
    {
        JFrame frm = new JFrame("Tab selection text component focus test");
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setSize(600, 480);

        final int MAX = 5;
        final JChatsTabbedPane ctp = new JChatsTabbedPane();
        frm.getContentPane().add(ctp);

        //build menu
        JMenuBar mb = new JMenuBar();

        JMenu mn = new JMenu("Menu");

        //add tab
        Action actAdd =
            new AbstractAction("Add tab")
            {
                public void actionPerformed(ActionEvent e)
                {
                    int tc = ctp.getTabCount();

                    if ( tc < MAX )
                    {
                        ctp.addTab("i = " + tc, null, new JChatPanel(tc), "tip");
                    }
                }
            };

        mn.add(new JMenuItem(actAdd));
        mn.addSeparator();

        //remove tabs
        for ( int i = 0 ; i < MAX ; i++ )
        {
            Action actRem =
                new AbstractAction("Remove tab #" + (i + 1))
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        int tc = ctp.getTabCount();

                        //String strName = ((JMenuItem)e.getSource()).getName();
                        String strName = e.getActionCommand();
                        int index = strName.charAt(strName.length() - 1) - 48; //hack:
char '0' is int 48

                        if ( tc > 0 )
                        {
                            ctp.removeTabAt(index);
                        }
                    }
                };

            //actRem.setProp("Remove tab " + i);
            JMenuItem mi = new JMenuItem(actRem);
            //mi.setName("Remove tab " + i);

            mn.add(mi);
        }

        mb.add(mn);

        frm.setJMenuBar(mb);
        frm.setVisible(true);
    }

    public JChatsTabbedPane()
    {
        //add change listener to selection model
        getModel().addChangeListener(this);
        addContainerListener(this);
    }

    public void stateChanged(ChangeEvent ce)
    {
        System.out.println("selection stateChanged");

        final SingleSelectionModel ssm = getModel();
        int tc = getTabCount();

        //one tab is displayed when chat list empty, so there's always a
selected index
        if ( tc > 0 )
        {
            int index = ssm.getSelectedIndex();

            System.out.println("Selected index is " + index);

            if ( index >= tc )
            {
                return;
            }

            //valid index...
            JChatPanel cp = (JChatPanel)getComponentAt(index);

            System.out.println("Requesting focus on " + getTitleAt(index));

            JTextComponent tcUserMessage = cp.getUserMessageTextComponent();

            //request focus on user message text component
            tcUserMessage.requestFocus();

            /*Document doc = tcUserMessage.getDocument();

            try
            {
                //prove we the right text component
                doc.insertString(doc.getEndPosition().getOffset(), "" + index,
null);
            }
            catch ( Exception e )
            {
                e.printStackTrace();
            }*/
        }

    }

    public void componentAdded(ContainerEvent ce)
    {
        //System.out.println("componentAdded");
    }

    public void componentRemoved(ContainerEvent ce)
    {
        //System.out.println("componentRemoved");
        //stateChanged(null);
    }

//inner class building the panels, not interesting!
public static class JChatPanel extends JPanel
{
    private final JTextComponent tcUserMessage;

    public JChatPanel(int i)
    {
        super(new BorderLayout());

        //chat messages text pane
        JTextComponent tcChatMessages = new JTextPane();
        tcChatMessages.setText("Welcome to chat " + i + "!\n\nspecialk >
hello\nagentk > hi specialk\n");
        tcChatMessages.setEditable(false);

        //user message text pane
        tcUserMessage = new JTextField("panel index = " + i + ": user enters
stupid things here");

        //chat messages scroller
        JScrollPane scrChatMessages = new JScrollPane();
        scrChatMessages.setViewportView(tcChatMessages);

        //user list always gets a scroller, horizontal scrolling depending
on subclass!
        JScrollPane scrUserList = new JScrollPane();
        scrUserList.setViewportView(new JList());

        //chat split pane
        JSplitPane splChat = new JSplitPane();
        splChat.setLeftComponent(scrChatMessages);
        splChat.setResizeWeight(0.8);
        splChat.setRightComponent(scrUserList);
        splChat.setEnabled(true);

        //main horizontal divider split pane
        JSplitPane splMain = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
true);
        splMain.setResizeWeight(0.9);
        splMain.setLeftComponent(splChat);
        splMain.setRightComponent(null); //divider not movable

        final JComponent cmpMain;

        //user messages view
        cmpMain = new JPanel(new BorderLayout());
        cmpMain.add(splMain);
        cmpMain.add(tcUserMessage, BorderLayout.SOUTH);

        //add
        add(cmpMain);
    }

    public JTextComponent getUserMessageTextComponent()
    {
        return tcUserMessage;
    }

}

}
Andrew Thompson - 22 Mar 2008 14:38 GMT
> Hello,
>
> I'm referring to

Sub: Text component not focusable (tabbed pane switching involved) try
2: SSCCE

Hey Karsten.  I try to look in on any thread that
mentions SSCCE in the title.  An SSCCE is intended
to either
a) solve the problem for you, or..
b) make it easy for others to see what the
problem is.

Unfortunately, there are two problems with the
code you posted that inhibit that goal..

1) That code is *far* too wide and line wraps.
Line wrap causes all sorts of problems to code
examples.  I recommend that no line be wider than
72 chars (less, if practical) but as I looked through
the 21 compilation errors that copy/pasted  code
produced, it was obvious the *indent* of some lines
was 67 chars!

2) A 'proper' news client will understand that a post
might end with '}' but damnable GG screws it up.
If you add a 'sig.', even poor (retarded) GG
gets it right.  Please include a sig. after
the end of your message.  (Awaits the torrent of
abuse for daring suggest anybody cater to GG
or their users).

Please consider making code lines much shorter,
and adding a sig., in future posts.

--
Andrew T.
PhySci.org
Karsten Wutzke - 22 Mar 2008 18:10 GMT
> > Hello,
>
[quoted text clipped - 31 lines]
> Please consider making code lines much shorter,
> and adding a sig., in future posts.

OK that was a little dirty... try #3:

Hope this works now...

Karsten

--------------------------------------

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class JChatsTabbedPane extends JTabbedPane
implements ChangeListener, ContainerListener
{
   public static void main(String[] strArgs)
   {
       JFrame frm = new JFrame("Tab selection text pane focus test");
       frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frm.setSize(600, 480);

       final int MAX = 5;
       final JChatsTabbedPane ctp = new JChatsTabbedPane();
       frm.getContentPane().add(ctp);

       //build menu
       JMenuBar mb = new JMenuBar();

       JMenu mn = new JMenu("Menu");

       //add tab
       Action actAdd =
           new AbstractAction("Add tab")
           {
               public void actionPerformed(ActionEvent e)
               {
                   int tc = ctp.getTabCount();

                   if ( tc < MAX )
                   {
                       JChatPanel cp = new JChatPanel(tc);
                       ctp.addTab("i = " + tc, null, cp, "tip");
                   }
               }
           };

       mn.add(new JMenuItem(actAdd));
       mn.addSeparator();

       //remove tabs
       for ( int i = 0 ; i < MAX ; i++ )
       {
           Action actRem =
               new AbstractAction("Remove tab #" + (i + 1))
               {
                   public void actionPerformed(ActionEvent e)
                   {
                       int tc = ctp.getTabCount();

                       String str = e.getActionCommand();
                       //hack: char '0' is int 48
                       int index = str.charAt(str.length() - 1) - 48;

                       if ( tc > 0 )
                       {
                           ctp.removeTabAt(index);
                       }
                   }
               };

           //actRem.setProp("Remove tab " + i);
           JMenuItem mi = new JMenuItem(actRem);
           //mi.setName("Remove tab " + i);

           mn.add(mi);
       }

       mb.add(mn);

       frm.setJMenuBar(mb);
       frm.setVisible(true);
   }

   public JChatsTabbedPane()
   {
       //add change listener to selection model
       getModel().addChangeListener(this);
       addContainerListener(this);
   }

   public void stateChanged(ChangeEvent ce)
   {
       System.out.println("selection stateChanged");

       final SingleSelectionModel ssm = getModel();
       int tc = getTabCount();

       //one tab is displayed when chat list empty,
       //so there's always a selected index
       if ( tc > 0 )
       {
           int index = ssm.getSelectedIndex();

           System.out.println("Selected index is " + index);

           if ( index >= tc )
           {
               return;
           }

           //valid index...
           JChatPanel cp = (JChatPanel)getComponentAt(index);

           System.out.println("Requesting focus on "
                              + getTitleAt(index));

           JTextComponent tcUserMessage =
               cp.getUserMessageTextComponent();

           //request focus on user message text component
           tcUserMessage.requestFocus();

           /*Document doc = tcUserMessage.getDocument();

           try
           {
               //prove we the right text component
               doc.insertString(doc.getEndPosition().getOffset(),
                                "" + index, null);
           }
           catch ( Exception e )
           {
               e.printStackTrace();
           }*/
       }

   }

   public void componentAdded(ContainerEvent ce)
   {
       //System.out.println("componentAdded");
   }

   public void componentRemoved(ContainerEvent ce)
   {
       //System.out.println("componentRemoved");
       //stateChanged(null);
   }

//inner class building the panels, not interesting!
public static class JChatPanel extends JPanel
{   //too lazy to indent!

   private final JTextComponent tcUserMessage;

   public JChatPanel(int i)
   {
       super(new BorderLayout());

       String str =   "Welcome to chat " + i + "!\n"
                    + "\n"
                    + "specialk > hello\n"
                    + "agentk > hi specialk\n";

       //chat messages text pane
       JTextComponent tcChatMessages = new JTextPane();
       tcChatMessages.setText(str);
       tcChatMessages.setEditable(false);

       //user message text pane
       tcUserMessage = new JTextField(  "panel index = " + i
                                      + ": user writes here");

       //chat messages scroller
       JScrollPane scrChatMessages = new JScrollPane();
       scrChatMessages.setViewportView(tcChatMessages);

       //user list
       JScrollPane scrUserList = new JScrollPane();
       scrUserList.setViewportView(new JList());

       //chat split pane
       JSplitPane splChat = new JSplitPane();
       splChat.setLeftComponent(scrChatMessages);
       splChat.setResizeWeight(0.8);
       splChat.setRightComponent(scrUserList);
       splChat.setEnabled(true);

       //main horizontal divider split pane
       JSplitPane splMain = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                           true);
       splMain.setResizeWeight(0.9);
       splMain.setLeftComponent(splChat);
       splMain.setRightComponent(null); //divider not movable

       final JComponent cmpMain;

       //user messages view
       cmpMain = new JPanel(new BorderLayout());
       cmpMain.add(splMain);
       cmpMain.add(tcUserMessage, BorderLayout.SOUTH);

       //add
       add(cmpMain);
   }

   public JTextComponent getUserMessageTextComponent()
   {
       return tcUserMessage;
   }

}

}
Karsten Wutzke - 22 Mar 2008 18:33 GMT
> > > Hello,
>
[quoted text clipped - 249 lines]
> }
> }

To make the program a little better you might add

private static int added = 0;

just before main() and replace the "add tab" action

       //add tab
       Action actAdd =
           new AbstractAction("Add tab")
           {
               public void actionPerformed(ActionEvent e)
               {
                   int tc = ctp.getTabCount();

                   if ( tc < MAX )
                   {
                       JChatPanel cp = new JChatPanel(added);
                       ctp.addTab("i = " + added++, null, cp, "tip");
                   }
               }
           };

Like this a global counter is used for new tabs which is better. But
the program should demonstrate well enough what is going on. Focus is
on why requestFocus doesn't work on the text field at the bottom
(returned from each chat panel).

Karsten
Karsten Wutzke - 22 Mar 2008 18:34 GMT
Oops sry forgot to remove the full quote...


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.