GridBagLayout with JScrollPane difficulties

I'm having problems getting the components in a JPanel to layout properly. I'm using GridBagLayout and I'm having problems with adding a JScollPane.
The JScrollPane in the layout (holding a subclass of a JPanel as its viewport) does not work properly in some case. When the viewport won't display fully, and requires scroll bars, the JScrollPane shrinks to a tiny size (i think just enough to display minimized scroll bars). What do I mean to add to fix this problem?
Here is the relavent code:
public ScenePanel()
     SceneImagePanel sceneImagePanel = new SceneImagePanel("Images/library.jpg");
     JScrollPane sceneScroller = new JScrollPane(sceneImagePanel);
     GridBagLayout gridbag = new GridBagLayout();
     GridBagConstraints c = new GridBagConstraints();
     this.setLayout(gridbag);
     c.insets = new Insets(5,5,5,5);
     JButton b1 = new JButton("Left");
     c.anchor = GridBagConstraints.WEST;
     c.fill = GridBagConstraints.VERTICAL;
     c.gridx = 0;
     c.gridy = 0;
     c.gridwidth = 5;
     c.gridheight = 5;
     c.weightx = 0.5;
     c.weighty = 0.5;
     gridbag.setConstraints(b1, c);
     this.add(b1);
     c.anchor = GridBagConstraints.CENTER;
     c.fill = GridBagConstraints.NONE;
     c.gridx = 5;
     c.gridwidth = 10;
     c.weightx = 0.0;
     c.weighty = 0.0;
     gridbag.setConstraints(sceneScroller, c);
     this.add(sceneScroller);
     JButton b2 = new JButton("Right");
     c.anchor = GridBagConstraints.EAST;
     c.fill = GridBagConstraints.VERTICAL;
     c.gridx = 15;
     c.gridwidth = 5;
     c.weightx = 0.5;
     c.weighty = 0.5;
     gridbag.setConstraints(b2, c);
     this.add(b2);
     JButton b3 = new JButton("Bottom");
     c.anchor = GridBagConstraints.SOUTH;
     c.fill = GridBagConstraints.HORIZONTAL;
     c.gridwidth = 20;
     c.gridx = 0;
     c.gridy = 5;
     c.weighty = -0.5;
     gridbag.setConstraints(b3, c);
     this.add(b3);
//          this.add(sceneScroller, BorderLayout.CENTER);
}Note: the commented out line at the end displayed the JScrollPane properly (though I want the scroll pane to be sized to fit its viewport, not its container, so I stopped using BorderLayout)

Alright, I've figured out why the JScrollPane gets shrunk to such a small size...the 'fill' paramenter of the constraint can't be set to NONE. I've set it to 'BOTH' and changed the other constraints of some other components to fit.
The problem now is that the scroll pane is too big...the scroll pane does not need to actually have either scroll bar in all cases. To accomidate these situations, I want the scroll pane to only be as large as it needs to be to display as much of its viewport is possible. Meaning, if the viewport does not need the scroll pane to take up as much room as is avaliable to it in the JPanel, the scroll pane should only be as large as needed, and leave empty space around it.
Here is what I have now:
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
this.setLayout(gridbag);
c.insets = new Insets(5,5,5,5);
JButton b1 = new JButton("Left");
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.VERTICAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 5;
c.gridheight = 5;
c.weightx = -0.5;
c.weighty = 0.5;
gridbag.setConstraints(b1, c);
this.add(b1);
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.BOTH;
c.gridx = 5;
c.gridwidth = 10;
c.weightx = 0.5;
gridbag.setConstraints(sceneScroller, c);
this.add(sceneScroller);
JButton b2 = new JButton("Right");
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.VERTICAL;
c.gridx = 15;
c.gridwidth = 5;
c.weightx = -0.5;
c.weighty = 0.5;
gridbag.setConstraints(b2, c);
this.add(b2);
JButton b3 = new JButton("Bottom");
c.anchor = GridBagConstraints.SOUTH;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 20;
c.gridx = 0;
c.gridy = 5;
c.weighty = -0.5;
gridbag.setConstraints(b3, c);
this.add(b3);

