JPopupMenu with a JScrollPane

I have couple of questions
1. I want to add a JScrollPane to JPopupMenu, doing this would not make the JPopupMenu visible. Is this doable?
2. this is not related to question 1
I have a JPOpupMenu with JMenuItems. When I select one of items and the item selected , I append the String to a JTextArea.
The focus goes back to th beginning of the textArea, I want the focus to be at the end of string that is appended to the textArea.
thanx

I might sounding dense here, but I tried all the suggestions, it does not help. The textArea does not even get displayed.
Also I noticed another thing, the JtextArea is registered with a mouseListener. But when I right click on JTextField , I get teh popup. Which is strange.
I have attached the code with the above suggestions.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class TextChooserDemo extends JFrame{
     private JTextField field;
     private JLabel label1;
     private JLabel label2;
     private JPanel aPanel ;
     private JPanel bPanel;
     private JTextArea textArea;
    private TextChooser chooser;
    public TextChooserDemo() {
        initComponents();
        chooser=new TextChooser(this,textArea);
    private void initComponents() {
          field = new JTextField(20);
          label1 = new JLabel("Label1");
          textArea = new JTextArea();
          aPanel = new JPanel();
          aPanel = new JPanel();
          aPanel.setLayout(new BorderLayout());
          aPanel.add(label1, BorderLayout.WEST);
          aPanel.add(field, BorderLayout.CENTER);
          label2 = new JLabel("Label2");
          bPanel = new JPanel();
          bPanel.setLayout(new BorderLayout());
          bPanel.add(label2, BorderLayout.WEST);
          aPanel.add(textArea, BorderLayout.CENTER);
        setTitle("Text-Chooser Demo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(aPanel,BorderLayout.NORTH );
        getContentPane().add(bPanel,BorderLayout.CENTER);
        //getContentPane().add(aPanel );
        //getContentPane().add(bPanel);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-500)/2, (screenSize.height-350)/2, 500, 350);
    public static void main(String args[]) {
        new TextChooserDemo().setVisible(true);
class TextChooser extends JWindow {
    public TextChooser(JFrame parent, JTextArea textArea){
        super(parent);
        this.parent=parent;
        this.textArea=textArea;
        initChooser();
    private void initChooser(){
        textArea.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent evt) {
                textAreaMouseReleased(evt);
        popupScrollPane = new JScrollPane();
        popupList = new JList();
        popupList.setModel(new AbstractListModel() {
            String[] strings = { "java ", "is ", "cool ", "and ", "nice ", "to ", "have ", "with ", "no ", "error ", ".\n" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings; }
popupList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
popupListAction(evt);
popupScrollPane.setViewportView(popupList);
getContentPane().add(popupScrollPane);
private void popupListAction(ListSelectionEvent evt) {
if (evt.getValueIsAdjusting() == false) {
textArea.append((String)popupList.getSelectedValue());
try{
textArea.setCaretPosition(textArea.getLineEndOffset(textArea.getLineCount()-1));
}catch(BadLocationException ex){ex.printStackTrace();}
setVisible(false);
textArea.requestFocus();
private void textAreaMouseReleased(MouseEvent evt) {
Point pnt = evt.getPoint();
int x = (int)pnt.getX()+(int)parent.getX();
int y = (int)pnt.getY()+(int)parent.getY()+20;
if( !contains(x,y) ){
setVisible(false);
if(evt.isPopupTrigger()){
setBounds(x,y,200,100);
setVisible(true);
private JFrame parent;
private JTextArea textArea;
private JScrollPane popupScrollPane;
private JList popupList;
thnx again!!!

Similar Messages

  • Probleme on JPopupMenu with JDialog

    I use JPopupMenu with JDialog. To display the popup, I use a mousePressed in a panel of the dialog:
    public void mousePressed(MouseEvent e) {
    if( e.getClickCount()==1 && e.getModifiers()==MouseEvent.BUTTON3_MASK && ga!=null ) {
         mpopup.show(e.getComponent(),e.getX(), e.getY());
    It works fine, but when a part of the popup is out of the dialog, the popup doesn't display.
    Is it normal?
    Has someone already had this problem?
    I work with jdk1.3.1_01
    Thanks for your help
    Templ

    When you create your popup menu do this :
    mpopup.setLightWeightPopupEnabled(false);
    I hope this helps,
    Denis

  • JPopupMenu with multiline JMenuItem ?

    Hi there.
    Is it possible to do something like the subject says, a JPopupMenu with multiline JMenuItem's, without using html? I would like to create a JMenuItem with a MultiLineLabel as the argument instead of a String. I'm trying to do this because if i add the MultiLineLabel directly to the JPopupMenu, it displays as i want, but i loose the behaviour inherent to a JMenuItem, the highlighted index, etc.. Any help would be appreciated.

    Here's a workaround:
    JPopupMenu popupMenu = new JPopupMenu();
    // Workaround to stop first menu item being selected
    JMenuItem dummyItem = popupMenu.add(new JMenuItem());
    dummyItem.setPreferredSize(new Dimension(0, 0));
    popupMenu.add("Item 1");
    popupMenu.add("Item 2");
    popupMenu.add("Item 3");
    It works for me!

  • JPopupMenu with JCheckBoxMenuItmes

    Hi,
    I have a JPopupMenu with JCheckBoxMenuItems and JMenuItems.
    The default behaviour of the JPopupMenu is, that it closes on selection of a MenuItem. This behaviour is not really nice for the CheckBoxMenuItems !
    Does anyone know a workaround?
    Thanks,
    Elke

    I don't have a workaround, sorry. But I think thats not needed too. The behavior you don't seem to like, is consistent with every application I ever used.
    When I click on a menuitem, the only actions I expect is that either the menu closes and a command is executed, or another pop-up menu appears where I make my choice.
    If you had a menu that doesn't close when you select or deselect a CheckBoxMenuItem, how do you close that menu? I think a MenuItem "Close this menu" would not be appreciated by any user. I use CheckBoxes on menus sparingly, and only for actions that generate an immediate visual response. (For instance Grayscale Image vs. Colored Image).
    If you want the user to have more control about options its better you create a small dialog with your choices and an accept/cancel set of buttons.
    Sorry I couldn't help with your initial question.

  • JPopupMenu with JScrollPane

    Hi,
    How can I add a scroll in a JPopupMenu???????
    Thanks,

    Hi,
    How can I add a scroll in a JPopupMenu???????
    Thanks,

  • JPopupMenu with JInternalFrame, popup menu doesn't work

    hi, i have this problem, as shown in the sample code at the end of this post.. basically, i have a table, and i added a JPopupMenu onto the table.. the popup menu works well when running the table class, though, when i call the table class in a JInternalFrame environment, the popup menu won't work.. anyone know why?
    ///Basic sample table code, when run this alone, the popup menu will work
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableBasic extends JPanel
         private JTable table;
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        { new Date(), "B", new Integer(2), Boolean.FALSE },
                        { new Date(), "C", new Integer(9), Boolean.TRUE },
                        { new Date(), "D", new Integer(4), Boolean.FALSE}
              table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public void createPopupMenu()
              JMenuItem menuItem;
              //Create the popup menu.
              JPopupMenu popup = new JPopupMenu();
              menuItem = new JMenuItem("A popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              menuItem = new JMenuItem("Another popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              //Add listener to the text area so the popup menu can come up.
              MouseListener popupListener = new PopupListener(popup);
              table.addMouseListener(popupListener);
         public static void main(String[] args)
              JFrame frame = new JFrame();
              TableBasic table = new TableBasic();
              table.createPopupMenu();
              frame.setContentPane(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         class PopupListener extends MouseAdapter
              JPopupMenu popup;
              PopupListener(JPopupMenu popupMenu)
                   popup = popupMenu;
              public void mousePressed(MouseEvent e)
                   maybeShowPopup(e);
              public void mouseReleased(MouseEvent e)
                   maybeShowPopup(e);
              private void maybeShowPopup(MouseEvent e)
                   if (e.isPopupTrigger())
                        popup.show(e.getComponent(), e.getX(), e.getY());
    ///when integrate the previous table into here, popup menu won't work
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameBasic
         extends JFrame
         //implements ActionListener
         private JDesktopPane desktop;
         private JInternalFrame menuWindow;
         public static final int desktopWidth = 800;
         public static final int desktopHeight = 700;
         public InternalFrameBasic(String title)
              super(title);
              //Set up the GUI.
              desktop = new JDesktopPane();
              desktop.putClientProperty("JDesktopPane.dragMode", "outline");
              //Because we use pack, it's not enough to call setSize.
              //We must set the desktop's preferred size.
              desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
              setContentPane(desktop);
              createMenuWindow();
              desktop.add(menuWindow); //DON'T FORGET THIS!!!
              Dimension displaySize = menuWindow.getSize();
              menuWindow.setSize(desktopWidth, displaySize.height);
         private void createMenuWindow()
              menuWindow =
                             new JInternalFrame("Event Watcher", true, //resizable
                                                                                                   true, //closable
                                                                                                   false, //not maximizable
                                                                                                   true); //iconifiable
              menuWindow.setContentPane(new TableBasic());
              menuWindow.pack();
              menuWindow.setVisible(true);
          * Create the GUI and show it.  For thread safety,
          * this method should be invoked from the
          * event-dispatching thread.
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new InternalFrameBasic("Example Internal Frame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    table.createPopupMenu();The above line should not be in the main method. It should be in the constructor class of TableBasic.
    You never execute that method in your InternalFrameBasic class to the mouse listener never gets added to the table.

  • JPopupMenu with a submenu (doesn't work)

    I have a JPopupMenu that displays some info for me and I would like to add a submenu but it doesn't seem to work. I can successfully add the submenu but it doesn't "expand" when I mouse over the submen.
    JPopupMenu pm = new JPopupMenu();
    JMenu submenu = new JMenu("submenu");
    JMenuItem jmi = new JMenuItem(...);
    submenu.add(jmi);
    pm.add(submenu);The popup menu looks as it should and the only thing that is missing is the action that should expand the submenu when I mouse over (and clicking doesn't work either).
    Any ideas?

    I don't think it is my code because I have tried it with other JPopupMenu stuff and it never works. Here is a simple working example of it. If you can modify this code to work I will be a bielver...
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    public class PopUpMenuTest extends JPanel implements MouseListener, MouseMotionListener {
       private JPopupMenu jpm;
       private JFrame frame;
       public PopUpMenuTest() {
          super();
          addMouseListener(this);
          addMouseMotionListener(this);
          JFrame.setDefaultLookAndFeelDecorated(true);
          frame = new JFrame("Testing PopUpMenuTest");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setContentPane(this);
          frame.setSize(600, 400);
          frame.setVisible(true);
       public static void main(String[] args) {
          new PopUpMenuTest();
       public void mouseClicked(MouseEvent me) {
          System.out.println("Mouse clicked...");
          jpm = new JPopupMenu();
          jpm.setLightWeightPopupEnabled(false);
          jpm.add(new JMenuItem("Testing 1"));
          jpm.add(new JMenuItem("Testing 2"));
          jpm.addSeparator();
          JMenu submenu = new JMenu("A submenu");
          JMenuItem menuItem1 = new JMenuItem("An item in the submenu");
          submenu.add(menuItem1);
          JMenuItem menuItem2 = new JMenuItem("Another item");
          submenu.add(menuItem2);
          jpm.add(submenu);
          jpm.setVisible(true);
          jpm.setLocation(frame.getX()+me.getX(), frame.getY()+me.getY());
          jpm.setVisible(true);
       public void mouseMoved(MouseEvent arg0) {
          if (jpm != null) {
             jpm.setVisible(false);
             jpm = null;
       public void mouseEntered(MouseEvent arg0) {}
       public void mouseExited(MouseEvent arg0) {}
       public void mousePressed(MouseEvent arg0) {}
       public void mouseReleased(MouseEvent arg0) {}
       public void mouseDragged(MouseEvent arg0) {}
    }

  • A small problem with a JScrollPane and child windows

    Hi !
    I have created a customized JComponent inside a JScrollPane and when my application starts I create two JTextField's that I put in the JComponent and so far it all works fine to start with, but when ever the JComponent is redrawn after that the JTextField's are overdrawn or at least are not visible any longer...
    Do I need to repaint the sub components of my own JComponent myself or am I doing something very wrong here ?
    a JScrollPane
    a JComponent with some drawing going on in paint()
    a JTextField
    another JTextField
    Mikael

    Ooppps !
    Forget about it, I forgot to put a super.paint( g) at the top of my paint method, that was the problem.
    Mikael

  • JPopupMenu with submenu

    Hello,
    I have a grid of buttons. If the user clicks a button with the right mouse button,
    a JPopupMenu shows up. The popup menu includes also 2 submenus (JMenu).
    When the user selects a menuitem, I need to know which was the selected button,
    because it identifies the object on which the operation has to be performed.
    If the menuitem is not in a submenu, I can get the button using
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) popup.getInvoker();But if the selected menuitem is in the submenu, popup.getInvoker returns the JMenu (submenu)
    and not the button.
    How do I get which button was pressed?
    thanks Marina

    Sorry it is not clear to me how.
    This is the code that shows the popup
    mb.addMouseListener( new java.awt.event.MouseListener() {
              public void mouseEntered(MouseEvent e) {
              public void mouseExited(MouseEvent e) {
              public void mouseReleased(MouseEvent e) {
              public void mouseClicked(MouseEvent e) {
                   if (e.getButton() == MouseEvent.BUTTON3)
                        JButton button = (JButton)e.getSource();
                        if (button.isEnabled())
                             mcPopup.show(button,0,button.getHeight());
              public void mousePressed(MouseEvent e) {
    The different clicks are then handled by the ActionListener:     if(actionString.equals("ccbinfo")) //default action for left click on the button
                   b = (JButton) arg0.getSource();
              else if (actionString.contains("power")) //action for submenu items
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) ?
              else // action for popup items (not in submenu)
                   menuItem = (JMenuItem) arg0.getSource();
                   JPopupMenu popup = (JPopupMenu) menuItem.getParent();
                   b = (JButton) popup.getInvoker();
    In the ActionListener the button information from the MouseClicked event is not available,
    how do I pass the button info to the menu?
    The menu is constructed only once, and the attached to the button only when right clicked.     private void buildPopupMenu()
              mcPopup = new JPopupMenu();
              pwrOnPopup = new JMenu("Power on"); //submenu
              pwrOffPopup = new JMenu("Power off"); //submenu
    ... //build and add items
         mcPopup.add(pwrOnPopup);
         mcPopup.add(pwrOffPopup);
    thanks Marina                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem with the JScrollPane...

    Hi there!
    I have a little problem controling the JScrollPane.
    In some class - which extends the JPanel class - I build the GUI within the constructor.
    This class is later included by another class into the center of a border layout. Now when
    I make this whole window visible, everything looks fine except that the scrollpane scrolled
    down to approx. 3/4 of the panel, but I want the Scrollpane to scroll all the way to the top...
    I already tried to manage this by using
    scrollPane.getVerticalScrollBar().setValue(0);
    But this does not do anything as long as I am calling this function from within the constructor.
    When I trigger this function by pressing some JButton it works fine!
    I guess this has something to do with the way Java paints the Frames and the Panels. And that
    maybe the Scrollpane is not yet existend as such when I try to scroll all the way to the top....
    Do you have any suggestions??
    Thx in advance!!

    But this does not do anything as long as I am calling this function from within the constructor.
    scrollPane.getVerticalScrollBar().setValue(0);Try wrapping the above line in a SwingUtilities.invokeLater(...)
    or maybe using
    component.scrollRectToVisible(...);

  • JSplitPane with 2 JScrollPanes sincroniced

    Hi everyone,
    I have a problem, and I haven't been able to solve it yet, this is it: I have a SplitPane, on its left side I have a jTable, and on its rigth side I have a jPanel with labels, I need them to have independent horizontal Scrolls but I need one only vertical Scroll at the rigth so they move in a sincroniced way.
    I've tried using one Scroll Pane for all the Split Pane but then I Scroll both the titles of the jTable and the jPanel and I need them where they are.
    Now I have the split pane with two Scroll Panes one with the table and the other with the Panel I think I have to make one of my Scrolls listen to the other and scroll by what it hears but I don't know how to do that... Which method should I rewrite? what do I need to implement to listen to the Scroll in an other Scroll pane?
    Can any one help me?

    Create a ChangeListener and add it to the JViewPort of the first scrollpane, then update the viewport of the second scrollpane when you receive a ChangeEvent. If the underlieing data sources of the viewports are the same size you can simply copy the height of the location of the first viewport to the second, if they are not the same you have to add some compensation for this. Look at the getViewPosition() and setViewPosition() methods of JViewPort.
    Jurgen

  • Probably an easy problem with a JScrollPane

    Hi,
    I would like to scroll a JScrollPane from outside my JScrollPane, of course I could used the setValue of the JScrollBar but I would prefer to simulate a click on the up/down buttons of my bar. Does anyone can help me?
    Thanks.
    S�bastien

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class souptier extends JFrame implements ActionListener {
      JScrollPane scrollPane;
      JButton
        upButton,
        downButton;
      JRadioButton
        unitButton,
        blockButton;
      public souptier() {
        upButton = new JButton("Up");
        upButton.addActionListener(this);
        downButton = new JButton("Down");
        downButton.addActionListener(this);
        ButtonGroup group = new ButtonGroup();
        unitButton = new JRadioButton("unit");
        group.add(unitButton);
        blockButton = new JRadioButton("block");
        blockButton.setSelected(true);
        group.add(blockButton);
        JPanel buttonPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(0,0,0,45);
        buttonPanel.add(upButton, gbc);
        buttonPanel.add(downButton, gbc);
        gbc.insets = new Insets(0,0,0,0);
        buttonPanel.add(unitButton, gbc);
        buttonPanel.add(blockButton, gbc);
        JPanel panel = new JPanel(new GridBagLayout());
        gbc.insets = new Insets(0,50,0,0);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.gridwidth = gbc.REMAINDER;
        gbc.anchor = gbc.WEST;
        for(int j = 0; j < 20; j++)
          panel.add(new JLabel(String.valueOf(j)), gbc);
        panel.setBackground(Color.yellow);
        panel.setPreferredSize(new Dimension(1000,1000));
        scrollPane = new JScrollPane(panel);
        scrollPane.getVerticalScrollBar().setUnitIncrement(50);
        scrollPane.getVerticalScrollBar().setBlockIncrement(200);
        getContentPane().add(scrollPane, "Center");
        getContentPane().add(buttonPanel, "South");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400,300);
        setLocation(300,400);
        setVisible(true);
      public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        int inc;
        if(button == upButton) {
          JScrollBar vertBar = scrollPane.getVerticalScrollBar();
          int currentValue = vertBar.getValue();
          if(unitButton.isSelected())
            inc = vertBar.getUnitIncrement(-1);
          else
            inc = vertBar.getBlockIncrement(-1);
          if(currentValue + inc < vertBar.getMaximum())
            vertBar.setValue(currentValue + inc);
          else
            vertBar.setValue(vertBar.getMinimum());
        if(button == downButton) {
          JScrollBar vertBar = scrollPane.getVerticalScrollBar();
          int currentValue = vertBar.getValue();
          if(unitButton.isSelected())
            inc = vertBar.getUnitIncrement(1);
          else
            inc = vertBar.getBlockIncrement(1);
          if(currentValue - inc > vertBar.getMinimum())
            vertBar.setValue(currentValue - inc);
          else
            vertBar.setValue(vertBar.getMinimum());
      public static void main(String[] args) {
        new souptier();
    }

  • JOptionPane setMaximumSize with a JScrollPane as the object doesn't work

    I am trying to use a JOptionPane for error messages. I'm trying to make the JOptionPane dialog be a minimum of 500x100 and a maximum size of 500x450 depending on the amount of text in the JTextArea inside the JScrollPane that's being passed into JOptionPane. I've tried both JOptionPane.showMessagePane(), and instantiating a JOptionPane and then setting its maximumSize, neither of which work as expected. Here is the relevant code:
    public static void doCommonMessagePane( Component parent, String optMsg,
                                             String title, int msgType )
        JTextArea msg = new JTextArea( optMsg );
        JScrollPane jsp = new JScrollPane( msg );
        initOptionPaneComponents( msg, jsp );
        Dimension maxSize =new Dimension(500, 450) ;
        JOptionPane op = new JOptionPane(jsp, msgType);
        op.setMaximumSize(maxSize);
        op.revalidate();
        op.setVisible(true);
    //here is me also trying showMessageDialog
    //    JOptionPane.showMessageDialog(parent, jsp, title, msgType);
      private static void initOptionPaneComponents( JTextArea ta, JScrollPane sp )
              Color bg = UIManager.getColor( "Panel.background" );
              Dimension jspSz = new Dimension( 500, 75 );
              Dimension max = new Dimension( 500, 450 );
              ta.setMargin( new Insets( 5, 10, 10, 5 ) );
              ta.setColumns( 50 );
              ta.setLineWrap( true );
              ta.setWrapStyleWord( true );
              ta.setEditable( false );
              ta.setEnabled( false );
              ta.setBackground( bg );
              ta.setDisabledTextColor( Color.black );
              ta.setFont( UIManager.getLookAndFeelDefaults().getFont( "Dialog" ) );
              ta.setMaximumSize(max);
              ta.setMinimumSize(jspSz);
              sp.getViewport().add( ta );
         //sp.setPreferredSize( jspSz );
              sp.getViewport().setMaximumSize(max);
              sp.getViewport().setMinimumSize(jspSz);
              sp.setBorder( BorderFactory.createLoweredBevelBorder() );
              sp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );
         //     sp.setPreferredSize( jspSz );
           sp.setMinimumSize(jspSz);
              sp.setMaximumSize( max );
         }

    When the JScrollPane is placed into the CENTER position the JOptionPane ignores the maxSize of both the JScrollPane and the JTextArea and stretches both of these out to 500x700 so that all text is visible. You still miss the basic concept.
    The answer is it depends! First the size of the dialog needs to be determined.
    If you use dialog.pack() then the preferred size of all components is used to determine the size of the dialog and the scrollpane will be whatever preferred size you gave it. If you leave the preferred size at (0, 0) then the scrollpane and text area will be invisible.
    If you use dialog.setSize(???, ???), then the size of the scrollpane will be adjusted to fit the available space.
    The amount of text in the text area is irrelevant in determining the size of the scrollpane. It is relevant in determining whether scrollbars will appear or not once the scrollpane is displayed.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Help needed with a JScrollPane

    In the next example I have a small problem. I want that my scrollbar scroll back to 0 (vertical scrollbar) when i click on a item in the JList.
    so to see what i meen, you have to take the following steps to recreate the situation.
    - run the program
    - click on a item
    - scroll the vertical scrollbar to the half
    - click on the other item
    - And now the scrollbar needs to scroll back to 0 (this doesn't happen).
    I hope somebody know what I have to change.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.WindowEvent;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    public class Main extends JFrame{
        GridLayout gridLayout2 = new GridLayout();
        GridLayout gridLayout3 = new GridLayout();
        JPanel SubPanel1 = new JPanel();
        JPanel SubPanel2 = new JPanel();
        JList list = new JList();
        JScrollPane scrollPane = new JScrollPane(SubPanel2);
        public Main() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                jbInit();
            } catch (Exception ex) {
                ex.printStackTrace();
        public static void main(String[] args) {
            Main main = new Main();
            main.setVisible(true);
        private void jbInit() throws Exception {
            this.setTitle("HELP!!!!");
            this.setSize(350,350);
            this.getContentPane().setLayout(gridLayout2);
            this.setVisible(true);
            SubPanel2.setLayout(null);
            SubPanel1.setLayout(gridLayout3);
            this.getContentPane().add(list);
            SubPanel1.add(scrollPane);
            this.getContentPane().add(SubPanel1);
            ListModel listModel = new DefaultComboBoxModel(new String[] {
                                                           "Item One", "Item Two" });
            list.setModel(listModel);
            list.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent evt) {
                    listValueChanged(evt);
        protected void processWindowEvent(WindowEvent e) {
          super.processWindowEvent(e);
          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            System.exit(0);
        int i =0;
        public void listValueChanged(ListSelectionEvent e) {
            if(e.getValueIsAdjusting() == true){
                SubPanel2.removeAll();
                JPanel SubPanel3 = new JPanel();
                SubPanel3.setBounds(0, 100, 300, 200);
                SubPanel3.setBorder(BorderFactory.createTitledBorder("Panel 1" + i));
                JTextArea textArea1 = new JTextArea();
                SubPanel3.add(textArea1);
                textArea1.setText("12345");
                textArea1.setPreferredSize(new java.awt.Dimension(250, 80));
                textArea1.setFocusable(false);
                textArea1.setEditable(false);
                JPanel SubPanel4 = new JPanel();
                SubPanel4.setBounds(0, 320, 300, 200);
                SubPanel4.setBorder(BorderFactory.createTitledBorder("Panel 2" + i));
                JTextArea textArea2 = new JTextArea();
                SubPanel4.add(textArea2);
                textArea2.setText("67890");
                textArea2.setPreferredSize(new java.awt.Dimension(250, 80));
                textArea2.setEditable(false);
                textArea2.setFocusable(false);
                i++;
                SubPanel2.add(SubPanel3);
                SubPanel2.add(SubPanel4);
                SubPanel2.setPreferredSize(new Dimension(300, 500));
                SubPanel2.updateUI();
    }Greetings, Remco

    scrollPane.getViewport().setViewPosition(new Point(0, 0));
    SubPanel2.updateUI();Note:
    1) First character of a variable name should not be upper cased. (ie. SubPanel2 should be subPanel2.
    2) There is no need to override processWindowEvents to exit the application. Simple use the JFrame method:
    setDefaultCloseOperation( EXIT_ON_CLOSE );

  • GlassPane & JPopupMenu with child menus

    I've read the helpful posts on how to get a JPopupMenu to appear over the glasspane and handle mouse events (using setLightWeightPopupEnabled(false)).
    However, my JPopupMenu has child components that are JMenus. The JMenus now have the same problem of not responding to mouse events.
    How do I get JMenu to be heavyweight (or, is there a better way to do this whole thing)?

    FYI. I overcame this by going to a JLayeredPane rather than using the GlassPane.

Maybe you are looking for

  • Request timed out because there has been no reply from the server in 600000

    Issue: Request timed out because there has been no reply from the server in 600000 Scenario: 1. All the crystal reports are designed by using Crystal Report 2008 Version -- 12.3.0.601 2. All reports are uploaded to CMC (SAP Business Objects Enterpris

  • How do I install CC Photoshop Program?

    I've been trying to install the CC Photoshop Program on my desktop. I can save it,, but can't install it. Keep getting a 206 error message.

  • Acrobat 8: How to prevent "Combine Files" from adding a header?

    Hi All. I am using Acrobat 8 (Win XP SP II) and am having a problem with the "Combine Files" feature. In the past, I've used this function to create hundreds of PDF files from thousands of individiual PDF's. It worked great. But now, suddenly, Acroba

  • Ordering Book Error - an error occurred uploading your order

    I have searched high and low but cannot find a solution to this problem.  I am trying to order a photo book through iPhoto and keep getting the following error: "an error occurred uploading your order click retry to upload the failed asset..." I've t

  • Link in a work item

    Hi, within a task in a workflow I am checking whether stock is available for a particular material. If not then a worktitem (user decision) is generated with a link in the body of the message. On clicking on the link the material details for that par