JScrollPane is smearing JPanel

When painting to a panel inside a JScrollPane, I am having problems with the panel smearing as I scroll. It looks just as though it's repainting over what was already painted on the panel. Just as some testing, I called repaint within my paint method just to try and determine where the issue was coming from. While this didn't fix the issue nor kill my processor, it did seem to make it a little better. Could this be a problem as to the way I am drawing to the panel, or an issue with my use of the JScrollPane?
Here is my SongDisplay class that extends a JPanel:
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JPanel;
* @author tlee
public class SongDisplay extends JPanel implements /*MouseListener,*/ SongDisplayInterface
    List<SongFileWordDisplay> words = Collections.synchronizedList(new ArrayList<SongFileWordDisplay>());
    public SongDisplay()
        super();
        /*this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
          this.addMouseListener(this);*/
    @Override
    public void paint(Graphics g)
        g.setColor(Color.BLACK);
        synchronized (words)
            for (SongFileWordDisplay word : words)
                g.drawString(word.getLyric(), word.getPoint().x, word.getPoint().y);
    public void setWidth(int width)
        this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
        super.revalidate();
    public synchronized void addSongFileWordDisplay(SongFileWordDisplay sfwd)
        words.add(sfwd);
        this.repaint();
}

tristanlee85 wrote:
When painting to a panel inside a JScrollPane, I am having problems with the panel smearing as I scroll. It looks just as though it's repainting over what was already painted on the panel. Just as some testing, I called repaint within my paint method just to try and determine where the issue was coming from. While this didn't fix the issue nor kill my processor, it did seem to make it a little better. Could this be a problem as to the way I am drawing to the panel, or an issue with my use of the JScrollPane?
Here is my SongDisplay class that extends a JPanel:
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JPanel;
* @author tlee
public class SongDisplay extends JPanel implements /*MouseListener,*/ SongDisplayInterface
List<SongFileWordDisplay> words = Collections.synchronizedList(new ArrayList<SongFileWordDisplay>());
public SongDisplay()
super();
/*this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
this.addMouseListener(this);*/
@Override
public void paint(Graphics g)
g.setColor(Color.BLACK);
synchronized (words)
for (SongFileWordDisplay word : words)
g.drawString(word.getLyric(), word.getPoint().x, word.getPoint().y);
public void setWidth(int width)
this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
super.revalidate();
public synchronized void addSongFileWordDisplay(SongFileWordDisplay sfwd)
words.add(sfwd);
this.repaint();
It is definetly a problem in your paint--you need to call super.paint(g) as the first thing so your object will be painted correctly before you try to put your twist of the world in there.