Similar Messages

  • Controlling amount of rows in a jtextfield with jscrollpane

    As part of a school assignment, I we have output going to a textfield that is scrolled with JScrollPane. Part of it is for when it comes to 400 lines, and another line is added, that the first line of the output is erased, and the new one is added. Are there simple methods of the API to do this, or should I perhaps store all the output in a string, use an int to count, and then substring it to the first \n ?
    Thanks for the replies. Please dont give me direct answers, but help to find the answer, as I do not want to cheat.

    While I did not do a SSCCE, mine is not overly complicated on output. The first part of this was building a console client to connect to a server. This part is adding a GUI to it, with a bit of extra functionality. My writeMessage method of the console did a System.out.println. It now does a output.setText(output.getText() + "\n"+ date + msg); msg being the String parameter in the method. output is the JTextArea I have, and is passed to my Client object.
    The output works fine, its just trying to cut the first line out when max is reached. Just doing 20 lines for now. I tried adding this, but it started cutting more and more off the start of the text.
    if(output.getLineCount() > 20) {
         try {
              int firstRow = output.getLineEndOffset(0);
              output.setText(output.getText().substring(0, firstRow));
         catch(BadLocationException e) {
              e.printStackTrace();
    }Edited by: agm_ultimatex on Jun 29, 2009 12:35 PM

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • Error using JTextArea with JScrollPane

    hi,
    I am using JTextArea with JScrollpane. I am getting a problem in selecting the text in text area. I am searching for some text in the text area and selecting it if search successful. The problem is that the the scrollbar position didnt set to the correct location. So sometime the text selected is not visible in the scrolpane. Any help regarding this will be highly appreciated.
    Regards
    Danish

    What about sth like this:Rectangle r = textarea.modelToView(textarea.getSelectionStart());
    scrollpane.scrollRectToVisible(r);Just a guess, no idea whether it works.

  • Help with JScrollPane

    I have a JScrollPane that I need to add multiple components to. That includes 5 JButtons, and 5 Jtree's.
    I need to add all of the components at once, making the JTree's visible and invisible by clicking the JButton's. My first problem is when I try to add multiple objects to the JScrollPane using the default layout manager. The last object added is always stretched to fill the entire viewport. This makes the objects first added un-viewable. So I decided to first add all of the objects to a Box then add the Box to the scrollpane.
    My second problem occurs when I make a JTree visible, aftering adding it to the Box. It draws the tree completely from top to bottom as it should, but clips the right end of titles on the nodes. The horizontal scroll adjusts enought so that you can scroll far enough to the right, but the titles are cut off.
    If I add one of the JTree's directly to the JScrollPane it behaves as it should, showing the complete node titles.
    I've tried revalidating, updating, and repainting without success.
    So, first question is can multiple objects be added to a JScrollPane using the default layout manager, without having the last object hide the previously added objects?
    Secondly, does anyone know why nodes in a JTree would be clipped when added to a Box then added the Box added to a JScrollPane. And more importantly how to fix it.
    Any help would be appreciated,
    Thanks,
    Jim

    Hi there
    Im not sure on exactly what you are trying to do.
    But if you want multiple components in one JScrollPane
    I would use a JPanel that I would add to the JScrollPane
    On that JPanel I would then add my components.
    I would also use GridBagLayout instead of any other layout manager. Thats because it is the most complex
    layout manager and it will arrange the components as I whant.
    If you whant to be able to remove a component from the view by making them invisible. I think I would consider
    JLayeredPane.
    on a JLayeredPane you add components on different layers. Each component is positionend exactly with setLocation or setBounds. This is the most exact thing to use. The JLayeredPane uses exact positioning of its components. which can be usefull when you use
    several components that will be visible at different times
    /Markus

  • Issues with JScrollPane

    Hi everybody
    I created a class to display help dialogs dynamically created, because I'll need lots of help windows.
    I decided to created it based on 2-dimensional arrays of data. Up till here, everything is fine.
    But I'm facing some problems with the GUI, basically my scroll pane. my problems:
    - first, the vertical scrollbar was not being displayed, which I fixed setting the panel size with the viewport width, but that leaves me the problem of the height... it will change because of the width, and I don't know what value to use...
    - changing between pages, my scroll bar goes to different values, and setting its value to 0 doesn't help...
    - if there the window is made very small, sometimes some of the components placed inside the helpPanel overlaps each other... is there a way to fully avoid that?
    my class code:
    import java.awt.Component;
    import java.awt.Dialog;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.text.Document;
    public class HelpWindow extends JDialog implements ActionListener {
        private Object[][] helpData;
        private JPanel helpPanel;
        private JButton /*closeButton,*/ nextButton, prevButton;
        JScrollPane helpScrollPane;
        private int currentHelpDataIndex;
        public HelpWindow(Dialog owner, Object[][] helpData) {
            super(owner,"Help",true);
            if (helpData.length < 1) {
                throw new IllegalArgumentException("the help data cannot be empty");
            for (Object[] oa : helpData) {
                if (oa.length < 1)
                    throw new IllegalArgumentException("no help data page can be empty");
                for (Object o : oa) {
                    if (o == null)
                        throw new NullPointerException();
            this.helpData = helpData;
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            initGUI();
            currentHelpDataIndex = 0;
            updateGUI();
        private void initGUI() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            //help panel
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1;
            gbc.weighty = 1;
            helpPanel = new JPanel();
            helpScrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            helpScrollPane.getViewport().setView(helpPanel);
            add(helpScrollPane,gbc);
            //buttons panel
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 0;
            gbc.weighty = 0;
            gbc.gridy = 1;
            JPanel buttonsPanel = new JPanel();
            buttonsPanel.setLayout(new GridBagLayout());
                GridBagConstraints gbcBp = new GridBagConstraints();
                //next/previous buttons
                gbcBp.fill = GridBagConstraints.HORIZONTAL;
                gbcBp.weightx = 1;
                prevButton = new JButton("<<");
                prevButton.setEnabled(false);
                prevButton.addActionListener(this);
                buttonsPanel.add(prevButton,gbcBp);
                nextButton = new JButton(">>");
                nextButton.setEnabled(false);
                nextButton.addActionListener(this);
                gbcBp.gridx = 1;
                buttonsPanel.add(nextButton,gbcBp);
                /*//close button
                gbcBp.fill = GridBagConstraints.NONE;
                closeButton = new JButton("Close");
                closeButton.addActionListener(this);
                gbcBp.gridx = 0;
                gbcBp.gridy = 1;
                gbcBp.gridwidth = 2;
                buttonsPanel.add(closeButton,gbcBp);*/
            add(buttonsPanel,gbc);
            addComponentListener(new ComponentListener(){
                public void componentResized(ComponentEvent e) {
                    helpPanel.setPreferredSize(
                            new Dimension(
                                    (int)helpScrollPane.getViewport().getPreferredSize().getWidth(),
                                    (int)helpPanel.getPreferredSize().getHeight())
                    helpPanel.revalidate();
                public void componentMoved(ComponentEvent e) {}
                public void componentShown(ComponentEvent e) {}
                public void componentHidden(ComponentEvent e) {}
        private void updateGUI() {
            updateHelpData();
            updateNavigationButtons();
        private void updateHelpData() {
            helpPanel.removeAll();
            helpPanel.repaint();
            //insert data again
            Object[] data = helpData[currentHelpDataIndex];
            helpPanel.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1;
            //gbc.weighty = 1;
            for (int i = 0; i < data.length; i++) {
                Object currentData = data;
    gbc.gridy = i;
    //images - turned into labels
    if (currentData instanceof Image) {
    JLabel label = new JLabel();
    label.setIcon(new ImageIcon((Image)currentData));
    currentData = label;
    if (currentData instanceof Component) {
    //components - added as-is
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.CENTER;
    //gbc.weightx = 1;
    helpPanel.add((Component)currentData,gbc);
    } else {
    //everyting else - as text
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    //gbc.weightx = 0;
    JTextArea textArea;
    if (currentData instanceof Document) {
    textArea = new JTextArea((Document)currentData);
    } else {
    textArea = new JTextArea(currentData.toString());
    textArea.setOpaque(false);
    textArea.setFocusable(false);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    helpPanel.add(textArea,gbc);
    helpScrollPane.getVerticalScrollBar().setValue(0);
    validate();
    private void updateNavigationButtons() {
    prevButton.setEnabled(currentHelpDataIndex != 0);
    nextButton.setEnabled(currentHelpDataIndex < helpData.length-1);
    public void actionPerformed(ActionEvent e) {
    JButton source = (JButton)e.getSource();
    /*if (source == closeButton) {
    dispose();
    } else*/ if (source == nextButton) {
    currentHelpDataIndex++;
    updateGUI();
    } else if (source == prevButton) {
    currentHelpDataIndex--;
    updateGUI();
    public static void main(String[] args) {
    HelpWindow window = new HelpWindow(
    new JDialog(),
    new Object[][]
    {"Java Technology\nSun's home for Java. Offers Windows, Solaris, and Linux Java Development Kits (JDKs), extensions, news, tutorials, and product information.\njava.sun.com/ - 26k - 17 Oct 2006 - Cached - Similar pages",
    "The Java� Tutorials\nFrom the download page, you can download the Java Tutorials for browsing ... The Java Tutorials are practical guides for programmers who want to use the ...\njava.sun.com/docs/books/tutorial/index.html - 13k - Cached - Similar pages\n[ More results from java.sun.com ]",
    new JButton("some button"),
    "Sun Microsystems\nSun Java Enterprise System Every time you log on to My Sun Connection (MSC), you're using Sun Java Enterprise System (JES) products. ...\nwww.sun.com/ - 15k - Cached - Similar pages"},
    {"another page...",
    new JCheckBox("something")}
    window.pack();
    window.setVisible(true);
    System.exit(0);
    many thanks in advance!

    Why are you doing it this way? It is just a help
    displayer right? It would be simplier to just keep
    it as text. Or create an object that can add itself.
    I veiw the instanceof Operator as a bad smell.I did this mainly because these help windows will surely contain images along with the text... so to avoid creating tons of windows, I choose to create this class.
    Did you try using a borderlayout instead of the
    gridbag?
    Put the ScrollPane in the center with the button
    panel at PAGE_END.No use. The problem is the layout management inside helpPanel.
    Messing around, the only (dirty) working solution was recreating the help panel at each resize, and using grid bag for the panel, instead of box layout. And the problem about the scroll bar value is still there...
    It's a workaround... if someone know a better way, tell me please...
    current code:
    import java.awt.Component;
    import java.awt.Dialog;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.text.Document;
    public class HelpWindow extends JDialog implements ActionListener {
        private Object[][] helpData;
        private JPanel helpPanel;
        private JButton /*closeButton,*/ nextButton, prevButton;
        JScrollPane helpScrollPane;
        private int currentHelpDataIndex;
        public HelpWindow(Dialog owner, Object[][] helpData) {
            super(owner,"Help",true);
            if (helpData.length < 1) {
                throw new IllegalArgumentException("the help data cannot be empty");
            for (Object[] oa : helpData) {
                if (oa.length < 1)
                    throw new IllegalArgumentException("no help data page can be empty");
                for (Object o : oa) {
                    if (o == null)
                        throw new NullPointerException();
            this.helpData = helpData;
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            initGUI();
            currentHelpDataIndex = 0;
            updateGUI();
        private void initGUI() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            //help panel
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1;
            gbc.weighty = 1;
            helpPanel = new JPanel();
            helpScrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            helpScrollPane.getViewport().setView(helpPanel);
            //helpScrollPane.setPreferredSize( new Dimension(300, 300) );
            add(helpScrollPane,gbc);
            //buttons panel
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 0;
            gbc.weighty = 0;
            gbc.gridy = 1;
            JPanel buttonsPanel = new JPanel();
            buttonsPanel.setLayout(new GridBagLayout());
                GridBagConstraints gbcBp = new GridBagConstraints();
                //next/previous buttons
                gbcBp.fill = GridBagConstraints.HORIZONTAL;
                gbcBp.weightx = 1;
                prevButton = new JButton("<<");
                prevButton.setEnabled(false);
                prevButton.addActionListener(this);
                buttonsPanel.add(prevButton,gbcBp);
                nextButton = new JButton(">>");
                nextButton.setEnabled(false);
                nextButton.addActionListener(this);
                gbcBp.gridx = 1;
                buttonsPanel.add(nextButton,gbcBp);
                /*//close button
                gbcBp.fill = GridBagConstraints.NONE;
                closeButton = new JButton("Close");
                closeButton.addActionListener(this);
                gbcBp.gridx = 0;
                gbcBp.gridy = 1;
                gbcBp.gridwidth = 2;
                buttonsPanel.add(closeButton,gbcBp);*/
            add(buttonsPanel,gbc);
            addComponentListener(new ComponentListener(){
                public void componentResized(ComponentEvent e) {
                    /*helpPanel.setPreferredSize(
                            new Dimension(
                                    (int)helpScrollPane.getViewport().getPreferredSize().getWidth(),
                                    (int)helpPanel.getPreferredSize().getHeight())
                    helpPanel.revalidate();
                    helpScrollPane.validate();*/
                    //helpPanel.revalidate();
                    //helpPanel.repaint();
                    updateHelpData();
                public void componentMoved(ComponentEvent e) {}
                public void componentShown(ComponentEvent e) {}
                public void componentHidden(ComponentEvent e) {}
        private void updateGUI() {
            updateHelpData();
            updateNavigationButtons();
        private void updateHelpData() {
            helpPanel.removeAll();
            helpPanel.repaint();
            //helpPanel = new JPanel();
            //insert data again
            Object[] data = helpData[currentHelpDataIndex];
            //helpPanel.setLayout(new BoxLayout(helpPanel,BoxLayout.Y_AXIS));
            helpPanel.setLayout(new GridBagLayout());
            //helpPanel.add(Box.createVerticalBox());
            //helpPanel.add(Box.createHorizontalGlue());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1;
            //gbc.weighty = 1;
            for (int i = 0; i < data.length; i++) {
                Object currentData = data;
    gbc.gridy = i;
    //images - turned into labels
    if (currentData instanceof Image) {
    JLabel label = new JLabel();
    label.setIcon(new ImageIcon((Image)currentData));
    currentData = label;
    if (currentData instanceof JComponent) {
    //components - added as-is
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.CENTER;
    //gbc.weightx = 1;
    JComponent c = (JComponent)currentData;
    c.setAlignmentX(Component.CENTER_ALIGNMENT);
    helpPanel.add(c,gbc);
    } else {
    //everyting else - as text
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    //gbc.weightx = 0;
    JTextArea textArea;
    if (currentData instanceof Document) {
    textArea = new JTextArea((Document)currentData);
    } else {
    textArea = new JTextArea(currentData.toString());
    textArea.setOpaque(false);
    textArea.setFocusable(false);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
    helpPanel.add(textArea,gbc);
    //helpScrollPane.getViewport().setView(helpPanel);
    helpScrollPane.validate();
    helpScrollPane.getVerticalScrollBar().setValue(helpScrollPane.getVerticalScrollBar().getMinimum());
    private void updateNavigationButtons() {
    prevButton.setEnabled(currentHelpDataIndex != 0);
    nextButton.setEnabled(currentHelpDataIndex < helpData.length-1);
    public void actionPerformed(ActionEvent e) {
    JButton source = (JButton)e.getSource();
    /*if (source == closeButton) {
    dispose();
    } else*/ if (source == nextButton) {
    currentHelpDataIndex++;
    updateGUI();
    } else if (source == prevButton) {
    currentHelpDataIndex--;
    updateGUI();
    public static void main(String[] args) {
    HelpWindow window = new HelpWindow(
    new JDialog(),
    new Object[][]
    {"Java Technology\nSun's home for Java. Offers Windows, Solaris, and Linux Java Development Kits (JDKs), extensions, news, tutorials, and product information.\njava.sun.com/ - 26k - 17 Oct 2006 - Cached - Similar pages",
    "The Java� Tutorials\nFrom the download page, you can download the Java Tutorials for browsing ... The Java Tutorials are practical guides for programmers who want to use the ...\njava.sun.com/docs/books/tutorial/index.html - 13k - Cached - Similar pages\n[ More results from java.sun.com ]",
    new JButton("some button"),
    "Sun Microsystems\nSun Java Enterprise System Every time you log on to My Sun Connection (MSC), you're using Sun Java Enterprise System (JES) products. ...\nwww.sun.com/ - 15k - Cached - Similar pages"},
    {"another page...",
    new JCheckBox("something")}
    window.setPreferredSize(new Dimension(300,300));
    window.pack();
    window.setVisible(true);
    System.exit(0);

  • Resizing variable size panel with JScrollPane

    I have a JPanel which contains four radio buttons. Selecting each of them opens another panel which are of different sizes.
    These panels open in the same parent panel below the radio button panel.
    However these panels contain large no of components. i.e. the final size of the main panel varies depeding on which button is selected.
    I am using a JScrollPane to view them properly.
    However, I am facing problem while resizing the main panel. If I mention the preferred size of the JScrollPane, the main panel on maximizing, shows this scrollpane with the size mentioned and does not get maximized as the parent panel.
    If I don't mention the scrollpane size, resizing the main panel don't show the scrollbars.
    what is the correct way to implement a JScrollpane in this case?
    Also can anyone tell me what is the exact deifference between setSize() and setPreferredSize()?

    i think you are looking for this if i got it right.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.ComboBoxModel;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JToggleButton;
    import javax.swing.WindowConstants;
    public class TestVariablePanelSize extends javax.swing.JPanel
        private JPanel buttonPanel;
        private JRadioButton jRadioButton3;
        private JRadioButton jRadioButton4;
        private JLabel jLabel3;
        private JPanel displayPanel2;
        private JLabel jLabel2;
        private JLabel jLabel1;
        private JPanel jPanel1;
        private ButtonGroup buttonGroup1;
        private JScrollPane jScrollPane1;
        private JToggleButton jToggleButton1;
        private JComboBox jComboBox1;
        private JPanel topPanel;
        private JPanel displayPanel;
        private JPanel parentPanel;
        private JRadioButton jRadioButton2;
        private JRadioButton jRadioButton1;
        JFrame container;
        public static void main(String[] args)
            JFrame frame = new JFrame();
            frame.getContentPane().add(new TestVariablePanelSize(frame));
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        public TestVariablePanelSize(JFrame frame)
            super();
            container = frame;
            initGUI();
        private void initGUI()
            try
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                System.out.println("screenSize" + screenSize);
                container.setMaximumSize(screenSize);
                final ErrorReportImportPanel errorReportPanel = new ErrorReportImportPanel();
                BorderLayout thisLayout = new BorderLayout();
                container.setLayout(thisLayout);
                container.setPreferredSize(new java.awt.Dimension(655, 365));
                container.setFocusable(false);
                // START >> jScrollPane1
                // START >>
                buttonGroup1 = new ButtonGroup();
                // END << buttonGroup1
                jScrollPane1 = new JScrollPane();
                container.add(jScrollPane1, BorderLayout.NORTH);
                jScrollPane1.setPreferredSize(new java.awt.Dimension(602, 285));
                // START >> parentPanel
                parentPanel = new JPanel();
                jScrollPane1.setViewportView(parentPanel);
                GridBagLayout parentPanelLayout = new GridBagLayout();
                parentPanelLayout.columnWeights = new double[]{0.1};
                parentPanelLayout.columnWidths = new int[]{7};
                parentPanelLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0};
                parentPanelLayout.rowHeights = new int[]{33, 23, 186, 26};
                parentPanel.setLayout(parentPanelLayout);
                // parentPanel.setPreferredSize(new java.awt.Dimension(652, 371));
                // START >> topPanel
                topPanel = new JPanel();
                parentPanel.add(topPanel, new GridBagConstraints(
                    0,
                    0,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jComboBox1
                ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[]{"Item One", "Item Two"});
                jComboBox1 = new JComboBox();
                topPanel.add(jComboBox1);
                jComboBox1.setModel(jComboBox1Model);
                jComboBox1.setPreferredSize(new java.awt.Dimension(75, 20));
                // END << jComboBox1
                // END << topPanel
                // START >> buttonPanel
                buttonPanel = new JPanel();
                parentPanel.add(buttonPanel, new GridBagConstraints(
                    0,
                    1,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jRadioButton1
                jRadioButton1 = new JRadioButton();
                buttonPanel.add(jRadioButton1);
                jRadioButton1.setText("jRadioButton1");
                jRadioButton1.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel.setVisible(true);
                        // displayPanel2.setVisible(false);
                        // parentPanel.remove(displayPanel2);
                // END << jRadioButton1
                // START >> jRadioButton2
                jRadioButton2 = new JRadioButton();
                buttonPanel.add(jRadioButton2);
                jRadioButton2.setText("jRadioButton2");
                jRadioButton2.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent evt)
                        displayPanel2.setVisible(true);
                        displayPanel.setVisible(false);
                        parentPanel.remove(displayPanel2);
                // END << jRadioButton2
                // START >> jRadioButton3
                jRadioButton3 = new JRadioButton();
                buttonPanel.add(jRadioButton3);
                jRadioButton3.setText("jRadioButton3");
                // END << jRadioButton3
                // START >> jRadioButton4
                jRadioButton4 = new JRadioButton();
                buttonPanel.add(jRadioButton4);
                jRadioButton4.setText("jRadioButton4");
                // END << jRadioButton4
                // END << buttonPanel
                buttonGroup1.add(jRadioButton1);
                buttonGroup1.add(jRadioButton2);
                buttonGroup1.add(jRadioButton3);
                buttonGroup1.add(jRadioButton4);
                // START >> displayPanel
                displayPanel = new JPanel();
                parentPanel.add(displayPanel, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.NORTH,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel.setVisible(false);
                // START >> jLabel2
                jLabel2 = new JLabel();
                displayPanel.add(jLabel2);
                jLabel2.setText("displayPanel");
                jLabel2.setPreferredSize(new java.awt.Dimension(462, 152));
                jLabel2.setOpaque(true);
                jLabel2.setBackground(new java.awt.Color(128, 128, 255));
                jLabel2.setVisible(false);
                // END << jLabel2
                // END << displayPanel
                // START >> displayPanel2
                displayPanel2 = new JPanel();
                parentPanel.add(displayPanel2, new GridBagConstraints(
                    0,
                    2,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.BOTH,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                displayPanel2.setVisible(false);
                // START >> jLabel3
                jLabel3 = new JLabel();
                displayPanel2.add(jLabel3);
                jLabel3.setText("displayPanel2");
                jLabel3.setOpaque(true);
                jLabel3.setBackground(new java.awt.Color(0, 128, 192));
                jLabel3.setPreferredSize(new java.awt.Dimension(460, 171));
                // END << jLabel3
                // END << displayPanel2
                // START >> jToggleButton1
                jToggleButton1 = new JToggleButton();
                parentPanel.add(jToggleButton1, new GridBagConstraints(
                    0,
                    3,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.WEST,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                jToggleButton1.setText("jToggleButton1");
                // END << jToggleButton1
                // START >> jPanel1
                jPanel1 = new JPanel();
                parentPanel.add(jPanel1, new GridBagConstraints(
                    0,
                    4,
                    1,
                    1,
                    0.0,
                    0.0,
                    GridBagConstraints.CENTER,
                    GridBagConstraints.NONE,
                    new Insets(0, 0, 0, 0),
                    0,
                    0));
                // START >> jLabel1
                jLabel1 = new JLabel();
                jPanel1.add(jLabel1);
                jLabel1.setText("Another Panel");
                jLabel1.setPreferredSize(new java.awt.Dimension(469, 87));
                jLabel1.setBackground(new java.awt.Color(0, 128, 0));
                jLabel1.setForeground(new java.awt.Color(0, 0, 0));
                jLabel1.setOpaque(true);
                // END << jLabel1
                // END << jPanel1
                // END << parentPanel
                // END << jScrollPane1
            catch (Exception e)
                e.printStackTrace();
    }

  • JTable disturbs gridbaglayout with jtextfields

    Hello, my problem is a JTable, that shrinks my two JTextFields to zero length. I tried to create the gui without the JTable and it works as expected. There should be two JTextFields with fixed length in a row below the JTable in a JTabbedPane. Code:
        jT1 = new JTable( 10,10);
        jSP1 = new JScrollPane( jT1);// without jT1 everything is fine
        jP1 = new JPanel( new BorderLayout());
        jP1.add( jSP1, BorderLayout.CENTER);
        jTP = new JTabbedPane();
        jTP.add( "Tab1", jP1);
        jL1 = new JLabel( "Txt1:");
        jTF1 = new JTextField( "0.00",10);
        jL2 = new JLabel( "Txt2:");
        jTF2 = new JTextField( "0.00",10);
        jP0 = new JPanel(new GridBagLayout());
        jP0.add(jTP, new GridBagConstraints(0, 0, 4, 1, 1.0, 1.0
            ,GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
        jP0.add(jL1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 0), 0, 0));
        jP0.add(jTF1, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 10, 0, 0), 0, 0));
        jP0.add(jL2, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 20, 0, 0), 0, 0));
        jP0.add(jTF2, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 10, 0, 0), 0, 0));Setting weightx to 0.5 and GriBagConstraints.HORIZONTAL for the JTextFields makes them variable size, but that' not what I want.

    What about setting iPadx parameter in GridBagConstraints?
    regards,
    Stas

  • Design problem with JScrollPane

    First, I have problems with english. I hope u understand without problems that Im trying to say here. Sorry about that.
    Mi problem is whit a JScrollPane. I want to put an image whit a predefined size for draw inside it. I dont have any information about it, just the size. I want to put it in a JPane. The best choice is use the JPane area. The problem is that I want to use a JScrollPane because the image is bigger that the visualization area.
    Im unable to put a Canvas in the ScrollPane, or a JPane whit a predefined size or an image whit a predefined size. Im sure that is a design problem. Somebody can tell me something I can start whit? What do u think is better choice to put inside a JScrollPane?
    I dont send any source code because I dont have anything else that is show in the example.
    Gracias.

    import java.awt.*;
    import javax.swing.*;
    import java.net.URL;
    public class Test extends JFrame {
      String url = "http://www.sandbox-usa.com/images/product_images/2piece_16.gif";
      public Test() {
    //    System.getProperties().put( "proxySet", "true" );  // uncomment if you have proxy
    //    System.getProperties().put( "proxyHost", "myproxy.mydomain.com" ); // Your proxyname/IP
    //    System.getProperties().put( "proxyPort", "80"); // Sometimes 8080   
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        Container content = getContentPane();
        try {
          Image i = Toolkit.getDefaultToolkit().getImage(new URL(url));
          JLabel jl = new JLabel(new ImageIcon(i));
          content.add(new JScrollPane(jl), BorderLayout.CENTER);
          setSize(200, 200);   
          setVisible(true); 
        } catch (Exception e) { e.printStackTrace(); }
      public static void main(String[] args) { new Test(); }
    }

  • Problem with JScrollPane and Mouse Event in JDK 1.4

    The folowing code works fine with JDK 1.3. But not with JDK 1.4. It has got a JPanel(main panel) which hosts JScrollPane which hosts another JPanel (drawing Panel). If I remove(do not add) JScrollPane to the main Panel and ad drawing panel directly to the main panel, it works.
    Thanks.
    In order to replicate the exact scenario, I have modified Sun's tutorial ScrollDemo2.java
    * This code is based on an example provided by John Vella,
    * a tutorial reader.
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class ScrollDemo2 extends JPanel {
    private Dimension size; // indicates size taken up by graphics
    private Vector objects; // rectangular coordinates used to draw graphics
    private final Color colors[] = {
    Color.red, Color.blue, Color.green, Color.orange,
    Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
    private final int color_n = colors.length;
    JPanel drawingArea;
    public ScrollDemo2() {
    setOpaque(true);
    size = new Dimension(0,0);
    objects = new Vector();
    //Set up the instructions.
    JLabel instructionsLeft = new JLabel(
    "Click left mouse button to place a circle.");
    JLabel instructionsRight = new JLabel(
    "Click right mouse button to clear drawing area.");
    JPanel instructionPanel = new JPanel(new GridLayout(0,1));
    instructionPanel.add(instructionsLeft);
    instructionPanel.add(instructionsRight);
    class MyScrollPane extends JScrollPane
    MyScrollPane(JPanel drawingArea)
    super(drawingArea);
    public void grabFocus()
    super.grabFocus();
    public void requestFocus()
    super.requestFocus();
    protected void processFocusEvent(FocusEvent e)
    if ( e.getID() == FocusEvent.FOCUS_GAINED )
    int i = 0;
    else
    if( e.getID() == FocusEvent.FOCUS_LOST )
    int i = 0;
    super.processFocusEvent(e);
    //Set up the drawing area.
    drawingArea = new JPanel() {
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Rectangle rect;
    for (int i = 0; i < objects.size(); i++) {
    rect = (Rectangle)objects.elementAt(i);
    g.setColor(colors[(i % color_n)]);
    g.fillOval(rect.x, rect.y, rect.width, rect.height);
    g.drawString("Hello",100,100);
    protected void processMouseEvent(MouseEvent pEvent)
    if(pEvent.getID() == pEvent.MOUSE_PRESSED)
    super.processMouseEvent(pEvent);
    else
    super.processMouseEvent(pEvent);
    drawingArea.setBackground(Color.LIGHT_GRAY);
    addMouseListener(new MyMouseListener());
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new MyScrollPane(drawingArea);
    scroller.setPreferredSize(new Dimension(200,200));
    setLayout(new BorderLayout());
    add(scroller, BorderLayout.CENTER);
    //If the above line is commented and the line bellow will be uncommented it works.
    //add(drawingArea, BorderLayout.CENTER);
    protected void processMouseEvent(MouseEvent pEvent)
    if(pEvent.getID() == pEvent.MOUSE_PRESSED)
    super.processMouseEvent(pEvent);
    else
    super.processMouseEvent(pEvent);
    class MyMouseListener extends MouseInputAdapter {
    final int W = 100;
    final int H = 100;
    public void mouseReleased(MouseEvent e) {
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    // This will clear the graphic objects.
    objects.removeAllElements();
    size.width=0;
    size.height=0;
    changed = true;
    } else {
    int x = e.getX() - W/2;
    int y = e.getY() - H/2;
    if (x < 0) x = 0;
    if (y < 0) y = 0;
    Rectangle rect = new Rectangle(x, y, W, H);
    objects.addElement(rect);
    drawingArea.scrollRectToVisible(rect);
    int this_width = (x + W + 2);
    if (this_width > size.width)
    {size.width = this_width; changed=true;}
    int this_height = (y + H + 2);
    if (this_height > size.height)
    {size.height = this_height; changed=true;}
    if (changed) {
    //Update client's preferred size because
    //the area taken up by the graphics has
    //gotten larger or smaller (if cleared).
    drawingArea.setPreferredSize(size);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingArea.revalidate();
    drawingArea.repaint();
    public static void main (String args[]) {
    JFrame frame = new JFrame("ScrollDemo2");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.setContentPane(new ScrollDemo2());
    frame.pack();
    frame.setVisible(true);

    I tried it . It didn't work.
    Thanks for the suggestionI've got it... I know that inside the paitComponet method you can't call setSize() in jdk1.4, but you could in previous versions... that has caused al lot of problems to me...
    Abraham

  • How can I get the selected row's index of a Jlist wrapped with JScrollpane?

    the problem is that I can use getSelectedIndex() only if the JList is not wrapped in a JScrollPane.
    but in my program the JList IS wrapped in a JScrollPane.
    when I select one item of the jscrollpane I can't catch the event.
    please F1 me.
    Lior.

    What difference does it make if the list is inside a scroll pane or not? If you have a member varialbe that references the list you can call getSelectedIndex when ever you need.
        myList = new JList (...)
        someComponent.add (new JScrollPane (myList));
        //  Then later
        int sel = myList.getSelectedIndex ();And you can always be up on any selection chagnes in the list by supplying it with a ListSelecitonListener.

  • Zoom Issues with JScrollPane

    Hello all,
    I have ran into an issue with zoom functionality on a JScrollPane.
    Here is the situation (code to follow):
    I have a JFrame with a JDesktopPane as the contentpane. Then I have a JScrollPane with a JPanel inside. On this JPanel are three rectangles. When they are clicked on, they will open up a JInternalFrame with their name (rect1, rect2, or rect3) as the title bar. Rect3 is positioned (2000,2000).
    I have attached a mousewheel listener to the JPanel so I can zoom in and out.
    I have also attached a mouse listener so I can detect the mouse clicks for the rectangles. I also do a transformation on the point so I can be use it during clicks while the panel is zoomed.
    All of this works fantastic. The only issue I am having is that when the JScrollPane scroll bars change, I cannot select any of the rectangles.
    I will give a step by step reproduction to be used with the code:
    1.) Upon loading you will see two rectangles. Click the far right one. You'll see a window appear. Good. Move it to the far right side.
    2.) Zoom in with your mouse wheel (push it towards you) until you cannot zoom anymore (May have to get focus back on the panel). You should see three rectangles. Click on the newly shown rectangle. Another window, titled rect3 should appear. Close both windows.
    3.) This is where things get alittle tricky. Sometimes it works as intended, other times it doesn't. But do something to this affect: Scroll to the right so that only the third rectangle is showing. Try to click on it. If a window does not appear - that is the problem. But if a window does appear, close it out and try to click on the 3rd rect again. Most times, it will not display another window for me. I have to zoom out one step and back in. Then the window will appear.
    After playing around with it for awhile, I first thought it may be a focus issue...I've put some code in the internal window listeners so the JPanel/JScrollPane can grab the focus upon window closing, but it still does not work. So, either the AffineTransform and/or point conversion could be the problem with the scroll bars? It only happens when the scroll bar has been moved. What affect would this have on the AffineTransform and/or point conversion?
    Any help would be great.
    Here is the code, it consists of two files:
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    public class InternalFrameAffineTransformIssue
         public static void main ( String[] args )
              JFrame frame = new JFrame("AffineTransform Scroll Issue");
              frame.setLayout(null);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JDesktopPane desktop = new JDesktopPane();
              frame.setContentPane(desktop);
              MyJPanel panel = new MyJPanel(frame);
              JScrollPane myScrollPane = new JScrollPane(panel);
              panel.setScrollPane(myScrollPane);
              myScrollPane.setLocation(0, 0);
              myScrollPane.setSize(new Dimension(800, 800));
              myScrollPane.getVerticalScrollBar().setUnitIncrement(50);
              myScrollPane.getHorizontalScrollBar().setUnitIncrement(50);
              myScrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.black));
              frame.getContentPane().add(myScrollPane);
              frame.setBounds(0, 100, 900, 900);
              frame.setVisible(true);
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.NoninvertibleTransformException;
    import java.awt.geom.Point2D;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.event.InternalFrameAdapter;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    public class MyJPanel extends JPanel implements MouseWheelListener
              double zoom = 1;
              Rectangle rect1 = new Rectangle(50, 50, 20, 20);
              Rectangle rect2 = new Rectangle(100, 50, 20, 20);
              Rectangle rect3 = new Rectangle(2000, 2000, 20, 20);
              AffineTransform zoomedAffineTransform;
              JFrame frame;
              JPanel myPanel = this;
              JScrollPane myScrollPane;
              public MyJPanel(JFrame inputFrame)
                   setAutoscrolls(true);
                   addMouseListener(new MouseAdapter(){
                        public void mousePressed ( MouseEvent e )
                             System.out.println("Clicked: " + e.getPoint());
                             AffineTransform affineTransform = zoomedAffineTransform;
                             Point2D transformedPoint = e.getPoint();
                             //Do the transform if it is not null
                             if(affineTransform != null)
                                  try
                                       transformedPoint = affineTransform.inverseTransform(transformedPoint, null);
                                  catch (NoninvertibleTransformException ex)
                                       ex.printStackTrace();
                             System.out.println("Tranformed Point: " + transformedPoint);
                             if(rect1.contains(transformedPoint))
                                  System.out.println("You clicked on rect1.");
                                  createInternalFrame("Rect1");
                             if(rect2.contains(transformedPoint))
                                  System.out.println("You clicked on rect2.");
                                  createInternalFrame("Rect2");
                             if(rect3.contains(transformedPoint))
                                  System.out.println("You clicked on rect3.");
                                  createInternalFrame("Rect3");
                   addMouseWheelListener(this);
                   frame = inputFrame;
                   setPreferredSize(new Dimension(4000, 4000));
                   setLocation(0, 0);
              public void paintComponent ( Graphics g )
                   super.paintComponent(g);
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.scale(zoom, zoom);
                   zoomedAffineTransform = g2d.getTransform();
                   g2d.draw(rect1);
                   g2d.draw(rect2);
                   g2d.draw(rect3);
              public void mouseWheelMoved ( MouseWheelEvent e )
                   System.out.println("Mouse wheel is moving.");
                   if(e.getWheelRotation() == 1)
                        zoom -= 0.05;
                        if(zoom <= 0.20)
                             zoom = 0.20;
                   else if(e.getWheelRotation() == -1)
                        zoom += 0.05;
                        if(zoom >= 1)
                             zoom = 1;
                   repaint();
              public void createInternalFrame ( String name )
                   JInternalFrame internalFrame = new JInternalFrame(name, true, true, true, true);
                   internalFrame.setBounds(10, 10, 300, 300);
                   internalFrame.setVisible(true);
                   internalFrame.addInternalFrameListener(new InternalFrameAdapter(){
                        public void internalFrameClosed ( InternalFrameEvent arg0 )
                             //myPanel.grabFocus();
                             myScrollPane.grabFocus();
                        public void internalFrameClosing ( InternalFrameEvent arg0 )
                             //myPanel.grabFocus();
                             myScrollPane.grabFocus();
                   frame.getContentPane().add(internalFrame, 0);
              public void setScrollPane ( JScrollPane myScrollPane )
                   this.myScrollPane = myScrollPane;
         }

    What I'm noticing is your zoomedAffineTransform is changing when you click to close the internal frame. This ends up being passed down the line, thus mucking up your clicks until you do something to reset it (like zoom in and out).
    Clicking on the JInternalFrame appears to add a translate to the g2d transform. This translation is what's throwing everything off. So in the paintComponent where you set the zoomedAffineTransform, you can verify if the transform has a translation before storing the reference:
             if (g2d.getTransform().getTranslateX() == 0.0) {
                zoomedAffineTransform = g2d.getTransform();
             }Edited by: jboeing on Oct 2, 2009 8:23 AM

  • Help With JScrollPane and many JLabels...

    I am in the process of designing an 'image browser' applet for a client, but am having some difficulty in deciding how I can most elegantly meet all of the requirements. The specification calls for an applet that can view up to 400 images (all images are small - 120 * 120 px), the view of the images can be scrolled (if not all are in the view) or scaled (zoom in and out on any area), and the images will need to 'animate' or move to new locations as sorting criteria changes. Also, I need to be able to group images into arbitrary n*n arrays and click on any image in the view (rollovers may also be necessary in the future).
    At first, I thought this would be easily solved by putting the images (JLabels?) into as many groups (JPanels?) as necessary to meet the sort criteria, then adding the groups to my main view (JScrollPane w/JPanel) in a GridLayout. My current attempt at a solution scales the groups (JPanels) via. an overridden paintComponent method from within my main scrolling view (using g2d and scale). Unfortunately, I now have many problems that I am having trouble solving:
    1. After I re-scale the JScrollPane (zoom in or out) and then try and scroll, the new images that scroll in are either garbled or just junk (seems like remnants of the original, non-scaled components?).
    2. The scrollbars, at first, were not reflecting the current scaling and how much content is visible, so I overrode the getPreferredSize method in my JScrollPane content object to return (super.getPreferredSize * scaleFactor) - this fixes the appearance of the scroll bars (ie. they accurately reflect how much content there is), but it also offsets all of the images left depending on the scale value (less scale -> images offset further left).
    3. I need pixel-perfect control over the images, so that I can animate the transition from one 'group' to another - I can't see a way to achieve this with my current solution.
    Has anyone tried to do something like this before? What is a good way of accomplishing what I need here? Any code out there that does something similar? Any help would be appreciated, I've been banging my head against the wall over this for days now...
    Thanks in advance,
    Mike P.
    Here is some relevant code:
    /* From BrowserPanel (JPanel associated with my main JScrollPane) */
    public void paint (Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.scale(scaleFactor, scaleFactor);
        super.paint(g2d);
    /* From BrowserPanel (JPanel associated with my main JScrollPane) */
    public Dimension getPreferredSize() {
        Dimension origSize = super.getPreferredSize();
        double originalSizeX;
        double originalSizeY;
        originalSizeX = origSize.getWidth();
        originalSizeY = origSize.getHeight();
        double newSizeX = originalSizeX * scaleFactor;
        double newSizeY = originalSizeY * scaleFactor;
        String strX = Double.toString(newSizeX);
        String strY = Double.toString(newSizeY);
        /* Round the string (discard anything after the decimal) */
        strX = strX.substring(0, strX.indexOf("."));
        strY = strY.substring(0, strY.indexOf("."));
        /* Convert string to int... */     
        int x = Integer.parseInt(strX);
        int y = Integer.parseInt(strY);
        return new Dimension(x, y);
    }

    I increased the frame size to 3 lines and noticed the the flickering is a result of the text area painting itself without the scrollbar and then repainting itself with the scrollbar. I don't know why this happens, but a work around is to use:
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,

  • HELP, HELP, HELP, Problems using GridBagLayout with a BorderLayout

    I have a BorderLayout for my application. I created a JPanel that has the following items added to it:
    1)Button
    2)VisualComponent
    3)ControllerComponent
    The JPanel is then added to the WEST Pane of the BorderLayout. My problem is that I can not get my components in the JPanel to display correctly. The items should be added from top to buttom in my JPanel, but they overlap and display side by side, and some don't appear at all until my entire window application is Maximized. It seems as if all my components are trying to display in one row even though I explicitly add them to different rows as follows:
    1)addUsingGBL(openFile,0,1,2,1);
    2)addUsingGBL(visualComponent,1,1,1,3);
    3)addUsingGBL(controlsComponent,4,1,2,1);
    where addUsingGBL is as follows:
    void addUsingGBL(Component component,int row, int column, int width, int height)
    gbc. gridx = row;
         gbc.gridy = column;
         gbc.gridwidth = width;
         gbc.gridheight = height;
         gbLayout.setConstraints(component, gbc);
         mediaPanel.add(component);
         mediaPanel.doLayout();
    If anyone has any suggestions, I would greatly appreciate it. Entire code is available if needed. Thanks!

    Here is the code, sorry, didn't see that part before.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.media.*;
    public class MediaPlayerDemo extends JFrame /*implements ControllerListener*/{
    private Player player;
    private File file;
    public static JPanel mediaPanel;
    public static JScrollPane scrollableMediaPanel;
    //public static JFrame navigation = new JFrame("Lessons");
    public static Component visualComponent;
    public static Component controlsComponent;
    private static ImageIcon background = new ImageIcon("c:/Tony.jpg");
    public static GridBagConstraints gbc;
    public static GridBagLayout gbLayout;
    //public static panel column;
    //public static Container c;
    // inner class to handler events from media player
    private class EventHandler implements ControllerListener
         public void controllerUpdate( ControllerEvent e )
              if ( e instanceof EndOfMediaEvent)
              //if ( player == null )
              //return;
              player.close();
              //if ( visualComponent != null )
              mediaPanel.remove( visualComponent );
              //if ( controlsComponent != null )
              mediaPanel.remove( controlsComponent );
              mediaPanel.doLayout();
              // doLayout();
              if ( e instanceof RealizeCompleteEvent )
                   //c = getContentPane();
                   // load Visual and Control components if they exist
                   visualComponent =
                   player.getVisualComponent();
                   //visualComponent.setSize(5,5);
                   mediaPanel.doLayout();
                   //**Sets the layout for mediaPanel as GridLayout**
                   //**GridLayouts set the rows and col, **
                   //**& adds contentslt to rt **
                   //scrollableMediaPanel= new JScrollPane(mediaPanel);
                   //scrollableMediaPanel= new JScrollPane(mediaPanel);
                   gbc.weightx = 0;
                   gbc.weighty = 0;
                   gbc.fill = GridBagConstraints.NONE;
                   if ( visualComponent != null )
                   //add comp #2
                   addUsingGBL(visualComponent,1,1,1,3);
                   controlsComponent =
                   player.getControlPanelComponent();
                   if ( controlsComponent != null )
                   //add comp #3
                   //mediaPanel.add(controlsComponent);
                   addUsingGBL(controlsComponent,1,1,1,3);
                   controlsComponent =
                   player.getControlPanelComponent();
                   /*if ( controlsComponent != null )
                   //add comp #3
                   addUsingGBL(controlsComponent,4,1,2,1);
              doLayout();//after all components are added, you must redo your layout
              //**The following is for adding the a container only **
              //**getContentPane().add(mediaPanel,BorderLayout.WEST);**
              //**getContenPane().doLayout(); **
              //**setSize(200,700);//(width, Height) **
              //**show(); **
              }//if
         }//controllerUpdate
    }//eventHandler
    public MediaPlayerDemo()
         //**Title for a container **
         //**super( "Demonstrating the Java Media Player" );**
         mediaPanel = new panelBack(background);//instantiate JPanel Object
         gbLayout = new GridBagLayout();
         mediaPanel.setAlignmentY(TOP_ALIGNMENT);
         mediaPanel.setLayout(gbLayout);
                   gbc = new GridBagConstraints();
                   gbc.fill = GridBagConstraints.NONE;
                   //gbc.anchor = GridBagConstraints.NONE;
         //instatiate JButton object
         JButton openFile = new JButton( "Open file to play" );
         //openFile.setBounds(0, 0, 25, 25);
         //openFile.setVisible(true);
         //JBUTTON ActionListener
         openFile.addActionListener
              new ActionListener()
                   public void actionPerformed( ActionEvent e )
                   openFile();
                   createPlayer();
         );//addActionListener
         //add comp #1
         addUsingGBL(openFile,0,1,2,1);
         //set scrollPane
         scrollableMediaPanel = new JScrollPane(mediaPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                   JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         //Set Border
         scrollableMediaPanel.setViewportBorder(new BevelBorder(BevelBorder.RAISED));
    }//Constructor
    private void createPlayer()
         if ( file == null )
              return;
         removePreviousPlayer();
         try
              // create a new player and add listener
              player = Manager.createPlayer( file.toURL() );
              player.addControllerListener( new EventHandler() );
              player.start(); // start player
         catch ( Exception e )
              JOptionPane.showMessageDialog( this,
                   "Invalid file or location", "Error loading file",
                   JOptionPane.ERROR_MESSAGE );
    //Main only useful if creating a container to hold menuPanel
    public static void main(String args[])
         MediaPlayerDemo app = new MediaPlayerDemo();
         app.getContentPane().setLayout(new BorderLayout(0,0));
              app.getContentPane().setBackground(Color.white);
              app.getContentPane().add(scrollableMediaPanel, BorderLayout.WEST);
         app.getContentPane().validate();//re-layout a container for which the layout has changed
         app.setSize(1000,700);//(width, height)
         app.show();
         app.addWindowListener
              new WindowAdapter()
                   public void windowClosing( WindowEvent e )
                   System.exit(0);
    private void openFile()
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(
              JFileChooser.FILES_ONLY );
         int result = fileChooser.showOpenDialog( this );
         // user clicked Cancel button on dialog
         if ( result == JFileChooser.CANCEL_OPTION )
              file = null;
         else
              file = fileChooser.getSelectedFile();
    private void removePreviousPlayer()
         if ( player == null )
              return;
         player.close();
         if ( visualComponent != null )
              mediaPanel.remove( visualComponent );
         if ( controlsComponent != null )
              mediaPanel.remove( controlsComponent );
         //set background for the JPanel
         public class panelBack extends JPanel
              ImageIcon image;
              panelBack(ImageIcon image)
                   super();
                   this.image=image;
              public void paintComponent(Graphics g)
                   image.paintIcon(this,g,0, 0);
         }//panelback
    void addUsingGBL(Component component,int row, int column, int width, int height)
    gbc = new GridBagConstraints();
         gbc. gridx = row;
         gbc.gridy = column;
         gbc.gridwidth = width;
         gbc.gridheight = height;
         gbLayout.setConstraints(component, gbc);
         mediaPanel.add(component);
         mediaPanel.doLayout();
    }//MediaPlayerDemo

  • Is it a bug? GridBagLayout  with textField

    Hi,
    The following method does not work fine.
    The textfield field gets all the space
    but if i change
    JTextField field = new JTextField();
    with
    JPanel field = new JPanel();
    it will work fine.
    I think there is a problem with GridBagLayout
    and textField. is it a bug in jdk1.2
    public JPanel getCPane() {
    int XUNIT = 5;
    int YUNIT = 100;
    JPanel pane = new JPanel();
    JPanel pane1 = new JPanel();
    JTextField field = new JTextField();
    pane1.setBackground(Color.red);
    pane1.setPreferredSize(new Dimension(2*XUNIT, YUNIT));
    field.setPreferredSize(new Dimension(6*XUNIT, YUNIT));
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(0,0,0,0);
    c.weightx = c.weighty = 0;
    c.gridx = 0; c.gridy = 0;
    c.gridwidth = 2*XUNIT; c.gridheight = YUNIT;
    pane.add(pane1, c);
    c.weightx = c.weighty = 1;
    c.gridx = 2; c.gridy = 0;
    c.gridwidth = 6*XUNIT; c.gridheight = YUNIT;
    pane.add(field, c);
    return pane;

    Any solution please

Maybe you are looking for

  • How to move from one transaction iView to another without losing the info.

    Hello expert, Is there a way to configure multiple transaction iViews in away that when I click on another iViews and want to go back to the old one, then the information is still there?  For example, we have a customize transaction that is fetched b

  • Grey bar at startup - Mac HD is greyed out in Disk Utility - Can't be repaired? Need to salvage my data!

    Mac Book Pro - My MacBook Pro (2008 Model) has been unable to start up - upon the start up screen when the grey Apple logo appears, I get a loading bar below it. After about 15-20 minutes when the bar is almost complete the machine shuts off. There s

  • Problems with Album Art flow

    I have Windows Vista, and it's on an excellent machine, (for example) I can run Oblivion on the highest graphical specs with no lag. However, my iTunes cover art, or my album art is slow, even when there is no album art. I tried reinstalling itunes a

  • Sync Settings Bug w/ Lens Corrections

    I'm having an issue with "Sync Settings" and Copy/Paste. Even though I have it *unchecked,* Lens Corrections are being applied. Obviously I only notice it when I try to sync some develop settings, for example, from an image shot with a 135mm to one s

  • Automatic Move-In Meter Read Population

    Hi Can you please let me know the relevant configurations to be done for automatically populating Move In Meter Read from historical read. I have already done configurations at "Define Control Parameters for Meter Reading Data Processing" but still M