JScrollPane in JPanel???

Hi !!!
I want to add a JScrollPane to a JPanel, but it's doesn't work.
class Planche extends JPanel
JFrame f;
public Planche(JFrame f)
this.f = f;
this.setLayout(null);
JPanel p_tousGraphique = new JPanel();
p_tousGraphique.setLayout(null);
JScrollPane scrollPane = new JScrollPane(p_tousGraphique, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
p_tousGraphique.setBounds(10,10,1800,1600);
this.add(scrollPane);
Thanks by advance!!!

Thanks for your answer, it's help to find the solution. The script display the scrollpane in the panel. But I have a problem. I want to put some componement in the jpanel and I do disable the layour manager
p_tousGraphique.setLayout(null);
But when I remove this line the scrollbar work fine, but my componement doesn't display like I want. So I disable the layour manager. The scrollbar display in jpanel but it doesn't scroll, dispite I have some componement that I don't see in my eye.
Thanks by advance !!!
My script that I do:
this.setLayout(new BorderLayout());
p_tousGraphique.setLayout(null);
JScrollPane scrollPane = new JScrollPane(p_tousGraphique, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(p_tousGraphique.getWidth(),p_tousGraphique.getHeight()));
this.add(scrollPane);
this is my principale JPanel

Similar Messages

  • JScrollpane and JPanel help

    i have a panel which is bigger than the main window's size. i want to add it onto the ScrollPane. but the scrollbar is not working. how do i refresh the scrollbar so that the scrollbar comes when the JPanel is attached onto it.

    the full code is
    public EditorPanel(int flag,String title,EditorFrame ed)
    Toolkit tk=Toolkit.getDefaultToolkit();
    clipBoard=tk.getSystemClipboard();
    write = new JTextPane();
    fileFlag=flag;
    fileName=title;
    edf=ed;
    EditorKit editorKit = new StyledEditorKit()     
    public Document createDefaultDocument()     
    {return new ColorSyntax();
    searchIndex=0;
         // creating the toolbar          
         toolBar=new JToolBar();
         addButtons(toolBar);
         toolBar.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
         toolBar.setFloatable(false);
         toolBar.setBounds(0, 0, 800, 20);
         write.setEditorKitForContentType("text/8085", editorKit);
         write.setContentType("text/8085");
         write.replaceSelection("");
         write.requestFocus();
         write.addKeyListener(this);
         write.registerKeyboardAction(edf.getUndoAction(),KeyStroke.getKeyStroke,KeyEvent.VK_Z,InputEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
         write.registerKeyboardAction(edf.getRedoAction(),KeyStroke.getKeyStroke(KeyEvent.VK_Y,InputEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
         Dimension d=tk.getScreenSize();
         StyledDocument styledDoc = write.getStyledDocument();
         AbstractDocument doc = (AbstractDocument)styledDoc;
         doc.addUndoableEditListener(new MyUndoableEditListener());
    //problem is here
         scrollpane = new JScrollPane(write);          
         scrollpane.setPreferredSize(new Dimension((2*d.width)/3 - 15,3*d.height/4));
         scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         // making the object of the device panel to be added onto the device scroller
         devAddPanel =new DeviceAddPanel();
         deviceScrollpane = new JScrollPane();
         deviceScrollpane.setViewportView(devAddPanel);
         deviceScrollpane.setPreferredSize(new Dimension((d.width)/3 - 15,3*d.height/4));
         deviceScrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         add(toolBar, BorderLayout.PAGE_START);
         //Create a split pane with the two scroll panes in it.
         splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,deviceScrollpane,scrollpane);
         splitPane.setOneTouchExpandable(true);
         splitPane.setDividerLocation(((d.width)/3)-5);
         splitPane.setContinuousLayout(true);
         splitPane.setDividerSize(15);
         add(splitPane, BorderLayout.CENTER);
    //problem ends here
    i am creating a split pane in which on the left i am adding the device panel which is giving the problem even though the panel is bigger that the scrollpane's size it is not showing the vertical scrollbar. the right side with the text area is working fine

  • JScrollPane containing JPanel HELP!

    Hi again,
    I'll try my luck again!
    Ok, I have a JPanel that uses a GridBagLayout with 3 columns and many rows. Each row is of the form:
    [JLabel][JTextField][JButton]
    Ok. Since I have many of these rows, and my application should be a constant size, I need to somehow make you able to scroll down the list of these labels,textfields and buttons - to the one you want. I have tried making the containing JPanel the viewport of a JScrollPane, however, when I only have a couple of rows of labels, textfields, and buttons, each expands to fit the viewport size - and they turn out looking really dumb.
    How can I get it so that the labels, textfields and buttons are only the height of the text in each?
    Please please, please, please help me.
    sincerely, Edd.

    Chenge the weight (x&y) in the GridBagConstraints of the components you don't want to expand to 0.0. Change the fill to GridBagConstraints.NONE.

  • To insert JScrollPane in JPanel

    Hi! I have a problem, want to put a JScrollPane in a JPanel, since in the JPanel a graph shows itself and I wanted to be able to move towards the right when I exceed the JPanel, but I put:
    scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    add( scroll,BorderLayout.CENTER );
    But does not it(he,she) appear, podeis to help myself? Thank you

    Hello again, I feel it but I do not understand you well. This uses but I do not work either, some another idea? Thank you
    calculo = new CalculoPanel(this,lanza);
    scroll = new JScrollPane(calculo);                    
    add(scroll, BorderLayout.CENTER);
    jpnInferior = new JPanel(gblInformacion);
    containerPanel.add("South",jpnInferior);
    jpnInferior.add(calculo,gbcInformacion);
    Message was edited by:
    agsim

  • Dynamically resizing Knobs on JScrollPane when JPanel contents grows

    If I dynamically add components to a JPanel (causing it to grow in length e.g. Flowlayout) that is inside a JScrollPane how can I detect and adjust the JScrollPane knobs so that they show the complete JPanel.
    I know that if I set the JPanel's preferred size it will do this, but how do I know what this size is? I don't want to have to track the size of the components I am adding to the JPanel and work it all out manually, there must be an easier way to do it.

    I know that if I set the JPanel's preferred size it will do this
    there must be an easier way to do it. You should NOT be manually setting the preferred size, just let the layout manager calculate it.
    After adding components to the panel you just invoke:
    panel.revalidate();

  • Adding JScrollPane on JPanel??Is there any problem.??

    hi,
    I have a JPanel over which i added a JScrollPane on to whose view portvie i added a JTable.
    But the problem is the table is not getting visble.Not only table all the components i add to scrollpane which on a panel is not getting displayed.
    Am i missing something??
    final JScrollPane scrollPane = new JScrollPane();
              panel.add(scrollPane);
              table = new JTable();
              scrollPane.setViewportView(table);

    Make sure to add the panel to the content pane as well.
    If the problem still persists, then please post a simple executable demo program that demonstrates the behavior.

  • Problem with JPanel and JScrollPane

    Hey,
    I have a class which extends JPanel. Inside this class I would like to have a JScrollPane.
    However, it does not seem to work.
    public class Summary extends JPanel
         JScrollPane scrollPane;
         JPanel p;
         public Summary()
              p = new JPanel()
                          public void paintComponent(Graphics g)
                                 /// do painting here!!!!
              setLayout(null);
              setBorder(BorderFactory.createLineBorder(Color.green));
              setBounds(0,0,240,290);
              //p.setLayout(null);
              p.setLayout(new FlowLayout());
              p.setBorder(BorderFactory.createLineBorder(Color.black));
              //p.setBounds(0,0,240,590);
              p.setPreferredSize(new Dimension(240,500));
              p.add(new JButton("test"));
              scrollPane = new JScrollPane(p);
              scrollPane.setLayout(null);
              scrollPane.setBounds(0,0,240,290);
              scrollPane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
              add(scrollPane);
         }Any advice????
    thanks in advance

    Any advice????ditch this
    setLayout(null);

  • 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.

  • How to enable a scrollbar in a JPanel

    Hi
    I am adding some components in a JPanel and I am adding the JPanel to a JScrollPane.The JScrollPane is finally added to the container.Now I could manage to get only the scrollbars added but it does not work!How should I use the scrollbars to view all the components that are added inside the JPanel.
    Here is my source code:
    tagPanel = new JPanel();
    tagPanel.setLayout(new FlowLayout());
    tagPanel.setPreferredSize(new Dimension(100,100));
    tagPanel.setBackground(Color.white);
    tagPanel.setAutoscrolls(true);
    for(int i = 0; i<=20; i++)
    tempButton = new JButton("Testing");
    tagPanel.add(tempButton);
    container.add(forbiddenscroll= new JScrollPane
    (tagPanel),BorderLayout.WEST);
    forbiddenscroll.setHorizontalScrollBarPolicy
    (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    forbiddenscroll.setVerticalScrollBarPolicy
    (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    Thank you for your reply!
    Your help is very much appreciated.

    don't set prefered size of the tag panel.
    run this code pasted below. it work fine.
    regards,
    Pratap
    import java.awt.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
         JScrollPane forbiddenscroll;
         JPanel tagPanel;
         JButton tempButton;
         public Frame1() {
              tagPanel = new JPanel();
              tagPanel.setLayout(new FlowLayout());
              tagPanel.setBackground(Color.white);
              tagPanel.setAutoscrolls(true);
              for(int i = 0; i<=20; i++)
                   tempButton = new JButton("Testing");
                   tagPanel.add(tempButton);
              forbiddenscroll = new JScrollPane();
              forbiddenscroll.getViewport().setView(tagPanel);
              getContentPane().add(forbiddenscroll, BorderLayout.CENTER);
              forbiddenscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
              forbiddenscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         public static void main(String[] args) {
              Frame1 f = new Frame1();
              f.pack();
              f.setLocation(200,200);
              f.show();
    }

  • 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

  • JScrollPane, JTextPane, Weird scrolling happening

    The code below shows the problem I am having: In short, I have a textPane in a scrollPane but when I try to getViewPort.setViewPosition(0,0); then the scroll pane briefly flashes to position 0,0 then re positions itself to display the bottom of the text pane. It is driving me wild! If I removed the InsertString function call used on the Document of the textPane, then it works as I thought it should (apart from an initial glitch where the slider bar is placed near the top...- see example)
    in the example I have a 'tall' JTextPane (ie, lot's of linefeeds) with a red panel all in a JPanel which inturn lies in a JScrollPane. Click on the 'Force Update' button to force the Text pane to be updated (in my real java class, there is other stuff to change the values of the textpane) and to set the display position to 0,0. Notice how the slider button flashes to the top of the vertical bar then returns to the bottom. If you cick on the 'toggle InsetString Active' button, then the code to Insert the String to the textArea is by-passed. Now clicking on the 'Force Update' button (after the initial glitch) does send the view to the top of the Jpanel(which now contains an empty textarea and a red panel).
    Can anyone give any clues as to what is causing the Scroll pane to redraw to the bottom of the panel? (and what is causing the glitch after the toggle InsertString button is pressed?)
    I have tried it on JDK 1.3.1 and 1.4 and scoured the groups for similar problems but found none. Lots have people had prblems getting the JScrollpane to the bottom of the textpane but I can't seem to stop it going down!
    I'd appreciate any help as I'm quickly going bald....
    Marc
    code begins....
    -------------------------cut here--------------------------
    import javax.swing.*;
    import java.awt.*; //for layout managers
    import java.awt.event.*; //for action and window events
    import javax.swing.text.*;
    public class WierdScroll extends JFrame
    ScrollPane scrollPane = null;
    JButton button = null;
    JButton b2 = null;
    JPanel screen = null;
    // below is the style to be associated with the textpane
    static private SimpleAttributeSet normalStyle = new SimpleAttributeSet(StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
    static
    StyleConstants.setFontFamily(normalStyle, "Courier");
    StyleConstants.setFontSize(normalStyle, 12);
    public WierdScroll()
    super("Wierd Scrolling \'feature\'");
    // create and setup the components
    screen = new JPanel();
    scrollPane = new ScrollPane();
    scrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(250, 155));
    scrollPane.setMinimumSize(new Dimension(10, 10));
    scrollPane.updateConstraintView();
    button = new JButton("Force update");
    button.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    scrollPane.updateConstraintView();
    b2 = new JButton("toggle InsertString Active");
    b2.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    JButton b = (JButton) e.getSource();
    scrollPane.allowInsertString = !scrollPane.allowInsertString;
    scrollPane.updateConstraintView();
    // add the component to the frame
    screen.add(scrollPane);
    screen.add(button);
    screen.add(b2);
    getContentPane().add(screen);
    public static void main(String[] args) {
    JFrame frame = new WierdScroll();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    // this extended class is the scrollpane. The problem occurrs when the doc.insertString function is called;
    // When insertString is called, the scroll pane flicks to the bottom of the scroll view but when insertString
    // is not called then the setViewPostion works OK....
    public class ScrollPane extends JScrollPane
    public JPanel panel;
    public JTextPane margin;
    public boolean allowInsertString = true;
    /** Creates a new instance of ConstraintView */
    public ScrollPane()
    // create the pane
    margin = new JTextPane();
    // create the label
    JPanel jp = new JPanel();
    jp.setBackground(Color.red);
    jp.setPreferredSize(new Dimension(500,500));
    panel = new JPanel();
    panel.setBackground(Color.white);
    // add the label and pane to the panel
    panel.add(margin);
    panel.add(jp);
    // set the scroll voew to be the panel
    setViewportView(panel);
    public void updateConstraintView()
    // if doc has stuff in it, then clear contents
    Document doc = margin.getDocument();
    if (doc.getLength() > 0)
    try
    doc.remove(0, doc.getLength());
    catch (BadLocationException ble) {}
    // the allowInsertString is toggled via button on screen to stop insertString call
    if (allowInsertString)
    try {
    doc.insertString(0, "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", normalStyle);
    catch (BadLocationException ble) {}
    // set viewport so that it scrolls to top
    getViewport().setViewPosition(new Point(0,0));

    Cheers!
    using the setCaretPosition() of the JTextPane instead of the getViewport().setViewPosition(new Point(0,0)) method of the JScrollPane works a treat.
    But I would have thought that the scroll pane should have 'complete' control (unless specified by programmer) of what it displays. It seems strange to have a component of a scrollpane dictate to the scrollpane what it should show...
    Thanks for your assistance.
    On a different note, has anyone noticed that the word 'c l a s s' has become cl***?? Is this a victim of sun's new swear filter to go with the new site look?

  • Problem in refreshing JTree inside Jscrollpane on Button click

    hi sir,
    i have problem in refreshing JTree on Button click inside JscrollPane
    Actually I am removing scrollPane from panel and then again creating tree inside scrollpane and adding it to Jpanel but the tree is not shown inside scrollpane. here is the dummy code.
    please help me.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.tree.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class Test
    public static void main(String[] args)
         JFrame jf=new TestTreeRefresh();
         jf.addWindowListener( new
         WindowAdapter()
         public void windowClosing(WindowEvent e )
         System.exit(0);
         jf.setVisible(true);
    class TestTreeRefresh extends JFrame
         DefaultMutableTreeNode top;
    JTree tree;
         JScrollPane treeView;
         JPanel jp=new JPanel();
         JButton jb= new JButton("Refresh");
    TestTreeRefresh()
    setTitle("TestTree");
    setSize(500,500);
    getContentPane().setLayout(null);
    jp.setBounds(new Rectangle(1,1,490,490));
    jp.setLayout(null);
    top =new DefaultMutableTreeNode("The Java Series");
    createNodes(top);
    tree = new JTree(top);
    treeView = new JScrollPane(tree);
    treeView.setBounds(new Rectangle(50,50,200,200));
    jb.setBounds(new Rectangle(50,300,100,50));
    jb.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
              jp.remove(treeView);
              top =new DefaultMutableTreeNode("The Java ");
    createNodes(top);
              tree = new JTree(top);
                   treeView = new JScrollPane(tree);
                   treeView.setBounds(new Rectangle(50,50,200,200));
                   jp.add(treeView);     
                   jp.repaint();     
    jp.add(jb);     
    jp.add(treeView);
    getContentPane().add(jp);
    private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode book = null;
    category = new DefaultMutableTreeNode("Books for Java Programmers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Tutorial Continued: The Rest of the JDK");
    category.add(book);
    book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs");
    category.add(book);
    book = new DefaultMutableTreeNode("Effective Java Programming Language Guide");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Programming Language");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Developers Almanac");
    category.add(book);
    category = new DefaultMutableTreeNode("Books for Java Implementers");
    top.add(category);
    book = new DefaultMutableTreeNode("The Java Virtual Machine Specification");
    category.add(book);
    book = new DefaultMutableTreeNode("The Java Language Specification");
    category.add(book);
    }

    hi sir ,
    thaks for u'r suggession.Its working fine but the
    properties of the previous tree were not working
    after setModel() property .like action at leaf node
    is not working,I'm sorry but I don't understand. I think you are saying that the problem is solved but I can read it to mean that you still have a problem.
    If you still have a problem then please post some code (using the [code] tags of course).

  • JScrollPane scroll setting first column is not visible?

    Hi All,
    i am using jtable and jscrollpane. in this my first column of 70 pixal width and rest 125 pixal width.set focus is on 1 cell(1 row, 1 column) in table. but due to this scrollbar is slightly on right side whice coz first column not visible.(need to drag for visibility). i am trying to make it visible without dragging.
    how to do this? HELP.
    i tried with tableScroll.scrollRectToVisible(table.getCellRect(0,0,true )); & -1,-1
    but it didnt worked.
    Code is like this..........
    table = new JTable(64,65){
    table.setName("Table");
    ((DefaultTableModel)table.getModel()).setColumnIdentifiers(vectName.getColumnIdentifiers());
              for(int i = 0;i<table.getRowCount();i++) {
                   table.setValueAt((i+1)+"",i,0);
              table.setGridColor(Color.black);
              table.setSelectionBackground(new Color(125,255,144));
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              table.setCellSelectionEnabled(true);          
              table.addKeyListener(listener);
              table.addMouseListener(listener);
              table.getSelectionModel().addListSelectionListener(this);
              table.getColumnModel().addColumnModelListener(this);
              table.getColumnModel().getColumn(0).setResizable(false);
              table.getColumnModel().getColumn(0).setMinWidth(70);
              table.getColumnModel().getColumn(0).setMaxWidth(70);
    JScrollPane tableScroll = new JScrollPane(table);
    Dimension minimumSize = new Dimension(100,25);
    tableScroll.setMinimumSize(minimumSize);          
    add(tableScroll);

    Hi weebib ,
    pls find some working code which shous my problame .
    you can see its coming to column 'B'. but i want it to show from column 'A' .
    sample working code : =
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.util.*;
    public class myTable extends JFrame{
    JTable table;
    JScrollPane jsp;
    JPanel p1;
    int NO_OF_ROWS = 64;
    int NO_OF_COLUMNS = 65;
    Vector vColumnNames ;
    myTable(){
         Container con = getContentPane();
         p1 = new JPanel();
         table = new JTable(NO_OF_ROWS,NO_OF_COLUMNS){
              public boolean isCellEditable(int row, int column) {
                                  if(column == 0){
                                       return false;
                                  else{
                                       return true;
         setTableProperties();
         jsp = new JScrollPane(table);
         p1.add(jsp);
         con.add(p1);
         setSize(400,500);
         show();
         //System.out.println("Hello there");
    public Vector getColumnIdentifiers(){
         vColumnNames = new Vector();
                   for(int i=65;i<129;i++) {
                        vColumnNames.add(new String((char)i+""));// setting the alphabets for the column names //orig
         return vColumnNames ;
    public void setTableProperties(){
         ((DefaultTableModel)table.getModel()).setColumnIdentifiers(getColumnIdentifiers());
         for(int i = 0;i<table.getRowCount();i++) {
                        table.setValueAt((i+1)+"",i,0);// Set the names of the row
         table.setGridColor(Color.black);
         table.setSelectionBackground( Color.RED);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.setCellSelectionEnabled(true);
         table.addMouseListener(new myMouseListener());
         table.addKeyListener(new myKeyListener());
    //     table.getColumnModel().getColumn(0).setPreferredWidth(125);
    //     table.getColumnModel().getColumn(0).setResizable(false);
    //     table.getColumnModel().getColumn(0).setMinWidth(70);
    //     table.getColumnModel().getColumn(0).setMaxWidth(70);
         for(int u =0 ;u<64;u++){
              if(u==0){
                   table.getColumnModel().getColumn(u).setPreferredWidth(70);
              else{
                   table.getColumnModel().getColumn(u).setPreferredWidth(200);
         table.changeSelection(0,1,false,false);
    static public void main(String[] args){
              myTable test = new myTable();
              test.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){System.exit(0);}
    public class myMouseListener extends MouseAdapter{
         public void mousePressed(MouseEvent me){
                   table.repaint();
    public class myKeyListener extends KeyAdapter{
         public void keyPressed(KeyEvent ke){
                   if(table.getSelectedColumn() == 0){
                        ke.consume();
    ================
    pls do reply back if i am doing something wrong.
    == Gavin

  • 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,

  • JScrollPane bar alignment

    I posted this to ProjectSwing forum and never got a reply, maybe here someone knows...
    I tried all the suggested methods, and yet I still get the vertical scroll bar aligned somewhere in the middle when the JFrame opens, when top alignment would be preferable... Any suggestion on this is more than welcome. My code is structured with nested components like this:
    JScrollPane scroll
    ---JPanel allJPanels
    ------JPanel a
    ---------JPanel a_1
    ---------JLabel a_2
    ---------JEditorPane a_3
    ------JPanel b
    ---------JPanel b_1
    ---------JLabel b_2
    ---------JEditorPane b_3
    scroll.setViewportView( allJPanels );
    Methods attempted:
    scroll.getVerticalScrollBar().setValue( scroll.getVerticalScrollBar().getMinimum() );
    OR
    scroll.getViewport().setViewPosition( new java.awt.Point( 0, 0 ) );
    OR
    scroll.getVerticalScrollBar().getModel().setValue( 0 );
    OR
    allJPanels.scrollRectToVisible( new java.awt.Rectangle( 1, 1, allJPanels.getWidth(), allJPanels.getHeight() ) );
    Thanks for any suggestion

    Strangely the problem was due to how this JFrame was initialised in another JFrame with the usual .pack() and .setVisible(). By implementing Runnable and initialising with new Thread and .start() in the main application JFrame the scroll bar seemed to obey its settings and aligned correctly to the top.

Maybe you are looking for

  • Loss on scrap sales to be reflected externally

    Hi , The following things reflect while dealing with scrap sales loss.. When the assets which are declared as scrap are retired/ deleted from Asset Inventory list from Asset module, using T-Code ABAVN the system automatically create/post a document c

  • Average Calculation in Hierarchial ALV

    Hi, I need to calculate average mean in hierarchial alv. the standard menu for calculate totals is disabled in both in function module REUSE_ALV_HIERSEQ_LIST_DISPLAY and in the class cl_salv_hierseq_table. Please help with this Regards, Mathivanan.G

  • Strange behavior of GregorianCalendar

    Hi all, There�s a strange behavior of GregorianCalendar class which spend my time and my patience. After I discovered the problem, I run this code... System.out.println("Data1: " + gcTemp.get(gcTemp.DAY_OF_MONTH)); gcTemp.add(gcTemp.DAY_OF_MONTH, 1);

  • Difference between Proxy pattern and Business Delegate pattern

    Hi All, Can any one please tell me what is the difference between Proxy pattern and Business Delegate pattern. Thanks in advance. Basak

  • How do I remove my wifes contacts from my phone?

    How do I delete my wife's contacts from my phone?