Similar Messages

  • How to add a JScrollPane in a JPanel

    I have a JPanel (layout = null, size = 200*400).
    I would like to add a JScrollPane, that sizes 100*100 and that contains an other JPanel, at the location 0,200 in the first JPanel. I would like too that the JScrollBar is always visible.
    How is it possible ?

    The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scroll pane. So you probably need to add:
    panel.setPreferredSize(...);
    Of course if you use LayoutManagers, instead of a null layout, then this is done automatically for you.
    If you want the scroll bars to appear all the time then read the JScrollPane API.

  • JScrollPane, JTextPane and JPanel... wtf?

    i am working on a extending a JPanel to have a JTextPane in a JScrollPane. When i add the JTextPane to the JScrollPane inside of the JPanel object it doesn't scroll horizontally, but when i add the whole panel to a JScrollPane in the JFrame that i have testing it, it does scroll horizontally, the JScrollPane in both instances the JScrollBar has both horizontal and vertical scrolling set to as needed.
    why is this happening?

    Thanks for your answers!
    Revalidating did the trick, however I still have a problem with the JScrollPane... I created a new JScrollPane and wrote so:
    myScrollPane = new JScrollPane(internalPanel);
    myScrollPane.setPreferredSize(new java.awt.Dimension(2, 205));
    myScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    //Added Code
    handScrollPane.setViewportView(handPanel);
    //End Added Code
    mainPanel.add(myScrollPane, BorderLayout.SOUTH);Then whenever items were added to the internalPanel I changed the scroll-bar's maximum value to the height of the internalPanel by writing:
    myScrollPane.getVerticalScrollBar().setMaximum(internalPanel.getHeight());But when I run my application, the scroll-bar's maximum value doesn't change even though items are added to the internalPanel. Why is this?
    With Thanks,
    laginimaineb.
    B.U.M.P (Sorry)

  • I can't interact (scroll) my scrollbars in JScrollPane on a JPanel

    Hi, I'm having trouble with my textarea with jscrollpane that is on an overidden JPanel to paint a background image. My first problem is that I can't even see the scrollpane but I fixed that through g.setXORMode(true). Now, my problem is even though I can see the component perfectly, when I try to scroll, it won't scroll (unclickable). Is there any way to fix this?
    -I heard that I should try to add the jscrollpane to a component (like JLabel) that's always above the image. But it didn't work. I am not sure i did it right though, so I am looking for other options.
    Anyways, here is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.metal.*;
    import java.util.*;
    public class SrtfMvtDemo extends JFrame implements ActionListener, Runnable {
         public DemoJPanel demoPanel = new DemoJPanel();
         private     JPanel     buttonPanel = new JPanel();
         private     JButton     buttonOpen = new JButton("Open"),
                             buttonStart = new JButton("Start"),
                             //buttonReset = new JButton("Reset"),
                             buttonPause = new JButton("Pause"),
                             buttonAbout = new JButton("About");
         public ImageIcon imageBg = new ImageIcon("img//logo.jpg");
         public ImageIcon imageDiagram = new ImageIcon("img//diagram.gif");
         private int[] xLocations = {550,522,494,466,438,410,382,354,326,298,272,242,
              214,186,158,130,102,74,46,18};
         private int[] xxLocations = {18,46,74,102,130,158,186,214,242,272,298,326,
              354,382,410,438,466,494,522,550};
         public static JLabel[] jqLabels = new JLabel[20];
         public static JLabel[] rqLabels = new JLabel[20];
         public static JLabel[] ioqLabels = new JLabel[20];
         private boolean isStarted = false;
         private boolean isFinished = false;
         public static final Color foreColor = Color.WHITE;
         public static boolean isPaused = false;
         public static JScrollPane scrollpane1;
         public static JScrollPane scrollpane2;
         public static JScrollPane scrollpane3;
         public static MVT memory = new MVT();
         public static CPU cpu = new CPU();
         public static IO ioDevice = new IO();
         public static JobQueue jQueue = new JobQueue();
         public static ReadyQueue rQueue = new ReadyQueue();
         public static IOQueue ioQueue = new IOQueue();
         public static Vector fQueue = new Vector(0,1);
         public static JTextArea cpuGantt = new JTextArea(3,20);
         public static JTextArea ioGantt = new JTextArea(3,20);
         public static JTextArea statistics = new JTextArea(3,30);
         public static JLabel procCpu = new JLabel();
         public static JLabel procIO = new JLabel();
         public static JPanel nonOver = new JPanel();
         public Thread mainThread = new Thread(this);
         public static int nTimer = -1;
         public SrtfMvtDemo() {
              super("INTROOS: SRTF - MVT Algorithm Demonstrator");
              setSize(800,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              setForeground(Color.white);
              setResizable(false);
              getContentPane().setLayout(null);
              buttonOpen.addActionListener(this);
              buttonStart.addActionListener(this);
              buttonPause.addActionListener(this);
              buttonAbout.addActionListener(this);
              buttonStart.setEnabled(false);
              buttonPause.setEnabled(false);
              demoPanel.setLayout(null);
              demoPanel.setSize(800,525);
              demoPanel.setLocation(0,0);
              buttonPanel.setSize(800,75);
              buttonPanel.setLocation(0,526);
              buttonPanel.setLayout(new FlowLayout());
              buttonPanel.add(buttonOpen);
              buttonPanel.add(buttonStart);
              buttonPanel.add(buttonPause);
              buttonPanel.add(buttonAbout);
              getContentPane().add(demoPanel);
              getContentPane().add(buttonPanel);
         private void showUI() {
              //Job Queue Labels
              for(int i=0; i<20; i++) {
                   jqLabels[i] = new JLabel();
                   jqLabels.setVerticalTextPosition(JLabel.CENTER);
                   jqLabels[i].setHorizontalTextPosition(JLabel.CENTER);
                   jqLabels[i].setForeground(Color.white);
                   jqLabels[i].setSize(25,25);
                   jqLabels[i].setLocation(xLocations[i],28);
                   demoPanel.add(jqLabels[i]);
              //Ready Queue Labels
              for(int i=0; i<20; i++) {
                   rqLabels[i] = new JLabel();
                   rqLabels[i].setVerticalTextPosition(JLabel.CENTER);
                   rqLabels[i].setHorizontalTextPosition(JLabel.CENTER);
                   rqLabels[i].setForeground(Color.white);
                   rqLabels[i].setSize(25,25);
                   rqLabels[i].setLocation(xxLocations[i],97);
                   demoPanel.add(rqLabels[i]);
              //IO Queue Labels
              for(int i=0; i<20; i++) {
                   ioqLabels[i] = new JLabel();
                   ioqLabels[i].setVerticalTextPosition(JLabel.CENTER);
                   ioqLabels[i].setHorizontalTextPosition(JLabel.CENTER);
                   ioqLabels[i].setForeground(Color.white);
                   ioqLabels[i].setSize(25,342);
                   ioqLabels[i].setLocation(xLocations[i],97);
                   demoPanel.add(ioqLabels[i]);
              procCpu.setSize(100,20);
              procCpu.setLocation(450,209);
              procCpu.setForeground(Color.white);
              procCpu.setBackground(Color.black);
              demoPanel.add(procCpu);
              procIO.setSize(100,20);
              procIO.setLocation(450,374);
              procIO.setForeground(Color.white);
              procIO.setBackground(Color.black);
              demoPanel.add(procIO);
              cpuGantt.setBackground(Color.black);
              cpuGantt.setForeground(Color.white);
              cpuGantt.setEditable(false);
              cpuGantt.setLineWrap(true);
              cpuGantt.setWrapStyleWord(true);
              cpuGantt.setSize(557,47);
              cpuGantt.setLocation(15,162);
              cpuGantt.setAutoscrolls(true);
              //demoPanel.add(cpuGantt);
              scrollpane1 = new JScrollPane(cpuGantt,
                   JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                   JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              scrollpane1.setSize(557,47);
              scrollpane1.setLocation(15,162);
              //demoPanel.add(scrollpane1);
              ioGantt.setBackground(Color.black);
              ioGantt.setForeground(Color.white);
              ioGantt.setEditable(false);
              ioGantt.setLineWrap(true);
              ioGantt.setWrapStyleWord(true);
              ioGantt.setSize(557,47);
              ioGantt.setLocation(15,327);
              ioGantt.setAutoscrolls(true);
              //demoPanel.add(ioGantt);
              scrollpane2 = new JScrollPane(ioGantt,
                   JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                   JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              scrollpane2.setSize(557,47);
              scrollpane2.setLocation(15,327);
              //demoPanel.add(scrollpane2);
              statistics.setBackground(Color.black);
              statistics.setForeground(Color.white);
              statistics.setEditable(false);
              statistics.setLineWrap(true);
              statistics.setWrapStyleWord(true);
              statistics.setSize(760,100);
              statistics.setLocation(18,405);
              statistics.setAutoscrolls(true);
              //demoPanel.add(statistics);
              scrollpane3 = new JScrollPane(statistics,
                   JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                   JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              scrollpane3.setSize(760,100);
              scrollpane3.setLocation(18,405);
              //demoPanel.add(scrollpane1);
              //demoPanel.add(scrollpane2);
              //demoPanel.add(scrollpane3);
              nonOver.setLayout(null);
              nonOver.setSize(800,525);
              nonOver.setLocation(0,0);
              nonOver.setOpaque(false);
              nonOver.add(scrollpane1);
              nonOver.add(scrollpane2);
              nonOver.add(scrollpane3);
              demoPanel.add(nonOver);
         public static void main(String[] args) {
              MetalLookAndFeel.setCurrentTheme(new JetTheme());
              try {
                   UIManager.setLookAndFeel(new MetalLookAndFeel());
              } catch(Exception e) {}
              setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              SrtfMvtDemo mainDemo = new SrtfMvtDemo();
              mainDemo.setVisible(true);
         public void actionPerformed(ActionEvent ae) {
              if(ae.getSource()==buttonOpen) {
                   Opener open = new Opener();
                   isStarted = open.doOpen();
                   if(isStarted) {
                        buttonStart.setEnabled(true);
                        buttonPause.setEnabled(true);
              if(ae.getSource()==buttonStart) {
                   buttonOpen.setEnabled(false);
                   buttonStart.setEnabled(false);
                   showUI();
                   isStarted = true;
                   showUI();
                   mainThread.start();
              if(ae.getSource()==buttonPause) {
                   isPaused = !isPaused;
              if(ae.getSource()==buttonAbout) {
                   JOptionPane.showMessageDialog(null, "This machine project is made "+
                        "by:\nAndrei Victor\nJohanne Pagaduan\nOliver Recio\nINTROOS S11",
                        "About", JOptionPane.INFORMATION_MESSAGE);
         public void run() {
              do {
                   while(!isPaused) {
                        if(fQueue.size() > 0 && fQueue.size() == Job.getNumberOfJobs()) {
                             isFinished = true;
                             break;
                        try {
                             mainThread.sleep(10);
                        } catch(Exception e) {
                        nTimer++;
                        System.out.println("Time: " + nTimer);
                        if(cpu.currentJob != null)
                             System.out.println("J"+cpu.currentJob.getID()+" Burst: "+cpu.currentJob.getBurst());
                        jQueue.check();
                        rQueue.check();
                        cpu.check();
                        ioQueue.check();
                        ioDevice.check();
                        repaint();
              } while(!isFinished);
              JOptionPane.showMessageDialog(null, "Simulation Finished", "Sim Info",
                   JOptionPane.INFORMATION_MESSAGE);
         public class DemoJPanel extends JPanel {
              //Do your paint stuff here!
              public DemoJPanel() {
                   setDoubleBuffered(true);
              public void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   if(!isStarted) {
                        g.drawImage(imageBg.getImage(), 0, 0, this);
                   } else {
                        g.drawImage(imageDiagram.getImage(), 0, 0, this);
                        g.drawString("Time: " + nTimer, 700, 370);
                        g.setXORMode(Color.black); //this lets me see through the image
                                                           //but doesn't let me interact with it.
                        for(int i=0; i<64; i++) {
                             if(memory.memory[i] != -1)
                                  g.setColor(new Color(128,47,249));
                             else
                                  g.setColor(new Color(0,0,0));
                             g.fill3DRect(655,28+(i*4)+i,125,4,true);
         /** JetTheme class to change the color of the L&F of the Metal theme.
    public static class JetTheme extends DefaultMetalTheme {
    /** Method to return the theme name.
    public String getName() { return( "Jet" ); }
    private final ColorUIResource primary1 =
    new ColorUIResource(80,80,80);
    private final ColorUIResource primary2 =
    new ColorUIResource(90,90,90);
    private final ColorUIResource primary3 =
    new ColorUIResource(50,50,50);
    private final ColorUIResource secondary1 =
    new ColorUIResource(0,210,0);
    private final ColorUIResource secondary2 =
    new ColorUIResource(0,140,0);
    private final ColorUIResource secondary3 =
    new ColorUIResource(0,0,0);
    private final ColorUIResource black =
    new ColorUIResource(0,255,0);
    private final ColorUIResource white =
    new ColorUIResource(0,0,0);
              protected ColorUIResource getPrimary1() { return( primary1 ); }
              protected ColorUIResource getPrimary2() { return( primary2 ); }
              protected ColorUIResource getPrimary3() { return( primary3 ); }
              protected ColorUIResource getSecondary1() { return( secondary1 ); }
              protected ColorUIResource getSecondary2() { return( secondary2 ); }
              protected ColorUIResource getSecondary3() { return( secondary3 ); }
              protected ColorUIResource getBlack() { return( black ); }
              protected ColorUIResource getWhite() { return( white ); }

    This is how I paint a background image:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=316074

  • 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

  • How to prevent scrolling if you have two Jpanels in a JScrollPane

    I have a JScrollPane with a JPanel for Linenumbers and one for a JTextArea,
    each time you have a new line in the JTextarea the propertyListenerEvent call a Method that sets the LineNumbers in the JPanel for Linenumbers, but then you get an unwanted behaviour of the scrollbar: The Scrollbar scrolls down to the last Line. (e.g. if youre writing in the first Line - LineNumber update after pressing return, set's the view to the last Line e.g. 200 - the caret/cursor is on the second) I tried to set the Linenumber Panel not focusable, but it doesn't work. Does anyone got a hint for me?

    Thanks for the answers.
    @itchyscratchy: didn't get it working with that workarround. but thanks a lot :)
    camickr: Since we can't see your code, we can't suggest what you might be doing wrong.I better kick my idea... thought it could be possible like: when
    LnNums=false after setLineNum Call in jTPaneCaretUpdate!?
    * LineNumberTest.java
    * Created on 12. Dezember 2006, 23:40
    public class LineNumberTest extends javax.swing.JFrame
        /** Creates new form LineNumberTest */
        public LineNumberTest()
            initComponents();
       // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents()
        jScrollPane1 = new javax.swing.JScrollPane();
            jPanel1 = new javax.swing.JPanel();
            jTxtArea1 = new javax.swing.JTextArea();
            jTLineNums = new javax.swing.JTextArea();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
           jPanel1.setLayout(new java.awt.BorderLayout());
            jTxtArea1.addCaretListener(new javax.swing.event.CaretListener() {
                public void caretUpdate(javax.swing.event.CaretEvent evt) 
                    jTxtArea1CaretUpdate(evt);
            jPanel1.add(jTxtArea1, java.awt.BorderLayout.CENTER);
            jTLineNums.setBackground(javax.swing.UIManager.getDefaults().getColor("TextField.disabledBackground"));
            jTLineNums.setEditable(false);
            jPanel1.add(jTLineNums, java.awt.BorderLayout.WEST);
            jScrollPane1.setViewportView(jPanel1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
        // </editor-fold>
        private void jTxtArea1CaretUpdate(javax.swing.event.CaretEvent evt)
            //Caret
            ci = jTxtArea1.getCaretPosition();
            String sc;
            sc = Integer.toString(ci);
            String s = "0";
            sli=jTxtArea1.getLineCount();
            s = Integer.toString(sli);
            if(LnNums) {
                setLineNums();
               //LnNums =false;
             private void setLineNums()
            jTLineNums.setText("");
            //jTLNums.setFont (new Font (fName, Font.PLAIN, fSize));
            for (int i = 1; i <= sli; i++) {
                jTLineNums.append(i+" \r\n");
            //setFoc ();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new LineNumberTest().setVisible(true);
        public javax.swing.JPanel jPanel1;
        public javax.swing.JScrollPane jScrollPane1;
        public javax.swing.JTextArea jTLineNums;
        public javax.swing.JTextArea jTxtArea1;
        boolean LnNums = true;
        int iLnNums, iSymBar, iCodeBar, iInv, sli, ci;
    }

  • Getting Autoscroll Interface to work with JScrollPane/JPanel

    I got drag and drop working with a JPanel extended class.
    JScrollPane -> JPanel
    My JPanel is a DropTarget. I want the viewable portion on that JPanel to have an Insets object associated with it. How would I do that?
    I originally associated the Insets object with the JPanel. Problem was that a lot of the JPanel can be obscured. So if the top is hidden it doesn't realize it is at the edge. I tried associating an Insets object with the JScrollPane and with the JScrollPane's JViewport with limited success. But I ran into similar errors. I may be on the right track with some of this. Not sure.
    I would appreciate any help if anyone has done this before.
    Regardless of the ways I am attempting, if you had a JScrollPane with a JPanel (and the JPanel was your DropTarget), how would you implement the autoscrolling? Esp. in regards to the Insets object?
    regards,
    Geoff Robinson

    The following code will autoscroll almost any drop target, not sure what insets you are talking about though.
        static int autoscrollMargin = 20;
        Insets autoscrollInsets = new Insets(0, 0, 0, 0);
        // AutoScroll methods.
        public void autoscroll(Point location)
            //System.out.println("mouse at " + location);
            int top = 0, left = 0, bottom = 0, right = 0;
            Dimension size = getSize();
            Rectangle rect = getVisibleRect();
            int bottomEdge = rect.y + rect.height;
            int rightEdge = rect.x + rect.width;
            if (location.y - rect.y <= autoscrollMargin && rect.y > 0) top = autoscrollMargin;
            if (location.x - rect.x <= autoscrollMargin && rect.x > 0) left = autoscrollMargin;
            if (bottomEdge - location.y <= autoscrollMargin && bottomEdge < size.height) bottom = autoscrollMargin;
            if (rightEdge - location.x <= autoscrollMargin && rightEdge < size.width) right = autoscrollMargin;
            rect.x += right - left;
            rect.y += bottom - top;
            scrollRectToVisible(rect);
        public Insets getAutoscrollInsets()
            Dimension size = getSize();
            Rectangle rect = getVisibleRect();
            autoscrollInsets.top = rect.y + autoscrollMargin;
            autoscrollInsets.left = rect.x + autoscrollMargin;
            autoscrollInsets.bottom = size.height - (rect.y + rect.height) + autoscrollMargin;
            autoscrollInsets.right = size.width - (rect.x + rect.width) + autoscrollMargin;
            return autoscrollInsets;
        }

  • 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

  • JSplitPane, JScrollPane, JPanel & resize

    My program has 2 nested JSplitpanes, that divide the screen in 4 parts like a cross.
    I added a JScrollPane to one of the quaters and added a JPanel to the JScrollPane. The JPanel uses a CardLayout since I want to switch the components that I show there.
    One of the components I show on the JPanel is a JTree. If I expand the tree the panel becomes scrollable to show the whole tree. This is what I want because I want to be able to view the whole tree.
    The problem is, that if I switch to another component on the panel the panel stays that large even though I just want it to have the visible size
    This is how the panel looks like before switching to the tree and expanding it:
    http://img272.imageshack.us/img272/8695/noscroll3zj.jpg
    This is how the panel looks like after switching to the tree, expanding it and switching back:
    http://img272.imageshack.us/img272/6690/scroll3ef.jpg
    I want to restore the panel to its initial state but I cannot figure out how. Please help.

    If I add a panel to the split pane (to make it card layout) I can't use it for scrolling anymoreThis simple example works for me:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SplitPaneCard extends JFrame
         JSplitPane splitPane;
         JPanel cards;
         public SplitPaneCard()
              splitPane = new JSplitPane();
              getContentPane().add(splitPane, BorderLayout.CENTER);
              JTextArea textArea1 = new JTextArea(5, 10);
              textArea1.setText("1\n2\n3\n4\n5\n6\n7");
              textArea1.setForeground( Color.RED );
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              JTextArea textArea2 = new JTextArea(5, 10);
              textArea2.setText("1234567");
              textArea2.setForeground( Color.BLUE );
              JScrollPane scrollPane2 = new JScrollPane( textArea2 );
            cards = new JPanel( new CardLayout() );
            cards.add(scrollPane1, "red");
            cards.add(scrollPane2, "blue");
            splitPane.setRightComponent( cards );
              JPanel buttonPanel = new JPanel();
              getContentPane().add(buttonPanel, BorderLayout.SOUTH);
              JButton red = new JButton("Show Red Text Area");
              red.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "red");
              buttonPanel.add(red);
              JButton blue = new JButton("Show Blue Text Area");
              blue.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "blue");
              buttonPanel.add(blue);
         public static void main(String[] args)
              final SplitPaneCard frame = new SplitPaneCard();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • How to pass/share components between different JPanels/Container

    Dear Friends,
    I know here a lot Java Guru, I met a problem below.
    How can I pass components between different JPanels??
    here, ListPanelMain.java is main,
    When I click a tree node in splitPane, I can see all its children on the right splitpane, but I hope they can be seen on another Panel called "ListRightPane.java"
    How to do it??
    Why cannot pass??
    [1]. main Program:
    package swing.com.test.test;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import java.io.Serializable;
    import swing.com.test.test.ListPanel;
    import java.awt.GridLayout;
    public class ListPanelMain implements java.io.Serializable{
         private JFrame frame;
         * Launch the application
         * @param args
         public static void main(String args[]) {
              try {
                   ListPanelMain window = new ListPanelMain();
                   window.frame.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         * Create the application
         public ListPanelMain() {
              initialize();
         * Initialize the contents of the frame
         private void initialize() {
              frame = new JFrame("FileTreePanelMain");
              frame.setBounds(100, 100, 900, 675);
         //     FieTreePanelComm      ftreecomm                = new      FieTreePanelComm();
              ListPanel                ftree                     = new      ListPanel("C:\\");
    //          ListAllFile           ftree                     = new      ListAllFile("C:\\");
         //     FileTreePanelText      fileTreePanelText      = new      FileTreePanelText(ftreecomm);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final JPanel panel = new JPanel();
              panel.setLayout(new GridLayout(0, 2));
              frame.getContentPane().add(panel, BorderLayout.CENTER);
         //     final JSplitPane splitPane = new JSplitPane();
         //     frame.getContentPane().add(splitPane, BorderLayout.CENTER);
         //     splitPane.setLeftComponent(ftree);
              panel.add(ftree);
              final ListRightPanel listRightPanel = new ListRightPanel(ftree);
              //splitPane.setRightComponent(listRightPanel);
              panel.add(listRightPanel);
         frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
         System.exit(0);
         frame.pack();
         frame.setVisible(true);
    [2]. Program 2:
    package swing.com.test.test;
    //File System Tree
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.io.File;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListPanel extends JPanel implements Serializable{
    protected JTree fileTree;
    private FileSystemModel fileSystemModel;
    private JTextArea ltextArea = new JTextArea();
    protected JTextArea fileDetailsTextArea = new JTextArea();
    private String str = "";
         public String getlTextArea() {
                   //textArea.getText();
                   return str;
         public String setlTextArea(String ta) {
                   ltextArea.setText(ta);
                   str = ta;
                   return str;
    public ListPanel(String directory) {
    //super("JTree FileSystem Viewer");
                   setLayout(new BorderLayout());
                   final JPanel panel = new JPanel();
                   panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
    fileDetailsTextArea.setEditable(false);
    fileSystemModel = new FileSystemModel(new File(directory));
    fileTree = new JTree(fileSystemModel);
    fileTree.setEditable(true);
    fileTree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent event) {
    System.out.println("1. What we save is: getlTextArea() =" + getlTextArea() );
    File file = (File) fileTree.getLastSelectedPathComponent();
    fileDetailsTextArea.setText(getFileDetails(file));
    final ListRightPanel lrp = new ListRightPanel(this);
    lrp.textArea.setText(getFileDetails(file));
    setlTextArea(getFileDetails(file));
    System.out.println("2. What we save is: getlTextArea() =" + getlTextArea() );
              final JSplitPane splitPane = new JSplitPane();
              panel.add(splitPane, BorderLayout.CENTER);
              final JPanel panel_1 = new JPanel();
              splitPane.setLeftComponent(panel_1);
              panel_1.add(new JScrollPane(fileTree));
              final JPanel panel_2 = new JPanel();
              splitPane.setRightComponent(panel_2);
              panel_2.add(new JScrollPane(fileDetailsTextArea));
    setVisible(true);
    private String getFileDetails(File file) {
    if (file == null)
    return "";
    StringBuffer buffer = new StringBuffer();
    if (file.listFiles()!=null){
         for (int i=0; i< file.listFiles().length; i++){
         buffer.append(((file.listFiles())) + "\n");
         System.out.println("List all files");
    return buffer.toString();
    public static void main(String args[]) {
    new ListPanel("c:\\");
    class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
    public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
    String[] fileList = file.list();
    if (fileList != null)
    return file.list().length;
    return 0;
    public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
    public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
    if (file.getName().equals(children[i])) {
    return i;
    return -1;
    public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
    listener = (TreeModelListener) iterator.next();
    listener.treeNodesChanged(event);
    public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
    public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
    private class TreeFile extends File {
    public TreeFile(File parent, String child) {
    super(parent, child);
    public String toString() {
    return getName();
    [3]. Program 3:
    package swing.com.test.test;
    import java.awt.BorderLayout;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListRightPanel extends JPanel implements TreeSelectionListener, Serializable{
         protected JTextArea textArea;
    //     protected ListAllFile laf;
    private String str = "";
              public String getlTextArea() {
                        //textArea.getText();
                        return str;
              public String setlTextArea(String ta) {
                        str = ta;
                        return str;
         * Create the panel
         public ListRightPanel(ListPanel laff) {
              super();
              setLayout(new BorderLayout());
              final JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
              textArea = new JTextArea();
    final String st = laff.getlTextArea();
    System.out.println("####################################");
    System.out.println("st=" + st);
         laff.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent event) {
         //laff.textArea.setText(getFileDetails(file));
              textArea.setText(getlTextArea());
         System.out.println("ListRightPanel Was Invoked from ListPanel!!getlTextArea() =" + getlTextArea() );
         System.out.println("st=" + st);
              panel.add(textArea, BorderLayout.CENTER);
         public void valueChanged(TreeSelectionEvent e){};
    It is runnable program, just compile and run it in Console is ok,
    Regards
    Sunny

    Thnaks, code post again, see
    [1]. package swing.com.test.test;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import java.io.Serializable;
    import swing.com.test.test.ListPanel;
    import java.awt.GridLayout;
    public class ListPanelMain implements java.io.Serializable{
         private JFrame frame;
          * Launch the application
          * @param args
         public static void main(String args[]) {
              try {
                   ListPanelMain window = new ListPanelMain();
                   window.frame.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
          * Create the application
         public ListPanelMain() {
              initialize();
          * Initialize the contents of the frame
         private void initialize() {
              frame = new JFrame("FileTreePanelMain");
              frame.setBounds(100, 100, 900, 675);
         //     FieTreePanelComm      ftreecomm                = new       FieTreePanelComm();
              ListPanel                 ftree                     = new      ListPanel("C:\\");
    //          ListAllFile            ftree                     = new      ListAllFile("C:\\");
         //     FileTreePanelText      fileTreePanelText      = new      FileTreePanelText(ftreecomm);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final JPanel panel = new JPanel();
              panel.setLayout(new GridLayout(0, 2));
              frame.getContentPane().add(panel, BorderLayout.CENTER);
         //     final JSplitPane splitPane = new JSplitPane();
         //     frame.getContentPane().add(splitPane, BorderLayout.CENTER);
         //     splitPane.setLeftComponent(ftree);
              panel.add(ftree);
              final ListRightPanel listRightPanel = new ListRightPanel(ftree);
              //splitPane.setRightComponent(listRightPanel);
              panel.add(listRightPanel);
                frame.addWindowListener(new WindowAdapter() {
                     public void windowClosing(WindowEvent e) {
                         System.exit(0);
                 frame.pack();
                 frame.setVisible(true);
    }[2] Program 2
    package swing.com.test.test;
    //File System Tree
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.io.File;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListPanel extends JPanel implements Serializable{
      protected JTree fileTree;
      private FileSystemModel fileSystemModel;
      private JTextArea ltextArea = new JTextArea();
      protected JTextArea fileDetailsTextArea = new JTextArea();
      private String str = "";
         public  String getlTextArea()  {
                   //textArea.getText();
                      return str;
         public  String setlTextArea(String ta)  {
                   ltextArea.setText(ta);
                   str = ta;
                      return str;
      public ListPanel(String directory) {
        //super("JTree FileSystem Viewer");
                   setLayout(new BorderLayout());
                   final JPanel panel = new JPanel();
                   panel.setLayout(new BorderLayout());
                  add(panel, BorderLayout.CENTER);
        fileDetailsTextArea.setEditable(false);
        fileSystemModel = new FileSystemModel(new File(directory));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(true);
        fileTree.addTreeSelectionListener(new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent event) {
            System.out.println("1. What we save is: getlTextArea() =" + getlTextArea() );
            File file = (File) fileTree.getLastSelectedPathComponent();
            fileDetailsTextArea.setText(getFileDetails(file));
            final ListRightPanel lrp = new ListRightPanel(this);
            lrp.textArea.setText(getFileDetails(file));
            setlTextArea(getFileDetails(file));
            System.out.println("2. What we save is: getlTextArea() =" + getlTextArea() );
              final JSplitPane splitPane = new JSplitPane();
              panel.add(splitPane, BorderLayout.CENTER);
              final JPanel panel_1 = new JPanel();
              splitPane.setLeftComponent(panel_1);
              panel_1.add(new JScrollPane(fileTree));
              final JPanel panel_2 = new JPanel();
              splitPane.setRightComponent(panel_2);
              panel_2.add(new JScrollPane(fileDetailsTextArea));
        setVisible(true);
      private String getFileDetails(File file) {
        if (file == null)
          return "";
        StringBuffer buffer = new StringBuffer();
        if (file.listFiles()!=null){
             for (int i=0; i< file.listFiles().length; i++){
             buffer.append(((file.listFiles())) + "\n");
         System.out.println("List all files");
    return buffer.toString();
    public static void main(String args[]) {
    new ListPanel("c:\\");
    class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
    public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
    String[] fileList = file.list();
    if (fileList != null)
    return file.list().length;
    return 0;
    public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
    public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
    if (file.getName().equals(children[i])) {
    return i;
    return -1;
    public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
    listener = (TreeModelListener) iterator.next();
    listener.treeNodesChanged(event);
    public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
    public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
    private class TreeFile extends File {
    public TreeFile(File parent, String child) {
    super(parent, child);
    public String toString() {
    return getName();
    [3] Program 3:
    package swing.com.test.test;
    import java.awt.BorderLayout;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListRightPanel extends JPanel implements TreeSelectionListener, Serializable{
         protected JTextArea textArea;
    //     protected ListAllFile  laf;
        private String str = "";
              public  String getlTextArea()  {
                        //textArea.getText();
                           return str;
              public  String setlTextArea(String ta)  {
                        str = ta;
                           return str;
          * Create the panel
         public ListRightPanel(ListPanel  laff) {
              super();
              setLayout(new BorderLayout());
              final JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
              textArea = new JTextArea();
            final String st = laff.getlTextArea();
            System.out.println("####################################");
            System.out.println("st=" + st);
             laff.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
                 public void valueChanged(TreeSelectionEvent event) {
                   //laff.textArea.setText(getFileDetails(file));
                      textArea.setText(getlTextArea());
                     System.out.println("ListRightPanel Was Invoked from ListPanel!!getlTextArea() =" + getlTextArea() );
                     System.out.println("st=" + st);
              panel.add(textArea, BorderLayout.CENTER);
           public void valueChanged(TreeSelectionEvent e){};
    }You can try this one, thanks again
    sunny

  • How to collect JScrollPanes into a Container variable? (urgent...)

    Please help me in following problem:
    I can collect succesfully one JScrollPane into a Container variable allComponents and then show this Container in application window. However, I would like to collect several JScrollPanes into this same Container variable but it does not work. Should I use some kind of add command?
    I tried something like
    allComponents.add(jspane);
    but I got error code "variable allComponents might not have been initialized" allthough I have tried my best to initialize it.
    Thanks for your kind help!
    Snippets from my program:
    class SwingApplication implements ActionListener
    public Container createComponents()
    Container allComponents;
    jspane = new JScrollPane(panel);
    jspane2 = new JScrollPane(cards);
    allComponents = jspane; // THIS WORKS BUT I WOULD LIKE TO COLLECT BOTH jspane AND jspane2 WITH ADD COMMAND
    return allComponents;
    class DragImage
    { public static void main(String[] args)
    JFrame frame = new JFrame("SwingApplication");
    SwingApplication app = new SwingApplication();
    Container contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);
    Message was edited by:
    wonderful123

    THanks for your interest!!
    Perhaps I give the whole source code
    The problem lies in the following place:
    allComponents = jspane;
    return allComponents;
    I would like to use some kind of command
    allComponents.add(jspane);
    but it does not seem to work. I get the error "variable allComponents might not be initialized".
    The program should print images in two rows. With my current knowledge i can only print one row of images.
    Thanks!
    import java.awt.*;
        import java.awt.event.*;
        import java.awt.datatransfer.*;
        import javax.swing.*;
    class SwingApplication implements ActionListener
                                            // extends JScrollPane
       private JScrollPane jspane;
       private JScrollPane jspane_n;
       private JPanel panel;
       private JLabel label;
       private Icon icon;
       private JPanel panel2;
       private JLabel label2;
       private Icon icon2;
       private JPanel panel_n;
       private JLabel label_n;
       private Icon icon_n;
       private JTextField testText;
       private int k;
        private static String labelPrefix = "Testing: ";
        private int numClicks = 0;
        final JLabel label_testing = new JLabel(labelPrefix + "nothing");
    JPanel cards; //a panel that uses CardLayout
        final String BUTTONPANEL = "JPanel with JButtons";
        final String TEXTPANEL = "JPanel with JTextField";
       public Container createComponents()
    Container allComponents;
         icon = new ImageIcon("kirjain_a.gif");
         label = new JLabel();
         label.setIcon(icon);
         icon2 = new ImageIcon("kirjain_b.gif");
         label2 = new JLabel();
         label2.setIcon(icon2);
         icon_n = new ImageIcon("numero_1.gif");
         label_n = new JLabel();
         label_n.setIcon(icon_n);
    label.setTransferHandler(new ImageSelection());              
    label2.setTransferHandler(new ImageSelection());
    label_n.setTransferHandler(new ImageSelection());
            MouseListener mouseListener = new MouseAdapter() {
              public void mousePressed(MouseEvent e) {
    JComponent sourceEvent = (JComponent)e.getSource();
    // Object sourceEvent = whatHappened.getSource();
    if (sourceEvent == label)
        { numClicks++;
            label_testing.setText(labelPrefix + numClicks);
    if (sourceEvent == label2)
    numClicks--;
            label_testing.setText(labelPrefix + numClicks);
                JComponent comp = (JComponent)e.getSource();
                TransferHandler handler = comp.getTransferHandler();
                handler.exportAsDrag(comp, e, TransferHandler.COPY);
           label.addMouseListener(mouseListener);
           label2.addMouseListener(mouseListener);  
           label_n.addMouseListener(mouseListener);  
         panel = new JPanel();
    // panel.setLayout(new GridLayout(1,3));
         panel.add(label);
         panel.add(label2);
         panel_n = new JPanel();
         panel_n.add(label_n);
    //Create the panel that contains the "cards".
            cards = new JPanel(new CardLayout());
            cards.add(panel_n, BUTTONPANEL);
            cards.add(panel_n, TEXTPANEL);
         panel.add(label_testing);
          jspane = new JScrollPane(panel);
          jspane_n = new JScrollPane(cards);
      //   jspane.setLayout(new GridLayout(3,2));      
      //   jspane.getViewport().add(panel);
      //   jspane_n.getViewport().add(cards);
      //    allComponents.add(panel, BorderLayout.PAGE_START);
      //    allComponents.add(cards, BorderLayout.CENTER);
      //     allComponents.add(jspane);
      //     allComponents.add(jspane_n);
         allComponents = jspane;
         return allComponents;
                                           //     label.addActionListener(this);
                                           //     k=0;
    public void actionPerformed(ActionEvent whatHappened)
      { Object sourceEvent = whatHappened.getSource();
        if (sourceEvent == label)
        { numClicks++;
            label_testing.setText(labelPrefix + numClicks);
    //    repaint();
    } // end class OwnPanel
    class CloserClass extends WindowAdapter
    { public void windowClosing(WindowEvent e)
       { System.exit(0);
    class DragImage
    { public static void main(String[] args)
           JFrame frame = new JFrame("SwingApplication");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            SwingApplication app = new SwingApplication();
            Container contents = app.createComponents();
            frame.getContentPane().add(contents, BorderLayout.CENTER);
            //Display the window.
    //    addWindowListener(new CloserClass());
            frame.pack();
            frame.setVisible(true);
        } // end class DragImage

  • URGENT! Need help with scrolling on a JPanel!

    Hello Guys! I guess there has been many postings about this subject in the forum, but the postings I found there.... still couldn't solve my problem...
    So, straight to the problem:
    I am drawing some primitive graphic on a JPanel. This JPanel is then placed in a JScrollPane. When running the code, the scrollbars are showing and the graphic is painted nicely. But when I try to scroll to see the parts of the graphics not visible in the current scrollbarview, nothing else than some flickering is happening... No movement what so ever...
    What on earth must I do to activate the scroll functionality on my JPanel??? Please Help!
    And yes, I have tried implementing the 'Scrollable' interface... But it did not make any difference...
    Code snippets:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class FilterComp extends JPanel {//implements Scrollable {
      protected DefaultMutableTreeNode root;
      protected Image buffer;
      protected int lastW = 0;
      protected int origoX = 0;
      protected final StringBuffer sb = new StringBuffer();
    //  protected int maxUnitIncrement = 1;
      protected JScrollPane scrollpane = new JScrollPane();
       *  Constructor for the FilterComp object
       *@param  scrollpane  Description of the Parameter
      public FilterComp(JScrollPane scrollpane) {
        super();
    //    setPreferredSize(new Dimension(1000, 500));
        this.setBackground(Color.magenta);
    //    setOpaque(false);
        setLayout(
          new BorderLayout() {
            public Dimension preferredLayoutSize(Container cont) {
              return new Dimension(1000, 600);
        this.scrollpane = scrollpane;
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollpane.setPreferredSize( new Dimension( 500, 500 ) );
        scrollpane.getViewport().add( this, null );
    //    scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        repaint();
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = getSize().width;
        if (w != lastW) {
          buffer = null;
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (root != null) {
          int h = getHeight(root);
          if (buffer == null) {
            buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g3 = (Graphics2D) buffer.getGraphics();
            g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g3.setColor(Color.black);
            g3.setStroke(new BasicStroke(2));
            paint(g3, (w / 2) + origoX, 10, w / 2, root); 
          lastW = w;
          AffineTransform old = g2.getTransform();
          AffineTransform trans = new AffineTransform();
          trans.translate((w / 2) + origoX, (getHeight() - (h * 40)) / 2);
          g2.setTransform(trans);
          g2.drawImage(buffer, (-w / 2) + origoX, 0, null);
          g2.setTransform(old);
        updateUI();
       *  Description of the Method
       *@param  g  Description of the Parameter
      public void update(Graphics g) {
        // Call paint to reduce flickering
        paint(g);
       *  Description of the Method
       *@param  g2    Description of the Parameter
       *@param  x     Description of the Parameter
       *@param  y     Description of the Parameter
       *@param  w     Description of the Parameter
       *@param  node  Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, int w, DefaultMutableTreeNode node) {
        if (node.getChildCount() == 2) {
          DefaultMutableTreeNode c1 = (DefaultMutableTreeNode) node.getChildAt(0);
          DefaultMutableTreeNode c2 = (DefaultMutableTreeNode) node.getChildAt(1);
          if (c1.getChildCount() == 0 && c2.getChildCount() == 0) {
            String s = c1.getUserObject().toString() + " " + node.getUserObject() + " " + c2.getUserObject();
            paint(g2, x, y, s);
          } else {
            g2.drawLine(x - (w / 2), y, x + (w / 2), y);
            Font f = g2.getFont();
            g2.setFont(new Font(f.getName(), Font.BOLD | Font.ITALIC, f.getSize() + 2));
            paint(g2, x, y, node.getUserObject().toString());
            g2.setFont(f);
            g2.drawLine(x - (w / 2), y, x - (w / 2), y + 40);
            g2.drawLine(x + (w / 2), y, x + (w / 2), y + 40);
            paint(g2, x - (w / 2), y + 40, w / 2, c1);
            paint(g2, x + (w / 2), y + 40, w / 2, c2);
        } else if (node.getChildCount() == 0) {
          paint(g2, x, y, node.getUserObject().toString());
       *  Description of the Method
       *@param  g2  Description of the Parameter
       *@param  x   Description of the Parameter
       *@param  y   Description of the Parameter
       *@param  s   Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, String s) {
        y += 10;
        StringTokenizer st = new StringTokenizer(s, "\\", false);
        if (s.indexOf("'") != -1 && st.countTokens() > 1) {
          int sh = g2.getFontMetrics().getHeight();
          while (st.hasMoreTokens()) {
            String t = st.nextToken();
            if (st.hasMoreTokens()) {
              t += "/";
            int sw = g2.getFontMetrics().stringWidth(t);
            g2.drawString(t, x - (sw / 2), y);
            y += sh;
        } else {
          int sw = g2.getFontMetrics().stringWidth(s);
          g2.drawString(s, x - (sw / 2), y);
       *  Sets the root attribute of the FilterComp object
       *@param  root  The new root value
      public void setRoot(DefaultMutableTreeNode root) {
        this.root = root;
        buffer = null;
       *  Gets the root attribute of the FilterComp object
       *@return    The root value
      public DefaultMutableTreeNode getRoot() {
        return root;
       *  Gets the height attribute of the FilterComp object
       *@param  t  Description of the Parameter
       *@return    The height value
      private int getHeight(TreeNode t) {
        int h = 1;
        int c = t.getChildCount();
        if (c > 0) {
          if (c > 1) {
            h += Math.max(getHeight(t.getChildAt(0)), getHeight(t.getChildAt(1)));
          } else {
            h += getHeight(t.getChildAt(0));
        return h;
       *  Sets the x attribute of the FilterComp object
       *@param  x  The new x value
      public void setX(int x) {
        origoX = x;
       *  Gets the x attribute of the FilterComp object
       *@return    The x value
      public int getX() {
        return origoX;
       *  Gets the preferredScrollableViewportSize attribute of the FilterComp
       *  object
       *@return    The preferredScrollableViewportSize value
    //  public Dimension getPreferredScrollableViewportSize() {
    //    return getPreferredSize();
       *  Gets the scrollableBlockIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableBlockIncrement value
    //  public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
       *  Gets the scrollableTracksViewportHeight attribute of the FilterComp object
       *@return    The scrollableTracksViewportHeight value
    //  public boolean getScrollableTracksViewportHeight() {
    //    return false;
       *  Gets the scrollableTracksViewportWidth attribute of the FilterComp object
       *@return    The scrollableTracksViewportWidth value
    //  public boolean getScrollableTracksViewportWidth() {
    //    return false;
       *  Gets the scrollableUnitIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableUnitIncrement value
    //  public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
    }

    The Scrollable interface should be implemented by a JPanel set as the JScrollPane's viewport or scrolling may not function. Although it is said to be only necessary for tables, lists, and trees, without it I have never had success with images. Even the Java Swing Tutorial on scrolling images with JScrollPane uses the Scrollable interface.
    I donot know what you are doing wrong here, but I use JScrollPane with a JPanel implementing Scrollable interface and it works very well scrolling images drawn into the JPanel.
    You can scroll using other components, such as the JScrollBar or even by using a MouseListener/MouseMotionListener combination, but this is all done behind the scenes with the use of JScrollPane/Scrollable combination.
    You could try this approach using an ImageIcon within a JLabel:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test extends JFrame {
         BufferedImage bi;
         Graphics2D g_bi;
         public Test() {
              super("Scroll Test");
              makeImage();
              Container contentPane = getContentPane();
              MyView view = new MyView(new ImageIcon(bi));
              JScrollPane sp = new JScrollPane(view);
              contentPane.add(sp);
              setSize(200, 200);
              setVisible(true);
         private void makeImage() {
              bi = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
              g_bi = bi.createGraphics();
              g_bi.setColor(Color.white);
              g_bi.fillRect(0,0,320,240);
              g_bi.setColor(Color.black);
              g_bi.drawLine(0,0,320,240);
         public static void main(String args[]) {
              Test test = new Test();
    class MyView extends JLabel {
         ImageIcon icon;
         public MyView(ImageIcon ii) {
              super(ii);
              icon = ii;
         public void paintComponent(Graphics g) {
              g.drawImage(icon.getImage(),0,0,this);
    }Robert Templeton

  • Install Application - TextArea inside JScrollPane

    I've been working on an install application to install another one of my programs (next/accept/next/ finish type of thing) and had a couple questions and would appreciate any help anyone can give.
    Some Background info:
    I made images and have them display as image icons through jlabels for the buttons and background. The labels have classes applying various mouselisteners (Mousepressed, MouseEntered, MouseExited, etc) changing the images and moving from screen to screen. I have my layout set to null, not for any particular reason, but because I have no formal education in layout managers.
    1) Is there a conical solution to moving through various windows? That is, right now I move through the various 'screens' with a check on an int called state, that gets incremented and decremented through forward and back buttons. I looked at some code given to us on a test by our teacher (we had to find bugs) and saw that he had implemented a fake "state" interface, with constants like "Account_State" to control where you were in the program. This seems a bit easier to read than ints, but is there a correct built in version of his states?
    2) On the second screen I have a license agreement (actually required for the application that gets installed), and a checkbox. The license is held inside of a JTextArea(scroll) inside a JScrollPane(textscroll). The JScrollPane is extending in weird ways. The following is a stripped down version of my code (it runs and demonstrates the problem):
    InstalleApp
    import javax.swing.*;
    import java.awt.*;
    public class InstalleApp {
        public static void main(String args[]) {
            InstalleFrame m = new InstalleFrame();
               Container content = m.getContentPane();
            m.setDefaultCloseOperation(3);
            m.setSize(550, 400);
            m.setUndecorated(true);
            m.setVisible(true);
            m.setTitle("Install");
    }InstalleFrame
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.Rectangle;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.util.*;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import java.awt.event.ActionEvent;
    import javax.swing.text.BadLocationException;
    import javax.swing.JSlider;
    import java.awt.Dimension;
    public class InstalleFrame
        extends JFrame implements ActionListener {
      public InstalleFrame() {
        try {
          jbInit();
        catch (Exception ex) {
          ex.printStackTrace();
      public void actionPerformed(ActionEvent e) {
      JScrollPane textscroll;
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(null);
        this.getContentPane().setBackground(UIManager.getColor("window"));
        background.setBounds(new Rectangle(0, 0, 550, 400));
        readcheck.setOpaque(false);
        readcheck.setText("I have read and accept the license agreement");
        readcheck.setBounds(new Rectangle(31, 357, 319, 32));
        scroll.setWrapStyleWord(true);
        scroll.setLineWrap(true);
        scroll.setText(
            "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this " +
            "software (or any work based on the software) you shall be deemed " +
            "to have accepted the terms and conditions set out below.\n\nGonZor228.com " +
            "(\"GonZor\") is making this software freely available on the basis " +
            "that it is accepted as found and that the user checks its fitness " +
            "for purpose prior to use.\n\nThis software is provided \'as-is\', without " +
            "any express or implied warranties whatsoever. In no event will the " +
            "authors, partners or contributors be held liable for any damages, " +
            "claims or other liabilities direct or indirect, arising from the " +
            "use of this software.\n\nGonZor will from time to time make software " +
            "updates available.  However, GonZor accepts no obligation to provide " +
            "any support to free license holders.\n\nGonZor grants you a limited " +
            "non-exclusive license to use this software for any purpose that does " +
            "not violate any laws that apply to your person in your current jurisdiction, " +
            "subject to the following restrictions: \n\n1. The origin of this software " +
            "must not be misrepresented; you must not claim that you wrote the " +
            "original software.\n2. You must not alter the software, user license " +
            "or installer in any way unless given permission to do so.\n3. This " +
            "notice may not be removed or altered from any distribution.\n4. You " +
            "may not resell or charge for the software.\n5. You may not reverse " +
            "engineer, decompile, disassemble, derive the source code of or modify " +
            "[or create derivative work from] the program without the express " +
            "permission of GonZor.\n6. You must not use this software to engage " +
            "in or allow others to engage in any illegal activity.\n7. You may " +
            "not claim any sponsorship by, endorsement by, or affiliation with " +
            "GonZor228.com\n8. You acknowledge that GonZor owns the copyright and " +
            "all associated intellectual property rights relating to the software.\n\n" +
            " This software license is governed by and construed in accordance " +
            "with the laws of Australia and you agree to submit to the exclusive " +
            "jurisdiction of the Australian courts.\n\nBy clicking the \"I agree\" " +
            "button below, you agree to these software license terms. If you disagree " +
            "with any of the terms below, GonZor does not grant you a license " +
            "to use the software ? exit the window.\n\nYou agree that by your installation " +
            "of the GonZor?s software, you acknowledge that you are at least 18 " +
            "years old, have read this software license, understand it, and agree " +
            "to be bound by its terms.\n\nGonZor reserves the right to update and " +
            "change, from time to time, this software license and all documents " +
            "incorporated by reference. You can always find the most recent version " +
            "of this software license at GonZor228.com.  GonZor may change this " +
            "software license by posting a new version without notice to you. " +
            "Use of the GonZor?s software after such change constitutes acceptance " +
            "of such changes.\n\n1.\tOwnership and Relationship of Parties.\n\nThe " +
            "software is protected by copyrights, trademarks, service marks, international " +
            "treaties, and/or other proprietary rights and laws of the U.S. and " +
            "other countries. You agree to abide by all applicable proprietary " +
            "rights laws and other laws, as well as any additional copyright notices " +
            "or restrictions contained in this software license. GonZor owns all " +
            "rights, titles, and interests in and to the applicable contributions " +
            "to the software. This software license grants you no right, title, " +
            "or interest in any intellectual property owned or licensed by GonZor, " +
            "including (but not limited to) the software, and creates no relationship " +
            "between yourself and GonZor other than that of GonZor to licensee.\n\n" +
            "The software and its components contain software licensed from " +
            "GonZor. The licensor software enables the software to perform certain " +
            "functions including, without limitation, access proprietary data " +
            "on third-party data servers as well as GonZor?s own server. You agree " +
            "that you will use the software, and any data accessed through the " +
            "software, for your own personal non-commercial use only. You agree " +
            "not to assign, copy, transfer, or transmit the software, or any data " +
            "obtained through the software, to any third party. Your license to " +
            "use the software, its components, and any third-party data, will " +
            "terminate if you violate these restrictions. If your license terminates, " +
            "you agree to cease any and all use of the software, its components, " +
            "and any third-party data. All rights in any third-party data, any " +
            "third-party software, and any third-party data servers, including " +
            "all ownership rights are reserved and remain with the respective " +
            "third parties. You agree that these third parties may enforce their " +
            "rights under this Agreement against you directly in their own name.\n\n" +
            "2.\tSupport and Software Updates.\n\nGonZor may elect to provide " +
            "you with customer support and/or software upgrades, enhancements, " +
            "or modifications for the software (collectively, \"Support\"), in its " +
            "sole discretion, and may terminate such Support at any time without " +
            "notice to you. GonZor may change, suspend, or discontinue any aspect " +
            "of the software at any time, including the availability of any software " +
            "feature, database, or content. GonZor may also impose limits on certain " +
            "features and services or restrict your access to parts or all of " +
            "the software or the GonZor228.com web site without notice or liability.\n\n" +
            "3.  \tFees and Payments.\n\nGonZor reserves the right to charge fees " +
            "for future use of or access to the software in GonZor?s sole discretion. " +
            "If GonZor decides to charge for the software, such charges will be " +
            "disclosed to you 28 days before they are applied if such fees will " +
            "affect your use of the product.\n\n4.\tDisclaimer of Warranties by " +
            "GonZor.\n\nUse of the software and any data accessed through the software " +
            "is at your sole risk. They are provided \"as is.\"  Any material or " +
            "service downloaded or otherwise obtained through the use of the software " +
            "(such as the \"plug-in\" feature) is done at your own discretion and " +
            "risk, and you will be solely responsible for any damage to your computer " +
            "system or loss of data that results from the download and/or use " +
            "of any such material or service.  GonZor, its officers, directors, " +
            "employees, contractors, agents, affiliates, assigns, and GonZor?s " +
            "licensors (collectively ?Associates?) do not represent that the software " +
            "or any data accessed there from is appropriate or available for use " +
            "outside the Australia.\n\nThe Associates expressly disclaim all warranties " +
            "of any kind, whether express or implied, relating to the software " +
            "and any data accessed there from, or the accuracy, timeliness, completeness, " +
            "or adequacy of the software and any data accessed there from, including " +
            "the implied warranties of title, merchantability, satisfactory quality, " +
            "fitness for a particular purpose, and non-infringement.\n\nIf the " +
            "software or any data accessed there from proves defective, you (and " +
            "not the Associates) assume the entire cost of all repairs or injury " +
            "of any kind, even if the Associates have been advised of the possibility " +
            "of such a defect or damages. Some jurisdictions do not allow restrictions " +
            "on implied warranties so some of these limitations may not apply " +
            "to you.\n\n5. \tLimitation of liability.\n\nThe Associates will not " +
            "be liable to you for claims and liabilities of any kind arising out " +
            "of or in any way related to the use of the software by yourself or " +
            "by third parties, to the use or non-use of any brokerage firm or " +
            "dealer, or to the sale or purchase of any security, whether such " +
            "claims and liabilities are based on any legal or equitable theory." +
            "\n\nThe Associates are not liable to you for any and all direct, incidental, " +
            "special, indirect, or consequential damages arising out of or related " +
            "to any third-party software, any data accessed through the software, " +
            "your use or inability to use or access the software, or any data " +
            "provided through the software, whether such damage claims are brought " +
            "under any theory of law or equity. Damages excluded by this clause " +
            "include, without limitation, those for loss of business profits, " +
            "injury to person or property, business interruption, loss of business " +
            "or personal information. Some jurisdictions do not allow limitation " +
            "of incidental or consequential damages so this restriction may not " +
            "apply to you.\n\nInformation provided through the software may be " +
            "delayed, inaccurate, or contain errors or omissions, and the Associates " +
            "will have no liability with respect thereto. GonZor may change or " +
            "discontinue any aspect or feature of the software or the use of all " +
            "or any features or technology in the software at any time without " +
            "prior notice to you, including, but not limited to, content, hours " +
            "of availability.\n\n6.  \tControlling Law.\n\nThis software license " +
            "and the relationship between you and GonZor is governed by the laws " +
            "of Australia without regard to its conflict of law provisions. You " +
            "and GonZor agree to submit to the personal and exclusive jurisdiction " +
            "of the courts located within Australia. The United Nations Convention " +
            "on the International Sale of Goods does not apply to this software " +
            "license.\n\n7.\tPrecedence.\n\nThis software license constitutes the " +
            "entire understanding between the parties respecting use of the software, " +
            "superseding all prior agreements between you and GonZor.\n\n8.\tSurviving " +
            "Provisions.\n\nSections 1, and 3 through 5, will survive any termination " +
            "of this Agreement.\n\n---------------------------------------------------------------------------------" +
            "---\nIf you accept the terms of the agreements, click I Agree to continue. " +
            " You must accept the agreement to download and use the software. ");
        scroll.setBounds(new Rectangle(36, 36, 478, 305));
        this.getContentPane().add(readcheck);
        readcheck.setVisible(false);
       this.getContentPane().add(scroll);
       textscroll = new JScrollPane (scroll, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textscroll.setBounds(36,36,400,400);
          getContentPane().add( textscroll );
        this.getContentPane().add(background);
      JLabel background = new JLabel();
      JCheckBox readcheck = new JCheckBox();
      JTextArea scroll = new JTextArea();
    }Sorry about all the text for the agreement. I've tried a number of different things I got from searching the forums at different points in the code (setting the number of rows/columns, setting max and min sizes, etc etc) The code above that wraps the text I could have sworn I tried 3 times before it magically worked... I also tried using the awt component for textareas that had the scrollbars built in, but scrapped it after having even more difficulties with that one. I'm trying to get the textbox to only go down about 300 px and 300 px to the right. Using the graphical editor to change it produces a null pointer error at compile time(?!?). Can anyone help me to get the textbox to render as I want it to?
    Edited by: rpk5000 on Jan 27, 2008 9:43 AM

    for instance, boxlayout would work nicely with the installer frame (or dialog)
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class InstalleFrame
        public InstalleFrame()
            try
                jbInit();
            catch (Exception ex)
                ex.printStackTrace();
        private JScrollPane textscroll;
        private JPanel contentPane = new JPanel();
        private JLabel background = new JLabel();
        private JCheckBox readcheck = new JCheckBox();
        private JTextArea scroll = new JTextArea();
        private void jbInit() throws Exception
            contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
            contentPane.setBackground(UIManager.getColor("window"));
            contentPane.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            scroll.setWrapStyleWord(true);
            scroll.setLineWrap(true);
            String text = "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this "
                            + "software (or any work based on the software) you shall be deemed "
                            + "to have accepted the terms and conditions set out below.\n\nGonZor228.com "
                            + "(\"GonZor\") is making this software freely available on the basis "
                            + "that it is accepted as found and that the user checks its fitness "
                            + "for purpose prior to use.\n\nThis software is provided \'as-is\', without "
                            + "any express or implied warranties whatsoever. In no event will the "
                            + "authors, partners or contributors be held liable for any damages, "
                            + "claims or other liabilities direct or indirect, arising from the "
                            + "use of this software.\n\nGonZor will from time to time make software "
                            + "updates available.  However, GonZor accepts no obligation to provide "
                            + "any support to free license holders.\n\nGonZor grants you a limited "
                            + "non-exclusive license to use this software for any purpose that does "
                            + "not violate any laws that apply to your person in your current jurisdiction, "
                            + "subject to the following restrictions: \n\n\nblah, blah, blah,..."
                            + "\n\n";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 5; i++)
                sb.append(text);
            scroll.setText(sb.toString());
            contentPane.add(readcheck);
            contentPane.add(scroll);
            textscroll = new JScrollPane(scroll,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            textscroll.setPreferredSize(new Dimension(400, 400));
            contentPane.add(textscroll);
            JPanel bottomPane = new JPanel();
            bottomPane.setOpaque(false);
            final JButton okButton = new JButton("OK");
            final JButton cancelButton = new JButton("Cancel");
            okButton.setEnabled(false);
            readcheck.setOpaque(false);
            readcheck.setText("I have read and accept the license agreement");
            readcheck.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JCheckBox radioBtn = (JCheckBox)e.getSource();
                    if (radioBtn.isSelected())
                        okButton.setEnabled(true);                   
                    else
                        okButton.setEnabled(false);
            okButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    // TODO: whatever needs to be done here
            cancelButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    SwingUtilities.getWindowAncestor(contentPane).dispose();
            bottomPane.add(readcheck);
            bottomPane.add(okButton);
            bottomPane.add(cancelButton);
            contentPane.add(bottomPane);
            //readcheck.setVisible(false);
            contentPane.add(background);
        public JPanel getContentPane()
            return contentPane;
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    InstalleFrame install = new InstalleFrame();
                    JFrame frame = new JFrame("Install");
                    frame.getContentPane().add(install.getContentPane());
                    frame.setDefaultCloseOperation(3);
                    frame.setSize(550, 400);
                    frame.setUndecorated(false);  //**
                    frame.pack();  //**
                    frame.setLocationRelativeTo(null); //**
                    frame.setVisible(true);
    }

  • 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

Maybe you are looking for

  • Importing internal table from one program to another program

    Hi everybody, i have one small doubt. i am using submit statement and passing the values from this program to another program selection screen. in that program logic is written.In that program one internal table values are being exported to the memor

  • 2nd HDD to replace optical drive - B560

    I have seen a thread here (http://forums.lenovo.com/t5/W-Series-ThinkPad-Laptops/2nd-hard-drive-in-a-W510/m-p/346539#M12570) of success replacing the optical drive with a 2nd HDD bay in a y560. I am wrong thinking there is not much difference betwee

  • Update InDesign Server Version on Mac OS X Server

    Hi folks, quick question - quick answer: How can I update an InDesign Server running on an Mac OS X Server 10.5.8? Tried to use the installed Extends Script Toolkit, but the menu item under Help->Updates was disabled! Cheers Tino

  • FP 10 only - Audio does not match Powerpoint slide after publishing

    This is strictly related to Flash Player 10 We create E-Learning courses related to Autism. We usually start with the Powerpoint and audios and load them into Captivate. Match the Powerpoint and the audio together. We then Publish it to our website.

  • How to Connect Oracle with Crystal Reports

    Hi Everyone, I am new to Crystal Report, Just tell me how to connect Crystal Report thro' Oracle 9i or 10g Forms With regards, Krishnan