JApplet ,JScrollPane, JPanel

Hi,
I have a class JTestPanel2 which extends JPanel, I have added a button to this class and overriden the paint method to draw some lines,
In my JApplet, i create instance of Test class and add to the JSCrollPane, I add this JScrollPane to my JApplet content pane, the problem is i dont see the JButton on the screen , but when i click on some where i have added the JButton , i get the action performed event triggered,
My layout for Test class is BorderLayout and i add the button to north,
So what is the problem ..how can i solve it,
Answere ASAP
here is the code
for JPAnel
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JPanelTest2 extends JPanel implements ActionListener
     JPanel jp2 ;
     JButton jb;
     String message = "test";
     JPanelTest2()
          super();
          setLayout(new BorderLayout());
          jp2 = new JPanel();
          jb = new JButton("Okay");
          jb.addActionListener(this);
          jp2.add(jb);     
     setPreferredSize(new Dimension(400,400));
     add("North", jp2);
     jp2.setVisible(true)     ;
     public void paint(Graphics g)
super.paintComponent(g);
g.drawString(message, 200, 200);
public void actionPerformed(ActionEvent ev)
     message = "change";
     repaint();
Code for Applet
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JPanelTest1 extends JApplet
     Container c ;
     public void init()
     c = getContentPane();
     c.setLayout(new BorderLayout());
