Size of a jScrollPane

Hi
I have a JEditorPane with a html page in it. The problem is that I don't want a horizontal scrollBar and my resolution is 800x600. Is there any possibility to adjust this when the page to be displayed has for example a table with a width of 1000 pxls ?
jerome

This is a Java forum, not a forum on how to use IDE's.
Later I want to resize the jPanel1 through my IDE. Also, we are not mind readers. We have no idea what IDE you are using so how to you expect us to help?
My suggetion is to use the IDE for compiling, debugging and testing, but learn how to write your GUI code yourself so you can manage it yourself.

Similar Messages

  • 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();
    }

  • How to change the size of a JScrollPane

    hi there,
    a JScrollPane always has the same size... how can i change this?
    because i want to add a JTable that is much larger( x-size )than the JScrollPane and I want that the whole row can be seen without the need of scrolling.
    I cannot make the cells any smaller (because of the content) so is there anyway to make the JScrollPane bigger?
    thx anyway
    Errraddicator

    What is the container of the JScrollPane, what is the
    layout used there ?.bingo, thats exactly my answer too.. Dont use a layout if you need the screen to be set up a certain way, just use setBounds on all the components in you container.. ya, you have to specify a bunch of x/y coordinates and component sizes, but you wouldn't be having this problem if you didn't have a layout..
    If/after your layout really IS null, then use scrollpane.setBounds(x,y,l,w) to set position and size..
    doug

  • Illustrating a stack of an unknown size in a JScrollPane

    I designed a maze generation/traversal program and I want to show what happens to the stack in the depth first algorithms that I used. I have a JFrame with a JPanel containing the maze and to the right of the JPanel is a JScrollPane to hold the stack illustration. I have a JPanel inside the JScrollPane and I was wondering how I can start from the bottom of the JPanel in the viewing area of the JScrollPane and continually add JLabels, representing blocks in a stock, to the JPanel, working my way from the bottom up. When a JLabel is added and goes above the top of the current viewspace of the JScrollPane, I'd like for the JScrollPane to scroll up. Also, which layout should I set the JPanel in the JScrollPane to? GridBagLayout?

    Nvm, I used a JList in a JScrollPane. I just have to alter the DefaultListModel so that the top of the list is the end of the vector and not the front.

  • Calculate the rectangle size displayed in JScrollPane

    Hi,
    I am pasting a code below, What i want to get is the the rectangle of panel which will be displayed, so i can use g.setClip method to only paint that much portion of the JPanel
    Please copy the code compile it and run it, so u will come to know my problem..
    I want to dynamically setClip so the display is proper when the user scrolls.
    Ashish
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestDisplaySize extends JFrame
         JScrollPane scrollPane ;
         public TestDisplaySize()
              super("layered pane");
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              MyPanel panel = new MyPanel();
              scrollPane = new JScrollPane(panel);
              Container contentPane = this.getContentPane();
              contentPane.add(scrollPane, BorderLayout.CENTER);
              setSize(new Dimension(800,600));
              this.setVisible(true);
         class MyPanel extends JPanel
              public MyPanel()
         setPreferredSize(new Dimension(2000,600) );     
         this.setBackground(Color.white);
         this.setOpaque(true);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.setClip(0,0, 750,550);
    g.setColor(Color.blue);
    int x = 0;
    for(int i = 0; i < 60; i++)
         x +=60;
         g.drawLine(x, 0, x, 600);
         public static void main(String args[])
         new TestDisplaySize();
    }

    ash,
    Use this:
    super.paintComponent(g);
    Rectangle r = scrollPane.getViewport().getViewRect();
    g.setClip((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
    g.setColor(Color.blue);--A
    PS: in future please see the "special tokens" link in the posting page for special tags that will make posted code format better.

  • Must reduce size of JScrollPane to see Scrollbar

    when I put a JScrollPane in a JPanel
    I must reduce the size of the JScrollPane to see the JScrollBar
    any Help is welcomed
    Thank U

    setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );

  • JScrollPane: lock views size in one direction

    Hi,
    I have a JScrollPane that should use only the vertical scrollbar and a fixed size in horizontal direction. That means when an element inside the scroll panes view is broader as allowed it has to be shrinked down according to the behaviour of its LayoutManager.
    I tried to set the preferred size for the JScrollPane itself and its view port but nothing helped. So how can I lock a JScrollPane in one direction so that it shows its standard behaviour only for the other direction?
    Oxy
    Edited by: Oxy on Oct 23, 2008 2:01 AM

    This response is probably way too late to solve your problem but I was looking for an answer to the same question and found this post, so I figure if I answer it here, the next person won't need to search further.
    Basically you use Scrollable to do this.
    Assuming you're working with a custom panel:
    public class MyCustomPanel implements Scrollable {
        public boolean getScrollableTracksViewportWidth() {
            return true;
    }If you're not using a custom panel then often it will already implement this method, but you can still override it to force the desired behaviour.
    FWIW this can also be used in the direction you do want it to scroll, if you have a background you need to fill the entire scrollable area:
    public class MyCustomPanel implements Scrollable {
        public boolean getScrollableTracksViewportHeight() {
            return getParent() instanceof JViewport && getParent().getHeight() > getPreferredSize().height;
    }i.e. if the viewport is bigger than what you need to paint, the viewport will stretch your component to fill the rest of the space.

  • JScrollPane with scrollbar as needed packs to the wrong size.

    Hi!
    I just noticed a strange problem when packing a JScrollPane with scrollbar policy "as needed" and wondered if it's me or if it is a real bug in Swing.
    I create a JFrame with a JScrollPane in it and a JPanel as viewportview. The JPanel (called "stuffPanel") contains a few components which give it a preferred size, and the JScrollPane is set to grow as needed if the window grows. A button in the center of the stuffPanel will invoke pack() on the window when clicked.
    Now, if I resize the window such that the JScrollPane can't display the entire stuffPanel, I get scrollbars as expected. If I click the pack button the window correctly resizes to the preferred size (without scrollbars).
    On the other hand, if I resize the window to become larger than the preferred size and then click the pack button, the window (and the stuffPanel) is resized to include 17 pixels of extra size around the edges.
    Put simply, pack() will resize the JPanel to different sizes depending on whether the scrollbars of the JScrollPane were visible at the time. Note that this only occurs when you're using the "scrollbars as needed" scrollbar policy.
    An even more interesting situation occurs if you resize the window to include (for example) only horizontal scrollbars and then packs the window repeatedly...
    Code for a Java app which displays the strange behaviour is included below:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestJScrollPane {
      static {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e) { }
      private JFrame mainWindow;
      public TestJScrollPane() {
        mainWindow = createMainWindow();
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.pack();
        mainWindow.show();
      public JFrame createMainWindow() {
        JFrame window = new JFrame("Test of scrollpane");
        window.getContentPane().setLayout(new GridBagLayout());
        final JPanel stuffPanel = new JPanel();
        stuffPanel.setBorder(BorderFactory.createTitledBorder("Collection of stuff"));
        stuffPanel.setLayout(new GridBagLayout());
        JLabel stuffLabel = new JLabel("A label");
        JTextField stuffField = new JTextField(10);
        JButton stuffButton = new JButton("Pack the window");
        JList listOfStuff = new JList();
        listOfStuff.setListData(new String[] {"Fish", "Bird", "Mammal", "Insect", "Spider"});
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        stuffPanel.add(stuffLabel, gbc);
        gbc.gridx = 1;
        stuffPanel.add(stuffField, gbc);
        gbc.gridy = 1;
        gbc.gridx = 0;
        gbc.gridwidth = 2;
        stuffPanel.add(stuffButton, gbc);
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        stuffPanel.add(listOfStuff, gbc);
        final JScrollPane scroller = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroller.setViewportView(stuffPanel);
        gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1;
        gbc.weighty = 1;
        window.getContentPane().add(scroller, gbc);
        stuffButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            mainWindow.pack();
            System.out.println("Stuff panel size: " + stuffPanel.getSize());
            System.out.println("Stuff panel preferred size:" + stuffPanel.getPreferredSize());
            System.out.println("Scroller size: " + scroller.getSize());
            System.out.println("Scroller preferred size: " + scroller.getPreferredSize());
        return window;
      public static void main(String[] args) {
        new TestJScrollPane();
    }

    Why would the JScrollPane be as big as the entire
    frame when you added 800x600 panels on all sides of
    it? It's going to be in the center surrounded by
    huge panels. Thanks, kablair. However, if you look at the code, these panels are not 800x600 on all sides. The north and south panels only add a combined height of 100, and the east and west panels only add a combined width of 100. so the whole window, minus insets, should be 900x700.
    Anyway, i took the advice of the guy above, and that has gotten me much closer. In the bigger app that I'm trying to calculate the size, now I'm only 2 pixels away from the true size, although I can't figure out what I'm forgetting.

  • Problem with JPanel inside JScrollPane

    I want to make a simple graphic editor (like MS-Paint) with Java.
    I create the frame using JFrame, and use many Swing component. But I found
    some difficult when I tried to create the drawing area (the area where user
    performs drawing). I use JPanel as drawing area and I put it in JScrollPane.
    I use JScrollPane in case if user want to create a big drawing area.
    What I want to do with drawing area is, to put it in JScrollPane with size smaller than JScrollPane but I can't get it because the size of drawing area (JPanel) is always be the same as JScrollPane size. In MS-Paint you can see that the canvas (drawing area) size is able to be resize. And the canvas default color is white, and the Scroll Box around it has darkgray color. How can I make it like that (MS-Paint)? Please help. Thanks...
    Irfin

    I haven't actually tested this, but I think it should work...
    Add a JPanel to the scrollpane setting it's background to grey (i think the dark grey in MSPaint is something easy like 128,128,128). Set the layout on that panel to null, then add a second panel to that panel, at freeze it's size (ie. setMaximumSize). Doing it this way will allow you to set like a (10,10) position or something like that, giving the second panel a position away from the edge of the scrollpane.
    Seeing as you will be using mouse listeners anyways, you might even be able to allow for the second panel to be resized by checking the mouse position to see if the mouse is over the edge of the panel. I won't go into detail, that'll ruin the fun for you.
    Good luck, hope this helps.
    Grant.

  • Problem with JPanel in a JScrollPane

    Hi all,
    I am devloping an application where in i insert the JPanel's object in the JScrollPane object. Intitially the size of the JPanel's object is more than the size of the JScrollPane object.At this point fo time i can drag the nob of the scrollpane to the extent of the size of the JPanel's object. Now When i move the mouse behond the size of the JPanel i am increasing the size of the JPanel's object but i cant move the nob of the scrollpane object behond the original limit.
    For example : when you open a notepad there will be scrollbar without the nob if you keep on pressing the enter key the size of the text area increases and we can see the scroll bar now. I what the similar functionality but
    instead of TextArea i need the panel.
    If any of you have solved this problem or know the solution please do inform. I need to solve this problem very urgently. Please do help me out.
    Thanks in Advance.
    regards
    Ravi

    Hi all,
    I got the solution.we need to revalidate the panel object.
    i.e JPanel.revalidate()
    regards
    Ravi Kumar

  • Dynamically changing the size of a JPanel

    Hi All,
    I am loading multiple images in a JPanel. I want the size of the JPanel to increase dynamically as and when the images are loaded. I have also added a JScrollPane and added the JPanel to this JScrollPane.
    However, the images are cut as soon as it crosses 800 pixels (which is the preferred size of the JScrollPane and it starts to give me NullPointerExceptions where I try to access the image height and width. Here is the code that gives me the problem. The files are opened using the filechooser and put into a Vector, which is then retrieved in the paint() method and rendered to the panel.
    CurrentScreenSize is a Dimension that stores the value of the current screent size that the image pane should have.
    imagePane is the JPanel that contains all the images.
    //File | Open action performed
    void jMenuFileOpen_actionPerformed(ActionEvent e) {
    //Handle open action.
    if (e.getSource() == jMenuFileOpen) {
    fc = new JFileChooser();
    //Filter out only image files (uses Utils.java and ImageFilter.java)
    fc.addChoosableFileFilter(new ImageFilter());
    fc.setAcceptAllFileFilterUsed(false);
    fc.setMultiSelectionEnabled(true);
    int returnVal = fc.showOpenDialog(MainFrame.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File[] files = fc.getSelectedFiles();
    //This is where a real application would open the file.
    int x=10, y=50;
    for(int i=0;i<files.length;i++)
    try {
    Image tempImage = ImageIO.read(files);
    image.add(tempImage);
    if(tempImage.getHeight(this) > currentScreenSize.getHeight())
    currentScreenSize.setSize(currentScreenSize.getWidth()
    + tempImage.getWidth(this),
    tempImage.getHeight(this));
    else
    currentScreenSize.setSize(currentScreenSize.getWidth()
    + tempImage.getWidth(this),
    currentScreenSize.getHeight());
    if (imagePane.getSize().getWidth() <
    currentScreenSize.getSize().getWidth() ||
    imagePane.getSize().getHeight() <
    currentScreenSize.getSize().getHeight())
    imagePane.setSize(currentScreenSize);
    this.pack();
    //repaint();
    catch (IOException ex) {
    ex.printStackTrace();
    //When all images are loaded then paint it / display it
    repaint();
    public void paint(Graphics g){
    int x=10, y=50;
    super.paint(g);
    g = imagePane.getGraphics();
    for (int j=0; j<image.size() ; j++)
    Image img = (Image)image.elementAt(j);
    int imageWidth = img.getWidth(this);
    int imageHeight = img.getHeight(this);
    g.drawImage(img, x, y, imageWidth, imageHeight, this);
    x = x+imageWidth;

    got the Solution, using validate() method does the work under the hood.

  • JScrollPane bars problem Help!!!

    There is some problem with my JScrollPane
    I have added components to the JScrollPane but when components exceeds thee size of the JScrollPane the bars of the JScrollPane are not appearing. Please somebody help me... Just drag the JFrame and increase and decrease its size you will understand my problem. i cant see the remaining components because of no scroll bar.
    Here is a working code...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.*;
    public class test2 extends JFrame implements ActionListener
         JPanel mypanes = new JPanel();     
         //Main Heading 1
         JPanel p1 = new JPanel();     
         JLabel l1 = new JLabel("MEDICINE INFORMATION");
         //Medicine General Information
         JPanel genpane = new JPanel();
         JLabel genl1 = new JLabel("General Information ");     
                   //MGI (1)
                   JPanel genpane1 = new JPanel();
                   JLabel nam = new JLabel("Name:");
                   JTextField gentf1 = new JTextField(14);               
                   JLabel genname = new JLabel("Name:");
                   JTextField gen1tf1 = new JTextField(14);
                   //MGI (2)
                   JPanel genpane2 = new JPanel();
                   JLabel genname1 = new JLabel("Generic Name:");
                   JTextField gen2tf2 = new JTextField(14);
                   //MGI (3)
                   JPanel genpane3 = new JPanel();
                   JLabel genname2 = new JLabel("Manufacturers Name:");
                   JTextField gen3tf3 = new JTextField(14);
                   //MGI (4)
                   JPanel genpane4 = new JPanel();
                   JLabel genname3 = new JLabel("Classification:");
                   JTextField gen4tf4 = new JTextField(14);
                   //MGI (6)
                   JPanel genpane5 = new JPanel();
                   JLabel genname4 = new JLabel("Prescription Required:");
                   JComboBox gen5tf5 = new JComboBox();
                   //Medicine Detailed Information
                   JPanel detpane = new JPanel();
                   JPanel detp2 = new JPanel();
                   JLabel detl1 = new JLabel("Detailed Information");
                   //MDI (1)
                   JPanel detpane1 = new JPanel();
                   //MDI (2)
                   JPanel detpane2 = new JPanel();
                   JLabel detl3 = new JLabel("Common Uses:");
                   //MDI (3)
                   JPanel detpane3 = new JPanel();
                   JTextArea dettf2 = new JTextArea(8,68);
         public test2(String title)
              super(title);
              //Main Heading Panel
              p1.setLayout(new GridLayout(3,3));
              p1.setBackground(Color.white);
              p1.add(new JLabel(""));                    
              p1.add(new JLabel(""));                    
              p1.add(new JLabel(""));                              
              p1.add(new JLabel(""));                    
              l1.setFont(new Font("avant garde bk bt",Font.BOLD,20));
              p1.add(l1);          
              p1.add(new JLabel(""));
              p1.add(new JLabel(""));                    
              p1.add(new JLabel(""));                    
              p1.add(new JLabel(""));     
                   //General Information
              genpane.setLayout(new GridLayout(10,1));
              genl1.setFont(new Font("TimesNewRoman",Font.PLAIN,20));
              genpane.add(genl1);
                   //MGI (1)
                   genpane1.setBackground(Color.white);
                   genpane1.setLayout(new GridLayout(1,5));
                   genpane1.add(new JLabel(""));
                   genpane1.add(new JLabel(""));
                   genpane1.add(new JLabel(""));               
                   genpane1.add(new JLabel(""));     
                   genpane1.add(new JLabel(""));     
                   //MGI (2)
                   genpane2.setBackground(Color.white);
                   genpane2.setLayout(new GridLayout(1,5));
                   genpane2.add(nam);
                   genpane2.add(gentf1);
                   genpane2.add(new JLabel(""));
                   genpane2.add(new JLabel(""));
                   genpane2.add(new JLabel(""));
                   //MGI (3)     
                   genpane3.setBackground(Color.white);
                   genpane3.setLayout(new GridLayout(1,5));
                   genpane3.add(genname1);
                   genpane3.add(gen2tf2);
                   genpane3.add(new JLabel(""));
                   genpane3.add(new JLabel(""));
                   genpane3.add(new JLabel(""));
                   //MGI (4)     
                   genpane4.setBackground(Color.white);
                   genpane4.setLayout(new GridLayout(1,5));
                   genpane4.add(genname2);
                   genpane4.add(gen3tf3);
                   genpane4.add(new JLabel(""));
                   genpane4.add(new JLabel(""));
                   genpane4.add(new JLabel(""));
                   //MGI (5)
                   genpane5.setBackground(Color.white);
                   genpane5.setLayout(new GridLayout(1,5));
                   genpane5.add(genname4);
                   genpane5.add(gen5tf5);
                   genpane5.add(new JLabel(""));
                   genpane5.add(new JLabel(""));
                   genpane5.add(new JLabel(""));               
                   //Medicine Detailed Information               
                   detpane.setLayout(new GridLayout(1,1));
                   detl1.setFont(new Font("TimesNewRoman",Font.PLAIN,20));
                   detpane.add(detl1);                         
                   //MDI(1)
                   detpane1.setBackground(Color.white);
                   detpane1.setLayout(new GridLayout(1,5));
                   detpane1.add(new JLabel(""));
                   detpane1.add(new JLabel(""));
                   detpane1.add(new JLabel(""));
                   detpane1.add(new JLabel(""));
                   detpane1.add(new JLabel(""));
                   //MDI(2)
                   detpane2.setBackground(Color.white);
                   detpane2.setLayout(new GridLayout(1,1));               
                   detpane2.add(detl3);
                   //MDI(3)
                   detpane3.setLayout(new GridLayout(1,1));
                   detpane3.add(dettf2);
                   //Adding Heading 2
                   detp2.setBackground(Color.white);
                   detp2.setLayout(new GridLayout(1,1));     
                   detp2.add(new JLabel(""));               
                   //Adding Panels to the Main JPanel i-e genpane
                   genpane.add(genpane1);
                   genpane.add(genpane2);
                   genpane.add(genpane3);
                   genpane.add(genpane4);
                   genpane.add(genpane5);
                   genpane.add(detp2);
                   genpane.add(detpane);
                   genpane.add(detpane1);                                        
                   genpane.add(detpane2);
                   gen5tf5.addItem("Yes");
                   gen5tf5.addItem("No");                    
                   JScrollPane spp = new JScrollPane(genpane);
                   spp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
                   spp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         mypanes.setBackground(Color.white);
         mypanes.add(p1);
         mypanes.add(spp);
         setContentPane(mypanes);
         public void actionPerformed(ActionEvent ae)
         public static void main(String args[])
              test2 t = new test2("Title");
              t.setSize(800,300);
              t.setVisible(true);

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.

  • JScrollPane Scroll Position

    Tried posting this in the newbie section with no luck....
    I created a class extending a JScrollPane that encompasses a JTextPane. The method below appends some text to the current JTextPane with a certain color (this part works fine). What I am also trying to do is force the JScrollPane to keep focus at the bottom after the append if it was there before the append. Now I am running into trouble.
    The code can determine fine if the scroll pane is at the end, but after the append, it sometimes prematurely puts the pane at the end again; i.e. the method is telling the scroll pane to go to the end before the text pane and/or scroll pane have finished updating their size. Thus, the scroll pane is moved to the bottom, then the text and scroll panes resize, and the scroll pane is no longer at the bottom.
    It seems that this problem occurs when the text appended is multiple lines, in which case it appears that the panes are resized multiple times- the scroll bar is positioned correctly after the first resize, but subsequent resizings sometimes occur after I reposition the scroll bar to the current "end" (which then changes).
    I've tried validating both panes to force them to update before repositioning the scroll bar, but this does not seem to stop the problem (although it may help).
    Does anyone know how to correct this problem? I'm still guessing that something (perhaps the doc?) is not fully updated by the time I reposition the scroll bar. If this is the problem, any suggestions on how to force the document to be updated before playing with these GUI panes? If possible, I prefer not to use a timer or sleep a thread to wait for this updating.
    Of course, if you know of existing methods/settings that help with this, please tell. I didn't manage to find anything in the API's that gave me what I want, but I've been known to overlook things from time to time ;)
    Again, this is a method in a class extending JScrollPane.
    textPane is the JTextPane embedded in the scroll pane.
    doc is the JTextPane document.
    public synchronized void append(String appendString, Color textColor)
         JScrollBar scrollBar;
         BoundedRangeModel rangeModel;
         boolean isMaxed;
         scrollBar = this.getVerticalScrollBar();
         rangeModel = scrollBar.getModel();
         isMaxed = ((rangeModel.getValue() + rangeModel.getExtent())
                             == rangeModel.getMaximum());
              // check if the scroll bar is at the bottom
         SimpleAttributeSet textAttributes = new SimpleAttributeSet();
         StyleConstants.setForeground(textAttributes, textColor);
         try
              doc.insertString(doc.getLength(), appendString, textAttributes);
              // append the formatted string to the document
         catch(BadLocationException ex)
              System.out.println("Error writing to the text pane");
         if (isMaxed)
              textPane.validate();     //force the text pane to validate
              this.validate();    //force the scroll pane to update
              scrollBar.setValue(rangeModel.getMaximum() - rangeModel.getExtent());
              // The above line is sometimes called before the text and scroll panes
              // have finished updating.  The maximum and extent of the scroll bar
              // depend on the size of the document.

    You are correct in your observation that the size of the JScrollPane is incorrectly reflected for the size of your newly appended document. I spent some time on this bug and eventually came up with the following solution:
    textPane.addComponentListener( new ComponentListener(){
    public void componentHidden(ComponentEvent e)
    public void componentMoved(ComponentEvent e)
    public void componentResized(ComponentEvent e)
    JViewport vp = scrollPane.getViewport();
    incoming.revalidate();
    Rectangle visRect = vp.getViewRect();
    Dimension viewDim = vp.getViewSize();
    Rectangle rect = new Rectangle( 0, (int)(viewDim.getHeight() - visRect.getHeight()),
    (int)visRect.getWidth(), (int)visRect.getHeight() );
    vp.scrollRectToVisible( rect );
    public void componentShown(ComponentEvent e )
    This solution also has the side benefit of scrolling to the bottom when the JTextPane is resized by the user.

  • JScrollPane, JPanel used to make a paint-like application

    I am new to swing. I need help with implementing a paint-like application using JScrollPane and JPanel.
    I have put a JPanel inside a JScrollPane.
    The size of JPanel exceeds preferred size of JScrollPane, and i can see the scrollbars, and can go up and down.
    Problem is, when i draw on the JPanel, i can see what i've drawn very clearly. Now if I scroll down, and then scroll back up, whatever i had previously drawn has been erased.
    let me put it in a simpler manner. suppose i have drawn a filled circle whose diameter is equal to the viewport size of the JScrollPane. Now i am scrolling down till i can see only the bottom half of the circle. When i scroll back up, the upper half of the circle has been erased.
    i think this is a newbie error, and i guess it'll have a textbook response, so i have not bothered to paste my entire code here. however, if it is required, please let me know.

    Sounds very much like you're painting outside the paint cycle. Read this,
    http://java.sun.com/products/jfc/tsc/articles/painting/
    When the user draws on the screen, you want to do one of two things (these being just the most obvious and easiest implementations). For raster operations you want to manipulate an Image; for vector operations you want to manipulate a collection of Shapes.
    Your paintComponent() method of the panel should simply draw the stored images and shapes to the supplied Graphics object as appropriate.
    If you paint to a Graphics object outside the paint cycle then it will all be erased when the paint cycle is next invoked.

  • Use of JScrollPane

    I try to use the JScrollPane class with a JPanel, which at the time contains a class compounded of several textboxes and other JComponent subclasses.
    I am not using any layout manager (setting every layout manager to null), and though displaying the components properly inside the JFrame, I don't get the JScrollPane (or the JViewPort in it) to recognize the underlying size of the JPanel, therefore not displaying any scrollbars, horizontal or vertical, when setting the JScrollPane horizontal and vertical scrollbar policies to "as needed". First guess, is that I should set some of the JScrollPane properties manually, such as extent, min, max and so on. Perhaps the problem lies on the LayoutManager.
    The strange point, is that whenever you provide as JViewPort component any root class (such as a texarea), everything works as desired.
    Can anybody help? Hope the explanation is clear.
    Thanks in advance.
    Carlos.

    Carlo,
    try setting the preferred size of the JScrollPane. If that doesn't work, You'll probably have to put your JScrollPane on another JPanel and set the size of THAT JPanel (the one that holds the scrollpane).
    If you just add the JScrollPane onto the JFrame, it will normally take up the whole size of the JFrame.
    If you paste up your code, it may help us understand the problem better.

Maybe you are looking for