JPanelTest2 jp1= new JPanelTest2();
     JScrollPane js = new JScrollPane(jp1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
     js.getHorizontalScrollBar().setMaximum(500);
     js.getHorizontalScrollBar().setValue(0);
     setSize(400,400);
     c.add("North", js);
Ashish

Do not override the drawing for your main container JPanel. Instead place another JPanel instance into the layout of your containing JPanel and draw with that. That will contain the drawing of that panel to just the area contained in that sub panel, and then it won't mess up the drawing of the other items contained within the main panel.

Similar Messages

  • 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, JPanel used to make a paint-like application

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

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

  • JScrollPane, JPanel & Scrollable interface

    Hello,
    I recently did a little programming with a JPanel and mistakenly implemented the Scrollable interface with a JPanel when I did not need to. In the process I discovered something that has sparked my curiosity. I added a group of JLabels in a GridLayout to this Scrollable JPanel. I also set the horizontalalignment of the JLabels in the panel. When this was set the JPanel by itself rendered the Labels according to the alignment I had set. However when I put the panel in a JScrollPane, The alignment of the Labels was not rendered as I expected. The elements in the JPanel were always flush to the left, no matter what alignment I had constructed the label with.
    Does anyone know why if you descended from a JPanel and implemented the Scrollable interface with that object, when you pass the object into a JScrollPane why you would lose the alignments of the JLabels in that Scrollable JPanel?
    This is not pivotal information to me, but I am curious. If anyone knows the answer to this please let me know.
    Thanks,
    Dan Hughes

    Dan,
    I have no idea why this happens. I do know however that it is a great source of insanity when you really need to get a JScrollPane to behave itself. If ever you need to make a JPanel the client of a JScrollPane use null layout and absolute positioning, also setPreferredSize of the JPanel before adding components. When all components are added to the JPanel make the JPanel the client of a JScrollPane. Also at the very end of your code you will need this code to make the layout the scrollBars behave:
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    getViewport().setViewPosition(new Point(0,0));
    JScrollPAINS were not named PAINS for no reason. This information probably seems mostly irrelevant, but if you are curious, or intend on programming in future with JScrollPane it is probably wise to keep this near by.

  • Accessing Pictures from JApplet through JPanel

    Hi there!
    First of all, Thanks for giving time to read me!
    I made a game, which is in JPanel. It accesses some images from the file (JPEGs and GIFs) from local disk.
    Now, If I put that JPanel in an Applet (or JApplet), I am getting security errors of can't access files.
    I have used URLs in ImageIcons (with "localhost", "file", "filename").
    Why is that?
    Is there any way of accessing Image files from a JAR package??
    Please reply it soon, as i have to submit the game in the competition next week.
    Thanks.

    Hi there!
    One more similar problem... :(
    I want to put my Java game (created in JPanel) online through JApplet.
    I have put the images & sounds for that online. (e.g. "http://bla.bla.com/images/image.gif").
    Now if I run the program in JFrame, it is loading and working fine! But in Applet, I am getting security warnings/errors. Can anyone help please?
    Here's the sample code:
    public class Game extends JPanel {
    URL url = null;
    URLConnection con = null;
    //Constructor{
    try{
    url = new URL("http://....../image.gif");
    conn = url.openConnection();
    }catch(Exception e){/Message}
    ImageIcon img = new ImageIcon(url);
    }

  • Image NOT refreshing in jscrollpane/jpanel [source code included]

    Hello All,
    I am simply trying to show a large image inside a JScrollPane. I put several panels inside the main frame with a scrollpane and buttons in separate panels. On load, the image shows fine, but when I click Hide, the image doesn't refresh unless i drag another window (whether it is the command prompt window or a browser window or ANY window) over the main frame. The same thing happens when I click Show. After the image is hidden (or removed) and Show is clicked, the image doesn't refresh unless you roll another window over the image window.
    Why does this happen??? Can someone please help? Your help is greatly appreciated! ...I am using Textpad by the way.
    You may try running this by pasting my code, but the line where it says "tempScreenCaptureTest = imageLoad "ScreenCapture/data/ScreenCapture.jpg");" needs a real jpg image file (i used a screenshot of my own desktop) for you to see an image.
    // import classes
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import javax.swing.*;
    public class ScreenCaptureTest extends JFrame implements ActionListener
         private static void main(String[] args)
              // Create an instance of the application
              ScreenCaptureTest mainFrame = new ScreenCaptureTest();
              mainFrame.setVisible(true);
         } // end of main
         // create window objects
         private JPanel panelCenter = new JPanel();
         private JPanel panelSouth = new JPanel();
         private JScrollPane scrollPane;
         private JButton buttonShow = new JButton("Show");
         private JButton buttonHide = new JButton("Hide");
         private JLabel tempScreenCaptureTest;
         public ScreenCaptureTest()
              // font properties
              Font mainFont = new Font(("Verdana"), Font.PLAIN, 16);
              // set window properties
              setTitle("Screen Capture");
              setSize(700, 700);
              setBackground(Color.white);
              setResizable(false);
              getContentPane().setLayout(new BorderLayout());
              // load the ScreenCaptureTest image into the scrollPane object
              tempScreenCaptureTest = imageLoad("ScreenCapture/data/ScreenCapture.jpg");
              // set Cancel properties
              buttonShow.setFont(mainFont);
              buttonShow.setForeground(Color.black);
              buttonShow.setBackground(Color.gray);
              buttonShow.setBounds(50, 260, 200, 50);
              buttonShow.addActionListener(this);
              panelSouth.add(buttonShow, BorderLayout.WEST);
              // set Clear properties
              buttonHide.setFont(mainFont);
              buttonHide.setForeground(Color.black);
              buttonHide.setBackground(Color.gray);
              buttonHide.setBounds(50, 260, 200, 50);
              buttonHide.addActionListener(this);
              panelSouth.add(buttonHide, BorderLayout.EAST);
              // set panel properties
              getContentPane().add(panelSouth, BorderLayout.SOUTH);
         } // end of constructor
         // loads an image into the JScrollPane
         private JLabel imageLoad(String filepath)
              // create a label
              Icon image = new ImageIcon(filepath);
              JLabel labelScreenCaptureTest = new JLabel(image);
              panelCenter.setLayout(new BorderLayout());
              // create a tabbed pane
              scrollPane = new JScrollPane();
              scrollPane.getViewport().add(labelScreenCaptureTest);
              panelCenter.add(scrollPane, BorderLayout.CENTER);
              // set panel properties
              getContentPane().add(panelCenter, BorderLayout.CENTER);
              return labelScreenCaptureTest;
         // ActionListener method()
         public void actionPerformed(ActionEvent event)
              if (event.getSource() == buttonShow) {
                   scrollPane.getViewport().add(tempScreenCaptureTest);
                   panelCenter.add(scrollPane, BorderLayout.CENTER);
                   getContentPane().add(panelCenter, BorderLayout.CENTER);
              } else if (event.getSource() == buttonHide) {
                   System.out.print(tempScreenCaptureTest);
                   scrollPane.getViewport().remove(tempScreenCaptureTest);
                   panelCenter.remove(scrollPane);
                   getContentPane().add(panelCenter);
    }

    I might as well add my problem while I'm here. I'm using a JPanel with an overridden paint() method to draw my image. I'm holding the image in a JScrollPane and setting the preferred size to the image's dimensions. The trouble is, the image takes time to load. I've used an ImageObserver but I'm having trouble making it repaint the image. I can make the scroll pane update it's scrollbar width and height by telling it to updateUI() but I can't make it redraw the image. I've tried everything but from debugging I can see that it always calls my getPreferredSize() method last then after resizing, it doesn't redraw the image. Even if I tell it to repaint after updating UI. I'm at a loss :/ Is there a special component for managing images as I haven't done much work with them?

  • (Another) problem with custom painting using JApplet and JPanel

    Hi all,
    I posted regarding this sort of issue yesterday (http://forums.sun.com/message.jspa?messageID=10883107). I fixed the issue I was having, but have run into another issue. I've tried solving this myself to no avail.
    Basically I'm working on creating the GUI for my JApplet and it has a few different JPanels which I will be painting to, hence I'm using custom painting. My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class TetrisClone extends JApplet {
         public void init() {
              setSize( 450, 500 );
              Container content = getContentPane();
              content.add( new mainGUI(), BorderLayout.CENTER );
              content.add( new rightGUI() , BorderLayout.LINE_END );
    class mainGUI extends JPanel {
         // Main bit where blocks fall
         public mainGUI() {
              setBackground( new Color(68,75,142) );
              setPreferredSize( new Dimension( 325, 500 ) );
              validate();
         public Dimension getPreferredSize() {
              return new Dimension( 450, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              // As a test. This shows up fine.
              g.setColor( Color.black );
              g.fillRect(10,10,100,100);
              g.setColor( Color.white );
              g.drawString("Main",45,55);
    class rightGUI extends JPanel {
         BufferedImage img = null;
         int currentLevel = 0;
         int currentScore = 0;
         int currentLines = 0;
         public rightGUI() {
              // The right panel. Has quite a few bits. Starts here..
              FlowLayout flow = new FlowLayout();
              flow.setVgap( 20 );
              setLayout( flow );
              setPreferredSize( new Dimension( 125, 500 ) );
              setBackground( new Color(27,34,97) );
              setBorder( BorderFactory.createMatteBorder(0,2,0,0,Color.black) );
              // Next block bit
              JPanel rightNext = new JPanel();
              rightNext.setPreferredSize( new Dimension( 100, 100 ) );
              //rightNext.setBackground( new Color(130,136,189) );
              rightNext.setOpaque( false );
              rightNext.setBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) );
              Font rightFont = new Font( "Courier", Font.BOLD, 18 );
              // The player's playing details
              JLabel rightLevel = new JLabel("Level: " + currentLevel, JLabel.LEFT );
              rightLevel.setFont( rightFont );
              rightLevel.setForeground( Color.white );
              JLabel rightScore = new JLabel("Score: " + currentScore, JLabel.LEFT );
              rightScore.setFont( rightFont );
              rightScore.setForeground( Color.white );
              JLabel rightLines = new JLabel("Lines: " + currentLines, JLabel.LEFT );
              rightLines.setFont( rightFont );
              rightLines.setForeground( Color.white );
              JPanel margin = new JPanel();
              margin.setPreferredSize( new Dimension( 100, 50 ) );
              margin.setBackground( new Color(27,34,97) );
              JButton rightPause = new JButton("Pause");
              try {
                  img = ImageIO.read(new File("MadeBy.gif"));
              catch (IOException e) { }
              add( rightNext );
              add( rightLevel );
              add( rightScore );
              add( rightLines );
              add( margin );
              add( rightPause );
              validate();
         public Dimension getPreferredSize() {
                   return new Dimension( 125, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              g.setColor( Color.black );
              g.drawString( "blah", 425, 475 ); // Doesn't show up
              g.drawImage( img, 400, 400, null ); // Nor this!
              System.out.println( "This bit gets called fine" );
    }Any help would be greatly appreciated. I've read loads of swing and custom painting tutorials and code samples but am still running into problems.
    Thanks,
    Tristan Perry

    Many thanks for reminding me about the error catching - I've added a System.out.println() call now. Anywhoo, the catch block never gets run; the image get call works fine.
    My problem was/is:
    "My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:"
    I guess I should have expanded on that. Basically whatever I try to output in the public void paintComponent( Graphics g ) method of the rightGUI class doesn't get output.
    So this doesn't output anything:
    g.drawString( "blah", 425, 475 ); // Doesn't show up
    g.drawImage( img, 400, 400, null ); // Nor this!
    I've checked and experimented with setOpaque(false), however this doesn't seem to be caused by any over-lapping JPanels or anything.
    Let me know if I can expand on this :)
    Many thanks,
    Tristan Perry
    Edited by: TristanPerry on Dec 10, 2009 8:40 AM

  • 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 in setting desired position for JPanel in JScrollPane!!!

    Dear Friends,
    I am having problem to set desired Scrollable(JScrollPane) JPanel position. I have a JPanel in a JFrame which is scrolable with lot of objects. It automatically displays on the top position inside JScrollPane, I want to set scroll position on the middle for the panel.
    I went through the search for the same in this forum, i found some posts related to this but they are linked with JTextArea(setCaretPosition). With JPanel i can't set caret position.
    Could anyone guide me how to set the scroll position on middle.
    Regards..
    Jayshree

    Replace:
    if(view.getValueAt(row,column) instanceof ImageIcon){
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
          }with:
    if(view.getValueAt(row,column) instanceof ImageIcon)
            view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
           view.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

  • Passing value from JSP to JApplet

    Hello,
    I am stuck up with a problem, can anyone please tell me how do i pass a value from a JSP page
    to a JApplet,
    and the parameter passed through JSP should be displaed in the JTextArea.
    It would be kindful if any of you could help.
    Thanks
    Sanam

    hello,
    thanks for reply.
    I know how to pass parameters from html,
    I want to pass values from jsp page,
    and i dono how to do it, may be we cann pass values through url connection but i dono how.
    if anone knows plz help me in solving this.
    i hvae posted my applet code.
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    <applet code = "DocApplet" width = 500 height =5000>
    </applet>
    public class DocApplet extends JApplet
         private JPanel jp;
         private Container cp;
         private JTextArea jt;
         private JToolBar tb;     
         private JScrollPane sp;
         private String annotation;
         private String url;
         private Connection con;
         private Statement stmt;
         public void init()
              jp = new JPanel();
              cp = getContentPane();
              jt = new JTextArea();
              tb = new JToolBar();
              sp = new JScrollPane(jt);
              repaint();
         public void start()
              jp.setLayout(new BorderLayout());
              jp.add(tb, BorderLayout.NORTH);
              jp.add(sp, BorderLayout.CENTER);
              jt.setBackground(Color.BLACK);
              jt.setForeground(Color.WHITE);
              setContentPane(jp);
              addButtons(tb);
              repaint();
         public void run()
              repaint();
         public void paint()
         private void addButtons(JToolBar tb)
              JButton button = null;
              button = new JButton("Save");
              button.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
              tb.add(button);
    }

  • Adding java 2d graphices to a JScrollPane

    How can I use the graphics 2d in a Java Applet JScrollPane?
    here is me code. I have a a ImageOps.java file that does a bunch of Java 2d, but I need it to fit into my applet's JScrollPane. Can anyone help me?
    package louis.tutorial;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JApplet;
    import java.awt.Dimension;
    import javax.swing.JInternalFrame;
    import javax.swing.JButton;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Rectangle;
    import java.awt.Point;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JTextArea;
    import javax.imageio.ImageIO;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.ImageIcon;
    import javax.swing.KeyStroke;
    import java.awt.FileDialog;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import java.io.IOException;
    import java.net.URL;
    import javax.swing.JScrollPane;
    * Place class description here
    * @version 1.0
    * @author llakser
    public class ImageApplet extends JApplet {
    private JPanel jContentPane = null;
    private JPanel jpLower = null;
    private JButton JBFirst = null;
    private JButton JBPrevious = null;
    private JButton JBNext = null;
    private JButton JBLast = null;
    private JButton JBZoonIn = null;
    private JButton JBZoomOut = null;
    private JButton JBAnimate = null;
    private JButton JBPause = null;
    private JButton JBAutoRepeat = null;
    private JComboBox jcbFrameDelay = null;
    private BufferedImage image; // the rasterized image
    private Image[] numbers = new Image[10];
    private Thread animate;
    private MediaTracker tracker;
    private int frame = 0;
    private ImageIcon[] icon = null;
    private JFrame f = new JFrame("ImageOps");
    * This is the xxx default constructor
    public ImageApplet() {
         super();
    * This method initializes this
    * @return void
    public void init() {
         this.setSize(600, 600);
         this.setContentPane(getJContentPane());
         this.setName("");
         this.setMinimumSize(new Dimension(600, 600));
         this.setPreferredSize(new Dimension(600, 600));
    // f.addWindowListener(new WindowAdapter() {
    // public void windowClosing(WindowEvent e) {System.exit(0);}
    ImageOps applet = new ImageOps();
    //getJContentPane().add("Center", f);
    getJContentPane().add("Center", applet);
    //applet.add(f);
    applet.init();
    f.pack();
    f.setSize(new Dimension(550,550));
    f.setVisible(true);
    public void load() {
         tracker = new MediaTracker(this);
         for (int i = 1; i < 10; i++) {
         numbers[i] = getImage (getCodeBase (), i+".jpeg");//getImage(getDocumentBase(), "Res/" + i + ".gif");
         //Image img;
         //ico[i] = new ImageIcon(getCodeBase (), i+".jpeg");
         /* if (fInBrowser)
         img = getImage (getCodeBase (), "1.jpeg");
         else
         img = Toolkit.getDefaultToolkit ().getImage (
         "1.jpeg");*/
         tracker.addImage(numbers, i);
         try {
         tracker.waitForAll();
         } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         int i = 1;
         // for (int i = 1; i < 10; i++)
              icon[0] = new ImageIcon ("C:/images2/1.jpeg");//getImage(getDocumentBase(), "Res/" + i + ".gif");
              //icon[0] = new ImageIcon("C:/images2/1.jpg");
              //System.out.println("Made it after icon " + ico.toString());
              //ImageIcon ii = new ImageIcon("1.jpg");
              //jLabel = new JLabel(icon);
              //jLabel.setText("JLabel");
              //jLabel.setIcon(icon[0]);
         Graphics g = null;
              //g.drawImage(numbers[1],0,0,1500,1400,jScrollPane);
         //ImageIcon ii = new ImageIcon(numbers[2]);
         //this.jScrollPane.add(new JLabel(ii));// = new JScrollPane(new JLabel(ii));
         // System.out.println("Gee I made it..");
              //scroll.paintComponents(g);
              //paintComponents(g);
    public void paintComponents(Graphics g) {
    super.paintComponents(g);
    // Retrieve the graphics context; this object is used to paint shapes
    Graphics2D g2d = (Graphics2D)g;
    // Draw an oval that fills the window
    int width = this.getBounds().width;
    int height = this.getBounds().height;
    Icon icon = new ImageIcon("C:/images2/1.jpg");
    //jLabel.setIcon(icon);
    //g2d.drawImage(0,0,1500,1400);
    g2d.drawOval(10,20, 300,400);
    // and Draw a diagonal line that fills MyPanel
    g2d.drawLine(0,0,width,height);
    * This method initializes jContentPane
    * @return javax.swing.JPanel
    private JPanel getJContentPane() {
         if (jContentPane == null) {
         jContentPane = new JPanel();
         jContentPane.setLayout(new BorderLayout());
         jContentPane.setPreferredSize(new Dimension(768, 576));
         jContentPane.setMinimumSize(new Dimension(768, 576));
         jContentPane.setName("");
         jContentPane.add(getJpLower(), BorderLayout.SOUTH);
         return jContentPane;
    * This method initializes jpLower     
    * @return javax.swing.JPanel     
    private JPanel getJpLower() {
    if (jpLower == null) {
         try {
         jpLower = new JPanel();
         jpLower.setLayout(null);
         jpLower.setPreferredSize(new Dimension(500, 100));
         jpLower.setMinimumSize(new Dimension(500, 160));
         jpLower.add(getJBFirst(), null);
         jpLower.add(getJBPrevious(), null);
         jpLower.add(getJBNext(), null);
         jpLower.add(getJBLast(), null);
         jpLower.add(getJBZoonIn(), null);
         jpLower.add(getJBZoomOut(), null);
         jpLower.add(getJBAnimate(), null);
         jpLower.add(getJBPause(), null);
         jpLower.add(getJBAutoRepeat(), null);
         jpLower.add(getJcbFrameDelay(), null);
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return jpLower;
    * This method initializes JBFirst     
    * @return javax.swing.JButton     
    private JButton getJBFirst() {
    if (JBFirst == null) {
         try {
         JBFirst = new JButton();
         JBFirst.setText("First");
         JBFirst.setLocation(new Point(7, 7));
         JBFirst.setSize(new Dimension(59, 26));
         JBFirst.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent e) {
              System.out.println("First Button Clicked()");
         load();
              // TODO Auto-generated Event stub actionPerformed()
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBFirst;
    * This method initializes JBPrevious     
    * @return javax.swing.JButton     
    private JButton getJBPrevious() {
    if (JBPrevious == null) {
         try {
         JBPrevious = new JButton();
         JBPrevious.setText("Previous");
         JBPrevious.setLocation(new Point(69, 7));
         JBPrevious.setSize(new Dimension(94, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBPrevious;
    * This method initializes JBNext     
    * @return javax.swing.JButton     
    private JButton getJBNext() {
    if (JBNext == null) {
         try {
         JBNext = new JButton();
         JBNext.setText("Next");
         JBNext.setLocation(new Point(166, 7));
         JBNext.setSize(new Dimension(66, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBNext;
    * This method initializes JBLast     
    * @return javax.swing.JButton     
    private JButton getJBLast() {
    if (JBLast == null) {
         try {
         JBLast = new JButton();
         JBLast.setText("Last");
         JBLast.setLocation(new Point(235, 7));
         JBLast.setSize(new Dimension(59, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBLast;
    * This method initializes JBZoonIn     
    * @return javax.swing.JButton     
    private JButton getJBZoonIn() {
    if (JBZoonIn == null) {
         try {
         JBZoonIn = new JButton();
         JBZoonIn.setText("Zoom In");
         JBZoonIn.setLocation(new Point(408, 7));
         JBZoonIn.setPreferredSize(new Dimension(90, 26));
         JBZoonIn.setSize(new Dimension(90, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBZoonIn;
    * This method initializes JBZoomOut     
    * @return javax.swing.JButton     
    private JButton getJBZoomOut() {
    if (JBZoomOut == null) {
         try {
         JBZoomOut = new JButton();
         JBZoomOut.setBounds(new Rectangle(503, 7, 90, 26));
         JBZoomOut.setPreferredSize(new Dimension(90, 26));
         JBZoomOut.setText("Zoom Out");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBZoomOut;
    * This method initializes JBAnimate     
    * @return javax.swing.JButton     
    private JButton getJBAnimate() {
    if (JBAnimate == null) {
         try {
         JBAnimate = new JButton();
         JBAnimate.setText("Animate");
         JBAnimate.setSize(new Dimension(90, 26));
         JBAnimate.setPreferredSize(new Dimension(90, 26));
         JBAnimate.setLocation(new Point(408, 36));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBAnimate;
    * This method initializes JBPause     
    * @return javax.swing.JButton     
    private JButton getJBPause() {
    if (JBPause == null) {
         try {
         JBPause = new JButton();
         JBPause.setPreferredSize(new Dimension(90, 26));
         JBPause.setLocation(new Point(503, 36));
         JBPause.setSize(new Dimension(90, 26));
         JBPause.setText("Pause");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBPause;
    * This method initializes JBAutoRepeat     
    * @return javax.swing.JButton     
    private JButton getJBAutoRepeat() {
    if (JBAutoRepeat == null) {
         try {
         JBAutoRepeat = new JButton();
         JBAutoRepeat.setBounds(new Rectangle(446, 65, 106, 26));
         JBAutoRepeat.setText("Auto Repeat");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBAutoRepeat;
    * This method initializes jcbFrameDelay     
    * @return javax.swing.JComboBox     
    private JComboBox getJcbFrameDelay() {
    if (jcbFrameDelay == null) {
         try {
         jcbFrameDelay = new JComboBox();
         jcbFrameDelay.setSize(new Dimension(156, 25));
         jcbFrameDelay.setName("Frame Delay");
         jcbFrameDelay.setLocation(new Point(7, 35));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return jcbFrameDelay;
    } // @jve:decl-index=0:visual-constraint="10,10"

    I think you've got it:
    public class ImageComponent extends JPanel { //or JComponent
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            //do your rendering here
    }The fact that ImageComponent sits inside JScrollPane is accidental, right?
    It should be able to function on its own, without a JScrollPane present, just as JTextArea can.
    So I'm not sure what your question is. Can you post a small (<1 page)
    example program demonstrating your problem.
    For example, here are a very few lines demonstrating what I am trying to say:
    import java.awt.*;
    import javax.swing.*;
    class CustomExample extends JPanel {
        public CustomExample() {
            setPreferredSize(new Dimension(800,800));
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(0, 0, getWidth(), getHeight());
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    JFrame f = new JFrame("CustomExample");
                    f.getContentPane().add(new JScrollPane(new CustomExample()));
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setSize(400,400);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }Now you post your problem in a program that is just as short.

  • Problem in focusing JScrollPane

    I have problem in focusing a JScrollPane.
    I added a JPanel size 1000x1000 to a JScrollPane and I want to focus at the center of this JPanel.
    I have tried 2 ways to do it, but both don't work.
    1.----adding jPanel to jScrollPane directly----------------
    jScrollPane = new JScrollPane(jPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jScrollPane.getVerticalScrollBar().setValue(500);
    jScrollPane.getHorizontalScrollBar().setValue(500);
    jScrollPane.getVerticalScrollBar().show();
    2.----using JViewport-------------------
    JViewport vp = new JViewport();
    vp.setView(jPanel);
    vp.setViewPosition(new Point(500,500));
    vp.repaint();
    vp.doLayout();
    jScrollPane.setViewport(vp);
    Can anybody tell me where did I go wrong, please?

    Not sure, but I don't think you can set the scroll bar location until the component is visible on the frame. That is a component doesn't really have a size until it is layed out and visible on the screen. So try:
    frame.setVisible(true);
    jScrollPane.getVerticalScrollBar().setValue(500);
    jScrollPane.getHorizontalScrollBar().setValue(500);
    Or your could try adding a ComponentListener to you ScrollPane to set the scrollbar values when the component is shown.
    I'm basing my suggestion on the discussion from this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=476357

  • Adding JScrollPane to CardLayout

    public static void panelLayout (String panel)
            cardPanel.add (Rosters.rosterPanel1, "roster1");
            cardPanel.add (Rosters.rosterPanel2, "roster2");
            cardPanel.add (OP300.evalLoadPane1, "op300load1"); // JScrollPane with JPanel inside
            cardPanel.add (mainPanel, "main");
            CardLayout showPanel = (CardLayout)(cardPanel.getLayout ());
            showPanel.show (cardPanel, panel);
        }I'm trying to add a JScrollPane to my CardLayout just like I have with the other JPanels. All of the other JPanels work fine, but adding the JScrollPane is giving me issues. As soon as PanelLayout() is called, even if it isn't calling for the JScrollPane, I'm getting: Exception occurred during event dispatching:
    java.lang.NullPointerException
            at java.awt.Container.addImpl(Container.java:1027)
            at java.awt.Container.add(Container.java:903)
            at HubEvals.panelLayout(HubEvals.java:540)
            at Login.b_loginActionPerformed(Login.java:175)
            at Login.access$000(Login.java:18)
            at Login$1.actionPerformed(Login.java:92)
            ...The JScrollPane modifier is public static so it isn't having problems getting access to it. I even tried putting the JScrollPane inside a JPanel so it would be like:
    - JPanel
    ----- JScrollPane
    ---------- JPanel (panel that is longer than the frame itself, hence why it's in a scroll pane)
    I still got the same error.

    This time I remembered to initialize it. I added it to my initComponents() method and I was still getting the problem:public HubEvals ()
            initComponents ();
            new Rosters ();
            new OP300 ();
            RegisterLogin intro = new RegisterLogin ();
            intro.showInDialog (this);
        }I had accidentally typed new OP3O0 (); instead of new OP300 ();. What's up with that? The first thing I typed doesn't even exist as a method, class, or variable and it still passed NetBeans validation. I spent well over 50 minutes on a stupid '0' being an 'O' and the 2 characters look exactly the same in the code font.
    Anyway, thanks. Problem solved. Heh. You run into stuff like this when you don't leave the computer for hours at a time.

  • JTextPane inside JScrollPane resizing when updated

    Hiya all,
    I've been struggling with this problem and checking the forums, but didn't find a solution, so I hope someone can help...at least help me for the nice picture :) It has to do with JTextPane's automatically resizing to their content on a GUI update, rather than scrollbars appearing (the desired result).
    Basically, I have a scenario where I am creating a series of multiple choice answers for a question. Each answer consists of a JTextPane inside a JScrollPane, and a JRadioButton, which are all contained in a JPanel (called singleAnswerPanel). So for 2 answers, I would have 2 of these singleAnswerPanels. There is a one large JPanel that contains all the singleAnswerPanels (called allAnswersPanel). This allAnswersPanel is contained in a JScrollPane. Graphically, this looks like:
       |       JPanel (allAnswersPanel) inside a JScrollPane            |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
        ----------------------------------------------------------------So above, I show 2 answers that can be filled in with text. So assuming both answer JTextPanes are filled with text beyond their current border (scrollbars appear as expected) and the user wishes to add more answers. I have a button to add another singleAnswerPanel to the containing JPanel (allAnswersPanel), and then I validate the main JScrollPane that contains the allAnswersPanel as it's view. The problem that occurs is the existing single answer JTextPanes resize to the size of their text and the vertical scrollbars (only vertical ones setup) of the JTextPanes dissappear! My intent is to keep the existing JScrollPanes the same size (with their scrollbars) when a new answer is added.
    The code snippet below shows what gets done when a new answer is added:
    private void createAnswer()
        // The panel that will hold the new single answer JTextPane pane
        // (inside a JScrollPane) and radio button.
        JPanel singleAnswerPanel = new JPanel();
        // Create the text pane for the single answer.
        JTextPane singleAnswerTextPane = new JTextPane();
        Dimension dimensions = new Dimension(200, 30);
        singleAnswerTextPane.setPreferredSize(dimensions);
        singleAnswerTextPane.setMaximumSize(dimensions);
        // Create a scroll pane and add the single answer text pane.
        JScrollPane singleAnswerScrollPane =
         new JScrollPane(singleAnswerTextPane);
        // Create a radio button that is associated with the single
        // answer text pane above.
        JRadioButton singleAnswerRadioButton = new JRadioButton();
        // Add the scroll pane and radio button to the panel (for a single
        // answer).
        singleAnswerPanel.add(singleAnswerScrollPane);
        singleAnswerPanel.add(singleAnswerRadioButton);
        // Add the panel holding a single answer to the panel holding
        // all the answers.
        m_allAnswersPanel.add(singleAnswerPanel);
        // Update the display.  m_allAnswersScrollPane is a JScrollPane
        // that has the m_allAnswersPanel (JPanel) as its view.
        m_allAnswersScrollPane.validate();
    }     Sorry for the length of the message, but I really want to solve this problem. So again, when updating the JScrollPane with validate(), the JTextPane for a single answer resizes to it's contents (plain text currently) and loses it's vertical scrollbars, but I want it to stay the same size and maintain the scrollbars.
    Thanks!

    http://java.sun.com/docs/books/tutorial/uiswing/mini/layout.htmlimport javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Test extends JFrame {
        int cnt=0;
        Random r = new Random();
        String[] nouns = {"air","water","men","idjits"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        JScrollPane mainScroll = new JScrollPane(mainPanel);
        JScrollBar mainScrollBar = mainScroll.getVerticalScrollBar();
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JLabel("QuizMaster 2003"), BorderLayout.NORTH);
         content.add(mainScroll, BorderLayout.CENTER);
         JButton jb = new JButton("New");
         content.add(jb, BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              JPanel questionPanel = new JPanel(new GridBagLayout());
              questionPanel.add(new JLabel("Question "+cnt++),
                   new GridBagConstraints(0,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              questionPanel.add(new JLabel("Why is there "+
                            nouns[r.nextInt(nouns.length)]+"?"),
                   new GridBagConstraints(1,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              JTextArea jta = new JTextArea();
              JScrollPane jsp = new JScrollPane(jta);
              jsp.setPreferredSize(new Dimension(300,50));
              questionPanel.add(jsp, new GridBagConstraints(0,1,2,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.BOTH,
                        new Insets(1,2,1,2),0,0));
              mainPanel.add(questionPanel, new GridBagConstraints(0,cnt,1,1,0.0,0.0,
                            GridBagConstraints.EAST,GridBagConstraints.NONE,
                            new Insets(0,0,0,0),0,0));
              mainPanel.revalidate();
              mainScroll.getViewport().setViewPosition(new Point(0, mainPanel.getHeight()));
         setSize(400,300);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • Knob in JScrollPane

    Hi,
    I'm using JScrollPane for a JTree.
    Now I want to change the look of the knob without changing the L&F.
    I found out that I can change the Colors using the UIManager:
    UIManager.put("ScrollBar.thumb",new Color(212,208,200));
    UIManager.put("ScrollBar.background", new Color(233,233,233));          
    UIManager.put("ScrollBar.thumbShadow",Color.lightGray.darker());
    UIManager.put("ScrollBar.thumbHighlight",Color.lightGray.brighter());
    Is there a posbility to change the knob the same way?
    J&ouml;rn

    hi,
    have you had any luck with this yet?
    I tried compiling the code below and it all seems to work??
    Does this work for you? If it does then could you send more code?
    asjf
    import javax.swing.*;
    import java.awt.*;
    public class DDPanel extends JPanel implements Scrollable//, CommonProperties
    private Dimension preferredViewportSize;
    public DDPanel()
    super();
    //super.setFont(DEFAULT_FONT);
    //super.setForeground(DEFAULT_FOREGROUND);
    //super.setSize(DEFAULT_PANEL_WIDTH,DEFAULT_PANEL_HEIGHT);
    super.setLayout(null);
    setAutoscrolls(true);
    public void paint(Graphics g)
         super.paint(g);
         g.drawString("Hello World",200,200);
    // Implementing the Scrollable interface
    public void setPreferredScrollableViewportSize(Dimension size)
    preferredViewportSize = size;
    public Dimension getPreferredScrollableViewportSize()
    return preferredViewportSize;
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
    return 10;
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
    return 100;
    public boolean getScrollableTracksViewportWidth()
    return true;
    public boolean getScrollableTracksViewportHeight()
    return false;
    public static void main(String [] arg)
         JFrame frame = new JFrame();
         frame.setSize(640,480);
         frame.setVisible(true);
         DDPanel pnlEncoderConfig = new DDPanel();
    pnlEncoderConfig.setPreferredSize(new Dimension(300,350));
    pnlEncoderConfig.setPreferredScrollableViewportSize(new Dimension(300, 300));
    JScrollPane spEncoderConfigPanel= new JScrollPane();
    JPanel configContainer = new JPanel(null);
    spEncoderConfigPanel.setViewportView(pnlEncoderConfig);
    spEncoderConfigPanel.setBounds(0, 0, 755, 260);
    //tpEncoderDetails.add(configContainer);
    configContainer.add(spEncoderConfigPanel);
    frame.getContentPane().add(configContainer);
    }

Maybe you are looking for