Extends JScrollPane

Hi everyone,
I am trying to extend JScrollPane component and show a tree component
into the extended
JScrollPane. I can compile the code, but when the JScrollPane is showed it is empty. This is the code that I am using:
class JScrollPaneObjectInspector extends JScrollPane {
      private JTree tree = null;
    public JScrollPaneObjectInspector()
        super();
        setSize(200, 200);
      //Inspect this object
        PointTest testClass = new PointTest(1,1);
        Class clsInfo = testClass.getClass();
        Variable v = new Variable(clsInfo, clsInfo.getName(), PointTest.class);
      ObjectTreeModel model = new ObjectTreeModel();
      model.setRoot(v);
      // construct and show tree
      setTree(new JTree(model));
      super.add(getTree());
    public void setTree(JTree tree) {
        this.tree = tree;
    public JTree getTree() {
        return tree;
public class MainWindow {
    private JFrame jFrame = null;...
     * This method initializes jSplitPane
     * @return javax.swing.JSplitPane
    private JSplitPane getJSplitPane() {
        if (jSplitPane == null) {
            jSplitPane = new JSplitPane();
            jSplitPane.setRightComponent(getJScrollPaneRight());
        return jSplitPane;
     * This method initializes jScrollPaneLeft
     * @return javax.swing.JScrollPane
    private JScrollPane getJScrollPaneRight() {
        if (rightSPaneObjInspector == null)
            rightSPaneObjInspector = new JScrollPaneObjectInspector();
            rightSPaneObjInspector.setPreferredSize(new Dimension(200, 200));
        return rightSPaneObjInspector;
     * @param args
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainWindow application = new MainWindow();
                application.getJFrame().setVisible(true);
}In the code I don't show how I create the tree, but this part is working, because I have test this with JScrollPane component directly. Thank very much for any help

There is no need to extend a scrollpane simply because you want to add a component to it. That is not new functionality as the scroll pane is designed to display components. Your basic code should be:
JTree tree = new JTree(...);
JScrollPane scrollPane = new JScrollPane( tree );I would guess the main problem with you code is that you don't "add" components to a scrollpane. Components are added to the viewport of the scrollpane. The easiest way to do this is when you create the scrollpane as I showed above. Otherwise you can set the viewport directly:
scrollPane.setViewportView( tree );

Similar Messages

  • Problem with JScrollPane and Mouse Event in JDK 1.4

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

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

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

  • JScrollPane, JTextPane, Weird scrolling happening

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

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

  • JScrollPane Scroll Position

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

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

  • JTable in JScrollPane auto resize refresh problem

    Hello,
    I have a JTable in a JScrollPane. Number of rows is changing.
    I'm using the following to auto-resize JScrollPane.
    public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
             }There is a JButton, which adds an empty row to the JTable. It all works fine, except the auto-resize when a new row is added. I want all rows of JTable to be visible, with no scrollbars present. I tried repaint(), revalidate(), addNotify(). What should I do?
    Thanks.

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • Mouse Coordinate issues caused by Scaling Components in a JScrollPane

    Hi All,
    I've been attempting to write a program that includes a simple modeler. However, I've been having some trouble with being able to select components when attempting to implement zoom functionality - when I "zoom" (which is done via scroll wheel) using the scale Graphics2D method, while it zooms correctly, the mouse location of components do not seem scale.
    I've tried one of the solutions found on the forums here (create a custom event queue that adjusts the mouse coordinates) and while it seemed to work initially, if I zoom in and adjust the current view position using the scrollbars, certain components contained in the JPane will become un-selectable and I haven't been able to work out why.
    I've attached a SSCCE that reproduces the problem below - it implements a JScrollPane with a JPane with a few selectable shapes set as the Viewport. The zoom is done using the mouse scroll wheel (with wheel up being zoom in and wheel down being zoom out)
    Any help in order to fix the selection/de-selection issues on zoom would be greatly appreciated! I've spent some time reading through the forums here but have unfortunately not been able to find a workable solution around it.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Tester extends JScrollPane
        public Tester() {
            this.setViewportView(new Model());
        public static void main (String[] args) {
            JFrame main = new JFrame();
            main.add(new Tester());
            main.setSize(500,300);
            main.setResizable(false);
            main.setVisible(true);
    class Model extends JPanel implements MouseListener, MouseWheelListener
        private GfxClass selection = null;
        private static double zoomLevel = 1;
        // zoom methods
        public void setZoom(double zoom) {
            if( zoom < 0 && zoomLevel > 1.0)
                zoomLevel += zoom;
            if( zoom > 0 && zoomLevel < 5.0)
                zoomLevel += zoom;
        public static double getZoom() { return zoomLevel; }
        public void resetZoom() { zoomLevel = 1; }
        public Model() {
            super(null);
            addMouseListener(this);
            addMouseWheelListener(this);
            MyEventQueue meq = new MyEventQueue();
            Toolkit.getDefaultToolkit().getSystemEventQueue().push(meq);
            for(int i = 0; i <7; i++) {
                double angle = Math.toRadians(i * 360 / 7);
                GfxClass oc_tmp = new GfxClass((int)(200 + 150 * Math.cos(angle)), (int)(125 + 100 * Math.sin(angle)), "Element"+i);
                add(oc_tmp);
            repaint();
        public void paint (Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            AffineTransform oldTr=g2.getTransform();
            g2.scale(getZoom(),getZoom());
            super.paint(g2);
            g2.setTransform(oldTr);
            setBackground (Color.white);
            super.paintBorder(g2);
        private static class MyEventQueue extends EventQueue  {
            protected void dispatchEvent(AWTEvent event) {
                AWTEvent event2=event;
                if ( !(event instanceof MouseWheelEvent) && (event instanceof MouseEvent) ) {
                    if ( event.getSource() instanceof Component && event instanceof MouseEvent) {
                        MouseEvent me=(MouseEvent)event2;
                        Component c=(Component)event.getSource();
                        Component cursorComponent=SwingUtilities.getDeepestComponentAt(c, me.getX(), me.getY());
                        JPanel zContainer= getZoomedPanel(cursorComponent);
                        if (zContainer!=null) {
                            int x=me.getX();
                            Point p=SwingUtilities.convertPoint(zContainer,0,0,(Component)event.getSource());
                            int cX=me.getX()-p.x;
                            x=x-cX+(int)(cX/getZoom());
                            int y=me.getY();
                            int cY=me.getY()-p.y;
                            y=y-cY+(int)(cY/getZoom());
                            MouseEvent ze = new MouseEvent(me.getComponent(), me.getID(), me.getWhen(), me.getModifiers(), x, y, me.getClickCount(), me.isPopupTrigger());
                            event2=ze;
                super.dispatchEvent(event2);
        public static JPanel getZoomedPanel(Component c) {
            if (c == null)
                return null;
            else if (c instanceof Model)
                return (Model)c;
            else
                return getZoomedPanel(c.getParent());
        private void deselectAll() {
            if(selection != null)
                selection.setSelected(false);
            selection = null;
        public void mouseClicked(MouseEvent arg0)  {    }
        public void mouseEntered(MouseEvent arg0)  {    }
        public void mouseExited(MouseEvent arg0)   {    }
        public void mouseReleased(MouseEvent arg0) {    }   
        public void mousePressed(MouseEvent me) {
            Component c1 = findComponentAt(me.getX(),me.getY());
            if(c1 instanceof GfxClass)
                if(selection != null)
                    selection.setSelected(false);
                selection = (GfxClass)c1;
                selection.setSelected(true);
            else
                deselectAll();
            repaint();
            return;
        public void mouseWheelMoved(MouseWheelEvent e) { // controls zoom
                int notches = e.getWheelRotation();
                if (notches < 0)
                    setZoom(0.1);
                else
                    setZoom(-0.1);
                this.setSize(new Dimension((int)(500*getZoom()),(int)(300*getZoom())));           
                this.setPreferredSize(new Dimension((int)(500*getZoom()),(int)(300*getZoom())));     
                repaint();
    class GfxClass extends Component { // simple graphical component
        private boolean isSelected = false;
        private String name;
        public GfxClass(int xPos, int yPos, String name) {
            this.name = name;
            this.setLocation(xPos,yPos);
            this.setSize(100,35);
        public void setSelected(boolean b) {
            if( b == isSelected )
                return;
            isSelected = b;
            repaint();
        public boolean isSelected() {
            return isSelected;
        public void paint(Graphics g2) {
            Graphics2D g = (Graphics2D)g2;
            if( isSelected )
                g.setColor(Color.RED);
            else
                g.setColor(Color.BLUE);
            g.fill(new Ellipse2D.Double(0,0,100,35));
            g.setColor(Color.BLACK);
            g.drawString(name, getSize().width/2 - 25, getSize().height/2);
    }Edited by: Kys99 on Feb 22, 2010 9:09 AM
    Edited by: Kys99 on Feb 22, 2010 9:10 AM

    Delete your EventQueue class. Change one line of code in your mouse pressed method.
    public void mousePressed(MouseEvent me) {
        Component c1 = findComponentAt((int) (me.getX()/getZoom()),
                                       (int) (me.getY()/getZoom()));
    }

  • JScrollPane visible part refresh rate problem

    I am writing an application that reads image and displays it in a JScrollPane via JPanel. It also has JSlider to set displayed image focus. The problem is that sometimes when big image is loaded and user changes seen part via scrollbars, the JScollPane refresh takes about 10 sec. The question is: How to make JScrollPane's content refresh/repaint only the part that is visible. The code is:
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    public class Main extends JFrame{
        private BufferedImage image;
        private JScrollPane sPane;
        private ImagePanel iPanel;
        private JSlider slider;
        private Container contentPane;
        public Main() {
            try {
                image = ImageIO.read(new File("c:\\pict\\img.JPG"));
            } catch (IOException ioe){
                ioe.printStackTrace();
                System.exit(1);
            slider = new JSlider(JSlider.HORIZONTAL,1,3,1);
            slider.setMinorTickSpacing(1);
            slider.setMajorTickSpacing(1);
            slider.setSnapToTicks(true);
            slider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    iPanel.setImageFocus(slider.getValue());
                    invalidate();
            iPanel = new ImagePanel(image);
            sPane = new JScrollPane(iPanel,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            contentPane = this.getContentPane();
            contentPane.add(slider,BorderLayout.NORTH);
            contentPane.add(sPane,BorderLayout.CENTER);
            setExtendedState(JFrame.MAXIMIZED_BOTH);
            setDefaultCloseOperation(3);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
    class ImagePanel extends JPanel{
        private Image img;
        private Dimension imageSize;
        public ImagePanel(Image img){
            this.img = img;
            imageSize = new Dimension(img.getWidth(null),img.getHeight(null));
        public void setImage(Image img){
            this.img = img;
        public void setImageFocus(int focus){
            if (this!=null){
                getGraphics().clearRect(0,0,imageSize.width,imageSize.height);
            switch (focus){
                case 1:
                    imageSize = new Dimension(img.getWidth(null),img.getHeight(null));
                    break;
                case 2:
                    imageSize = new Dimension(2*img.getWidth(null),2*img.getHeight(null));
                    break;
                case 3:
                    imageSize = new Dimension(3*img.getWidth(null),3*img.getHeight(null));
                    break;
                default:
                    imageSize = new Dimension(0,0);
            setSize(imageSize);
            setPreferredSize(imageSize);
            repaint();
            ((JScrollPane)getParent().getParent()).revalidate();
        public void paintComponent(Graphics g){
            JScrollPane sp = (JScrollPane)getParent().getParent();
            g.clearRect(sp.getX(),sp.getY(),sp.getWidth(),sp.getHeight());
            g.drawImage(img,0,0,imageSize.width,imageSize.height,null);
    }Thanks,

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • Fixed a top line in JScrollPane?

    Dear all,
    I have a JScrollPane, which has a textPane in it. Now I want to set one important warning line at the top of the textPane, and then add any other texts into textPane following the warning line. Moreover, I want this warning line to be fixed at the top, no matter whether the textPane scroll down or not, i.e, this warning line is always at the top of pane and never disappears when scrolling down the textPane.
    I do not know how to implement this. The following code will scroll away the warning line after I adds long lines to it.
    Any samples on how to implement this?
    public class NewsPane extends JScrollPane {
      private JTextPane text;
      private DefaultStyledDocument doc;
      public NewsPane() {
           JTextPane text = new JTextPane( doc=new DefaultStyledDocument());
           text.setText("Warning ...");
           setViewportView(text);
      }Thanks!

    Try this
    regards
    Stas
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
    JTextPane edit=new JTextPane();
    JScrollPane scroll;
    JLabel l;
    public Test() throws Exception {
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    scroll=new JScrollPane(edit);
    l=new JLabel("Warning!");
    l.setBounds(10,10,100,20);
    l.setForeground(Color.red);
    edit.add(l);
    frame.getContentPane().add(scroll);
    AdjustmentListener adjLst = new AdjustmentListener() {
    public void adjustmentValueChanged(AdjustmentEvent e) {
    Rectangle rect=scroll.getViewport().getViewRect();
    l.setLocation(rect.x+10,rect.y+10);
    scroll.getVerticalScrollBar().addAdjustmentListener(adjLst);
    frame.setSize(200,200);
    frame.setLocationRelativeTo(null);
    frame.show();
    edit.getDocument().insertString(0,"test1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",null);
    public static void main(String[] args) throws Exception {
    new Test();

  • Unable to grow and shrink a JTable within a JScrollPane

    I need help with the following: I want to display a JTable component with a calendar like design. Dragging the size of the parent component (having a border to drag) should dynamically adapt the JTable' size and its cells. Since the JTable has a minimum size shrinking the parent component should show scrollbars if the minimum size is reached horizontal or vertical respectively.
    I have the JTable put ijnto the viewport of a scrollpane and the scrollpane is the child component of a JPanel. So dragging appears with the panel.
    The JTable cells do nicely but from a specific size on there is a grey area on the lower part of the JPanel which is not repainted. What is causing this? What do I have to do? I'm lost in the jungle of invalidate(), repaint(), update(), doLayout() etc.
    Here is my SSCCE (at least I hope it is one):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    //public class MyComponent extends JScrollPane
    public class MyComponent extends JPanel
    ///   class data
         static public final long serialVersionUID = -1L;
         static public final int c_ColWidth = 29;
         static public final int c_RowHeight = 18;
         static public final int c_TableWidth = 930;
         static public final int c_TableHeight = 234;
    ///   instance data
         private String[] m_strColHeader = {
              "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
              "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
              "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
              "31",
         private Object[][] m_Data = new Object[12][33];// data array
         private TableModel m_DataModel = new AbstractTableModel() {
              static public final long serialVersionUID = -1L;
              public int getColumnCount() { return m_strColHeader.length; }
              public int getRowCount() { return m_Data != null ? m_Data.length : 0; }
              public Object getValueAt(int row, int col) { return m_Data[row][col]; }
              public String getColumnName(int col) { return m_strColHeader[col]; }
              public Class getColumnClass(int col) { return String.class; }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int col) {
                   m_Data[row][col] = aValue;
         protected BorderLayout myLayout = new BorderLayout();
         protected JTable tableView = new JTable(m_DataModel);
         protected JScrollPane scrollPane = new JScrollPane(tableView);
    ///   public class methods
         static public void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch(Exception e)
                   e.printStackTrace();
              MyComponent comp1 = new MyComponent();
              JFrame frame = new JFrame("MyComponent");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.getContentPane().add(comp1);
              frame.pack();
              frame.setVisible(true);
    ///   constructors
         public MyComponent()
              try
                   jbInit();
                   initTable();
              catch(Exception ex)
                   ex.printStackTrace();
    ///   protected instance methods
         protected void initTable()
              // do nor allow user interaction with calendar view
              tableView.getTableHeader().setReorderingAllowed(false);
              tableView.getTableHeader().setResizingAllowed(false);
              //tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tableView.setRowHeight(c_RowHeight);
              // adapt all CellRenderers
              for (int i = 0; i < m_DataModel.getColumnCount(); i++)
                   TableColumn column = tableView.getColumn(tableView.getColumnName(i));
                   column.setMinWidth(c_ColWidth);
                   column.setPreferredWidth(c_ColWidth);
    ///   private instance methods
         private void jbInit() throws Exception
              this.setLayout(myLayout);
              this.add(scrollPane, BorderLayout.CENTER);
              scrollPane.getViewport().setMinimumSize(new Dimension(c_TableWidth, c_TableHeight));
              scrollPane.getViewport().setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              tableView.setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              addComponentListener(new MyComponent_componentAdapter(this));
    ///   event handling
         public void componentBoundsChanged(ComponentEvent e)
              scrollPane.setBounds(0, 0, getWidth(), getHeight());
              scrollPane.getViewport().setBounds(0, 0, getWidth(), getHeight());
              //tableView.setBounds(0, 0, getWidth(), getHeight());
              tableView.setSize(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight());
              tableView.setRowHeight(getBounds().height / 13 < c_RowHeight ?
                        c_RowHeight : getBounds().height / 13);
              System.out.println("componentBoundsChanged: getBounds() = " + getBounds());
              System.out.println("componentBoundsChanged: getSize() = " + getSize());
              System.out.println("componentBoundsChanged: getViewport().getBounds() = " + scrollPane.getViewport().getBounds());
              System.out.println("componentBoundsChanged: getViewport().getSize() = " + scrollPane.getViewport().getSize());
              System.out.println("componentBoundsChanged: tableView.getBounds() = " + tableView.getBounds());
              System.out.println("componentBoundsChanged: tableView.getSize() = " + tableView.getSize());
    ///   event adapters
    class MyComponent_componentAdapter extends ComponentAdapter
         protected MyComponent adaptee;
         MyComponent_componentAdapter(MyComponent adaptee)
              this.adaptee = adaptee;
         public void componentMoved(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
         public void componentResized(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
    }

    I guess i am facing exactly opposite problem.
    What i want to do is, I have nested tables in a scroll pane. So I don't want a scroll pane to show exactly whatever visible rows are there in Table (No extra space). If i expand any row, i want scroll pane to be able to show expanded.

  • Adding a JPanel to a JScrollPane?

    I have a JPanel which may hold a lot of components, this may run off the end of the window so I want to add the components to a JPanel and the JPanel to a JScrollPane to deal with this can anyone tell me why the below code won't do this?
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ScrollPaneConstants;
    public class Test extends JScrollPane
         public JFrame testFrame;
         public JPanel testPanel;
         public JCheckBox checkBox;
         public static void main(String[] args)
              new Test();
         public Test()
              testFrame = new JFrame("test");
              //testFrame.getContentPane().setLayout(null);
              testPanel = new JPanel();          
              JScrollPane sp = new JScrollPane(testPanel);
              //add the panel to the scroll pane
              //sp.setViewportView(testPanel);
              //sp.getVerticalScrollBar();
              this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              testFrame.getContentPane().add(sp);
              //add the scroll pane to the frame
             JLabel lbl1 = new JLabel("blah");
             testPanel.add(lbl1);
            testFrame.getContentPane().add(testPanel);
             for(int i=0; i==20; i++)
                   checkBox = new JCheckBox(String.valueOf(i));
                  //checkBox.addItemListener(this);
                  JTextField txt1 = new JTextField(10);
                  txt1.setText("hello world");
                 testPanel.add(checkBox);
                testPanel.add(txt1);
            testPanel.validate();
            testPanel.setVisible(true);
            testFrame.pack();
            testFrame.setVisible(true);
            testFrame.setSize(100, 200);
            testFrame.show();
    }

    Actually not extending JScrollPane means that
    this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    raised compile errors so you've clearly not bothered to run it.
    Anyway, I figured out the solution, for anyone who may find it useful here it is:
    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.JTextField;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    public class Test
         public JFrame testFrame;
         public JPanel testPanel;
         public JCheckBox checkBox;
         public JButton btnDone;
         public static void main(String[] args)
              new Test();
         public Test()
              testFrame = new JFrame("test");
              testPanel = new JPanel();
              testPanel.setLayout(new GridBagLayout());
              JScrollPane sp = new JScrollPane();
              GridBagConstraints gridBagConstraints = new GridBagConstraints();
             JLabel lbl1 = new JLabel("blah");
             testPanel.add(lbl1);
             for(int i=0; i<20; i++)
                   checkBox = new JCheckBox(String.valueOf(i));
                  //checkBox.addItemListener(this);
                  JTextField txt1 = new JTextField(10);
                  txt1.setText("hello world");
                 gridBagConstraints.gridx = 0;
                 gridBagConstraints.gridy = i+1;
                 testPanel.add(checkBox, gridBagConstraints);
                 gridBagConstraints.gridx = 1;
                 gridBagConstraints.gridy = i+1;
                 testPanel.add(txt1, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = gridBagConstraints.gridy+1;
            testPanel.add(btnDone = new JButton("Done"), gridBagConstraints);
              sp.setViewportView(testPanel);
             testFrame.getContentPane().add(sp);
             //btnDone.addActionListener(this);
            testPanel.validate();
            testFrame.pack();
            testFrame.setVisible(true);
            testFrame.setSize(200, 300);
            testFrame.show();
    }

  • JScrollPane woes....

    Alright. I am making a program which has a "Workspace" which can contain plates (Plates as in the 96-well plates used in biology). Right now the plates can be dragged anywhere on the workspace, which is what I want. However I want the workspace to be scrollable so that if you scroll the plate off of the view then you can scroll to it.
    I tried making the workspace extend JPanel then just create a JScrollPane and add the panel to it, but I couldn't get that to work...so then I though I could just make the workspace extens JScrollPane but this also doesn't work. I tried implementing scrollable and that doesn't work
    Now, i did try new JScrollPane(new JTextArea(5,10)) just to see if it would work, and it did. So it appears what the JScrollPane is unable to determine when my plate has gone out of view.
    Here is the Plate:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Plate extends JPanel{
         public Plate(){
              setLayout(new GridLayout(9,12));
              setBackground(new Color(255,255,255));
              Border titledBdr = BorderFactory.createLineBorder(new Color(0,0,0));
              setBorder(titledBdr);
              setMinimumSize(new Dimension(275,175));
              setPreferredSize(new Dimension(275,175));
              setMaximumSize(new Dimension(275,175));
              myWells = new Well[9][12];
              for(int a=0; a<9; a++){
                   for(int b=0; b<12; b++){
                        Well tempWell = new Well(a, b, ("("+String.valueOf(a)+","+String.valueOf(b)+")"), false);
                        MouseListener listener = new DragMouseAdapter();
              tempWell.addMouseListener(listener);
                        myWells[a] = tempWell;
                        add(myWells[a][b]);
         public void setColor(int a, int b, int c){
              setBackground(new Color(a,b,c));
         private class DragMouseAdapter extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
    JComponent c = (JComponent)e.getSource();
    TransferHandler handler = c.getTransferHandler();
    handler.exportAsDrag(c, e, TransferHandler.COPY);
         private Well[][] myWells;
         private JPanel myPlate;
    ================================
    Here is the wokspace:
    import javax.swing.*;
    import java.awt.*;
    import java.util.ArrayList;
    import javax.swing.plaf.basic.BasicScrollBarUI;
    import java.util.Vector;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class WorkspacePanel extends JScrollPane implements MouseListener, MouseMotionListener{
         public WorkspacePanel(){
              currentPlate = null;
              addMouseListener(this);
         addMouseMotionListener(this);
         setAutoscrolls(true);
         public void mouseClicked(MouseEvent e){
              int x = (int)origin.getX();
              int y = (int)origin.getY();
              Component tempComponent = getComponentAt(x,y);
              if(tempComponent instanceof Plate){
                   currentPlate = (Plate)tempComponent;
         public void mouseEntered(MouseEvent e){
         public void mouseExited(MouseEvent e){
         public void mousePressed(MouseEvent e){
              origin = e.getPoint();
              int x = (int)origin.getX();
              int y = (int)origin.getY();
              Component tempComponent = getComponentAt(x,y);
              if(tempComponent instanceof Plate){
                   currentPlate = (Plate)tempComponent;
                   currentPlate.setBorder(new BevelBorder(BevelBorder.RAISED));
                   deltaX = e.getX() - currentPlate.getX();
                   deltaY = e.getY() - currentPlate.getY();
         public void mouseReleased(MouseEvent e){
              if(currentPlate!=null){
                   currentPlate.setBorder(BorderFactory.createEtchedBorder());
              currentPlate = null;
         public void mouseDragged(MouseEvent e) {
              Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
              scrollRectToVisible(r);
              if (currentPlate != null) {
                   //The user is dragging us, so scroll
    int x = (int) (e.getX() - deltaX);
    int y =     (int) (e.getY() - deltaY);
    currentPlate.setBorder(new BevelBorder(BevelBorder.RAISED));
                   currentPlate.setLocation(x, y);
                   currentPlate.repaint();
                   //repaint();
         public void mouseMoved(MouseEvent e) {
         public void paintComponent(Graphics g){
              Rectangle myBounds = getBounds();
         Graphics2D g2d = ( Graphics2D) g;
              Color startColor = new Color ( 158,158,199);
              Color endColor = new Color ( 192,192,192);
              GradientPaint gradient = new
              GradientPaint((int)myBounds.getX(),(int)myBounds.getY(),startColor, (int)(myBounds.getX()+myBounds.getWidth()),(int)myBounds.getY(), endColor);
              g2d.setPaint(gradient);
              g2d.fillRect(0, 0, (int)(myBounds.getX()+myBounds.getWidth()) , (int)(myBounds.getY()+myBounds.getHeight()));
         private int deltaX;
         private int deltaY;
    private Plate currentPlate;
    private Point origin;
    ====================
    here is how I put them togeather:
    JFrame myFrame = new JFrame();
              myPanel = new JPanel();
              myPanel.setLayout(null);
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              myFrame.setTitle("Bioinformatics");
              myFrame.setResizable(false);
              Dimension screenRes = Toolkit.getDefaultToolkit().getScreenSize();
              myScreenWidth = (int)screenRes.getWidth();
              myScreenHeight = (int)screenRes.getHeight();
              myFrame.setSize(((int)(myScreenWidth*.6)),((int)(myScreenHeight*.6)));
              myFrame.setLocationRelativeTo(null);
    JPanel toolBar = new JPanel();
    //     toolBar.setBackground(new Color ( 187,187,187));
         toolBar.setBounds(0, 0, ((int)(myScreenWidth*.6)), 35);
         FlowLayout theLayout = new FlowLayout(FlowLayout.LEFT);
         theLayout.setHgap(10);
         toolBar.setLayout(theLayout);
         toolBar.setLocation(0, 0);
         //Create the Workspace
         JScrollPane theWorkspace = new WorkspacePanel();
         theWorkspace.setLayout(null);
         theWorkspace.setBackground(new Color(210,210,210));
         theWorkspace.setBounds(0, 35, ((int)(myScreenWidth*.6)), ((int)(myScreenHeight*.6))-35);
         theWorkspace.setLocation(0, 35);
         //Set the Plate     
         Plate myPlate = new Plate();
         Insets insets = myPanel.getInsets();
    myPlate.setBounds(25, 25, 275, 175);
         myPlate.setLocation(25, 25);
         myPlate.setBorder(BorderFactory.createEtchedBorder());
         //Add Components
         theWorkspace.add(myPlate);
         myPanel.add(theWorkspace);
         myContainer.add(toolBar);
         myContainer.add(myPanel);
              myFrame.show();
    ============
    Sorry this is so sloppy with so much code.
    Any help would be VERY helpful
    Thanks

    I have to admit that I haven't actually read nor tested your code (without the code tags, it's hard) but have you had a look at the following article?
    http://www.javaworld.com/javaworld/jw-11-2001/jw-1130-jscroll.html

  • Can anyone help me, please(again)

    Hello :
    I am sorry that my massage is not clearly.
    Please run my coding first, and get some view from my coding. you can see somes buttons are on the frame.
    Now I want to click the number 20 of the buttons, and then I want to display a table which from the class TableRenderDemo to sit under the buttons. I added some coding for this problem in the class DrawClalendar, the coding is indicated by ??.
    but it still can not see the table apear on on the frame with the buttons.
    Can anyone help me to solve this problem.please
    Thanks
    *This program for add some buttons to JPanel
    *and add listeners to each button
    *I want to display myTable under the buttons,
    *when I click on number 20, but why it doesn't
    *work, The coding for these part are indicated by ??????????????
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel {
         private static DrawCalendar dC;
         private static TestMain tM;
         private static TableRenderDemo myTable;
         private static GridLayout gL;
         private static final int nlen = 35;
        private static String names[] = new String[nlen];
        private static JButton buttons[] = new JButton[nlen];
         public DrawCalendar(){
              gL=new GridLayout(5,7,0,0);
               setLayout(gL);
               assignValues();
               addJButton();
               registerListener();
        //assign values to each button
           private void assignValues(){
              names = new String[35];
             for(int i = 0; i < names.length; i++)
                names[i] = Integer.toString(i + 1);
         //create buttons and add them to Jpanel
         private void addJButton(){
              buttons=new JButton[names.length];
              for (int i=0; i<names.length; i++){
                   buttons=new JButton(names[i]);
         buttons[i].setBorder(null);
         buttons[i].setBackground(Color.white);
         buttons[i].setFont(new Font ("Palatino", 0,8));
    add(buttons[i]);
    //add listeners to each button
    private void registerListener(){
         for(int i=0; i<35; i++)
              buttons[i].addActionListener(new EventHandler());          
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
    private class EventHandler implements ActionListener{
         public void actionPerformed(ActionEvent e){
         for(int i=0; i<35; i++){
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
         if(i==20){  //???????????               
              tM=new TestMain(); //???????
              tM.c.removeAll(); //??????
              tM.c.add(dC); //???????
              tM.c.add(myTable); //????
              tM.validate();
         if(e.getSource()==buttons[i]){
         System.out.println("testing " + names[i]);
         break;
    *This program create a table with some data
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableRenderDemo extends JScrollPane {
    private boolean DEBUG = true;
    public TableRenderDemo() {
    // super("TableRenderDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
    //Create the scroll pane and add the table to it.
    setViewportView(table);
    //Set up column sizes.
    initColumnSizes(table, myModel);
    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table.getColumnModel().getColumn(2));
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table, MyTableModel model) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    try {
    comp = column.getHeaderRenderer().
    getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    } catch (NullPointerException e) {
    System.err.println("Null pointer exception!");
    System.err.println(" getHeaderRenderer returns null in 1.3.");
    System.err.println(" The replacement is getDefaultRenderer.");
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues[i],
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary ", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableRenderDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    *This program for add some buttons and a table on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class TestMain extends JFrame{
    private static TableRenderDemo tRD;
         private static TestMain tM;
    protected static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         setSize(800,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GridLayout(3,1));
    tRD=new TableRenderDemo();
    dC=new DrawCalendar();
    addItems();//add Buttons to JFrame
    private void addItems(){
         c.add(dC); //add Buttons to JFrame
         //c.add(tRD); //add Table to JFrame     

    I think this is what you are trying to do. Your code was not very clear so I wrote my own:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    public class TableButtons extends JFrame implements ActionListener
         Component southComponent;
        public TableButtons()
              JPanel buttons = new JPanel();
              buttons.setLayout( new GridLayout(5, 7) );
              Dimension buttonSize = new Dimension(20, 20);
              for (int j = 0; j < 35; j++)
                   // this is a trick to convert an integer to a string
                   String label = "" + (j + 1);
                   JButton button = new JButton( label );
                   button.setBorder( null );
                   button.setBackground( Color.white );
                   button.setPreferredSize( buttonSize );
                   button.addActionListener( this );
                   buttons.add(button);
              getContentPane().add(buttons, BorderLayout.NORTH);
         public void actionPerformed(ActionEvent e)
              JButton button = (JButton)e.getSource();
              String command = button.getActionCommand();
              if (command.equals("20"))
                   displayTable();
              else
                   System.out.println("Button " + command + " pressed");
                   if (southComponent != null)
                        getContentPane().remove( southComponent );
                        validate();
                        pack();
                        southComponent = null;
         private void displayTable()
            String[] columnNames = {"Student#", "Student Name", "Gender", "Grade", "Average"};
            Object[][] data =
                {new Integer(1), "Bob",   "M", "A", new Double(85.5) },
                {new Integer(2), "Carol", "F", "B", new Double(77.7) },
                {new Integer(3), "Ted",   "M", "C", new Double(66.6) },
                {new Integer(4), "Alice", "F", "D", new Double(55.5) }
            JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane= new JScrollPane( table );
            getContentPane().add(scrollPane, BorderLayout.SOUTH);
            validate();
            pack();
            southComponent = scrollPane;
        public static void main(String[] args)
            TableButtons frame = new TableButtons();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Can anyone help me, please

    Hello again:
    Please run my coding first, and get some view from my coding.
    I want to add a table(it is from TableRenderDemo) to a JFrame when I click on the button(from DrawCalendar) of the numer 20, and I want the table disply under the buttons(from DrawCalendar), and the table & buttons all appear on the frame. I added some code for this problem(in the EventHander of the DrawCalendar class), but I do
    not known why it can not work.Please help me to solve this problem.
    Can anyone help me, please.
    Thanks.
    *This program for add some buttons to JPanel
    *and add listeners to each button
    *I want to display myTable under the buttons,
    *when I click on number 20, but why it doesn't
    *work, The coding for these part are indicated by ??????????????
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel {
         private static DrawCalendar dC;
         private static TestMain tM;
         private static TableRenderDemo myTable;
         private static GridLayout gL;
         private static final int nlen = 35;
        private static String names[] = new String[nlen];
        private static JButton buttons[] = new JButton[nlen];
         public DrawCalendar(){
              gL=new GridLayout(5,7,0,0);
               setLayout(gL);
               assignValues();
               addJButton();
               registerListener();
        //assign values to each button
           private void assignValues(){
              names = new String[35];
             for(int i = 0; i < names.length; i++)
                names[i] = Integer.toString(i + 1);
         //create buttons and add them to Jpanel
         private void addJButton(){
              buttons=new JButton[names.length];
              for (int i=0; i<names.length; i++){
                   buttons=new JButton(names[i]);
         buttons[i].setBorder(null);
         buttons[i].setBackground(Color.white);
         buttons[i].setFont(new Font ("Palatino", 0,8));
    add(buttons[i]);
    //add listeners to each button
    private void registerListener(){
         for(int i=0; i<35; i++)
              buttons[i].addActionListener(new EventHandler());          
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
    private class EventHandler implements ActionListener{
         public void actionPerformed(ActionEvent e){
         for(int i=0; i<35; i++){
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
         if(i==20){  //???????????               
              tM=new TestMain(); //???????
              tM.c.removeAll(); //??????
              tM.c.add(dC); //???????
              tM.c.add(myTable); //????
              tM.validate();
         if(e.getSource()==buttons[i]){
         System.out.println("testing " + names[i]);
         break;
    *This program create a table with some data
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableRenderDemo extends JScrollPane {
    private boolean DEBUG = true;
    public TableRenderDemo() {
    // super("TableRenderDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
    //Create the scroll pane and add the table to it.
    setViewportView(table);
    //Set up column sizes.
    initColumnSizes(table, myModel);
    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table.getColumnModel().getColumn(2));
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table, MyTableModel model) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    try {
    comp = column.getHeaderRenderer().
    getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    } catch (NullPointerException e) {
    System.err.println("Null pointer exception!");
    System.err.println(" getHeaderRenderer returns null in 1.3.");
    System.err.println(" The replacement is getDefaultRenderer.");
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues[i],
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary ", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableRenderDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    *This program for add some buttons and a table on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class TestMain extends JFrame{
    private static TableRenderDemo tRD;
         private static TestMain tM;
    protected static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         setSize(800,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GridLayout(3,1));
    tRD=new TableRenderDemo();
    dC=new DrawCalendar();
    addItems();//add Buttons to JFrame
    private void addItems(){
         c.add(dC); //add Buttons to JFrame
         //c.add(tRD); //add Table to JFrame     

    Click Here and follow the steps to configure your Linksys Router with Version FIOS.

  • Need Help: JTable POP up menu in a CellEditor to display on a right click

    This was from a previous post:
    I am trying to make a POP menu in a JTextComponent that has a assigned JEditorPane for a HTMLDocument to make use of the HTMLEditorKit to allow modifying HTML by the POP up menu.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import javax.swing.text.html.*;
    import javax.swing.undo.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class SimpleTableDemo extends JFrame {
        public SimpleTableDemo() throws Exception {
            final JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            TableColumn fileColumn = table.getColumnModel().getColumn(2);
            FileTableCellEditor editor = new FileTableCellEditor();
            fileColumn.setCellRenderer(editor);
            fileColumn.setCellEditor(editor);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
                table.setRowHeight(100);
            public static void main(String[] args) throws Exception {
                SimpleTableDemo frame = new SimpleTableDemo();
                frame.pack();
                frame.setVisible(true);
            class MyTableModel extends AbstractTableModel {
                String[] columnNames = {"First Name","Last Name","HTML File"};
                public Object[][] data;
                MyTableModel() throws Exception
                    data = createArray();
                private Object[][] createArray() throws Exception
                    Object[][] data = {{"One", "Andrews", createDoc("file1.html")}
                return data;
                private Document createDoc(String url) throws Exception
                    File file = new File(url);
                    URL baseURL = file.toURL();
                    InputStream in = baseURL.openStream();
                    InputStreamReader r = new InputStreamReader(filterTag(in));
                    HTMLEditorKit kit = new HTMLEditorKit();
                Document doc = kit.createDefaultDocument();
                kit.read(r,doc,0);
                return doc;
                } // workaround for HTMLEditorKit.Parser, cant deal with "content-encoding"
                private InputStream filterTag(InputStream in) throws IOException {
                    DataInputStream dins = new DataInputStream( in);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                    while (din.available() > 0) {
                    String line = din.readLine();
                    String lline = line.toLowerCase();
                    if (0 <= lline.indexOf("<meta ")) // skip meta tags
                    continue;
                    bos.write( line.getBytes());
                    din.close();
                    return new ByteArrayInputStream( bos.toByteArray());
                public int getColumnCount() {
                    return columnNames.length;
                public int getRowCount() {
                    return data.length;
                public String getColumnName(int col) {
                    return columnNames[col];
                public Object getValueAt(int row, int col) {
                    return data[row][col];
                public Class getColumnClass(int c) {
                    return getValueAt(0, c).getClass();
                public boolean isCellEditable(int row, int col) {
                if (col >< 1) {
                    return false;
                } else {
                    return true;
    public class FileTableCellEditor extends JScrollPane implements TableCellEditor , TableCellRenderer
        public JTextComponent jtext;
        JEditorPane editor;
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();;
        private EventListenerList listenerList = new EventListenerList();
        private ChangeEvent event = new ChangeEvent(this);
        public FileTableCellEditor()
        editor = new JEditorPane();
        editor.setContentType("text/html");
        doc=new HTMLDocument();
        editor.addMouseListener(new MouseHandler());
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        editor.setEditable(true);
        editor.setCaretColor(Color.RED);
        getViewport().setView(editor);
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
            // System.out.println("has focus: "+hasFocus+", isSelected: "+isSelected);
            if (isSelected)
            table.editCellAt(row,column);
        table.editCellAt(row,column);
        return getTableCellEditorComponent(table,value,isSelected, row, column);
        public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column)
        editor.setDocument((Document)value);
        return this;
        public boolean isCellEditable(EventObject anEvent)
        { return true;
        public boolean shouldSelectCell(EventObject anEvent)
        { return true;
        public void cancelCellEditing()
        { fireEditingStopped();
        public boolean stopCellEditing()
        { return true;
        public Object getCellEditorValue()
        { return null;
        public void addCellEditorListener(CellEditorListener l)
        { listenerList.add(CellEditorListener.class, l);
        public void removeCellEditorListener(CellEditorListener l)
        { listenerList.remove(CellEditorListener.class, l);
        protected void fireEditingStopped()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingStopped(event);
        protected void fireEditingCanceled()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingCanceled(event);
            ///////////createPopupMenu///////////////
            protected JPopupMenu createPopupMenu()
            JPopupMenu popup =new JPopupMenu();
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.cutAction)).setAccelerator(null);
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.copyAction)).setAccelerator(null);
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.pasteAction)).setAccelerator(null);
            popup.addSeparator();
            popup.add(getTextComponent().getActionMap().get("font-bold"));
            popup.add(getTextComponent().getActionMap().get("font-italic"));
            popup.add(getTextComponent().getActionMap().get("font-underline"));
            //popup.add(getTextComponent().getActionMap().get("break"));
            return popup;
        public JTextComponent getTextComponent()
             return jtext;
        protected class MouseHandler extends MouseAdapter{
           public void mouseReleased(MouseEvent me){
               if(me.getButton()==MouseEvent.BUTTON3){
               Point p=me.getPoint();
               createPopupMenu().show((Component)me.getSource(),p.x,p.y);
    }

    I got the pop up to work, I had to go back to and add a createActionTable editor that is a JEditorPane, vs the JTextComponent!
    Here is the latest version:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.HashMap;
    import javax.swing.*;
    import javax.swing.undo.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import javax.swing.text.html.*;
    import javax.swing.undo.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class SimpleTableDemo extends JFrame {
        public SimpleTableDemo() throws Exception {
            final JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            TableColumn fileColumn = table.getColumnModel().getColumn(2);
            FileTableCellEditor editor = new FileTableCellEditor();
            fileColumn.setCellRenderer(editor);
            fileColumn.setCellEditor(editor);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
                table.setRowHeight(100);
            public static void main(String[] args) throws Exception {
                SimpleTableDemo frame = new SimpleTableDemo();
                frame.pack();
                frame.setVisible(true);
            class MyTableModel extends AbstractTableModel {
                String[] columnNames = {"First Name","Last Name","HTML File"};
                public Object[][] data;
                MyTableModel() throws Exception
                    data = createArray();
                private Object[][] createArray() throws Exception
                    Object[][] data = {{"One", "Andrews", createDoc("file1.html")}
                return data;
                private Document createDoc(String url) throws Exception
                    File file = new File(url);
                    URL baseURL = file.toURL();
                    InputStream in = baseURL.openStream();
                    InputStreamReader r = new InputStreamReader(filterTag(in));
                    HTMLEditorKit kit = new HTMLEditorKit();
                Document doc = kit.createDefaultDocument();
                kit.read(r,doc,0);
                return doc;
                } // workaround for HTMLEditorKit.Parser, cant deal with "content-encoding"
                private InputStream filterTag(InputStream in) throws IOException {
                    DataInputStream dins = new DataInputStream( in);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                    while (din.available() > 0) {
                    String line = din.readLine();
                    String lline = line.toLowerCase();
                    if (0 <= lline.indexOf("<meta ")) // skip meta tags
                    continue;
                    bos.write( line.getBytes());
                    din.close();
                    return new ByteArrayInputStream( bos.toByteArray());
                public int getColumnCount() {
                    return columnNames.length;
                public int getRowCount() {
                    return data.length;
                public String getColumnName(int col) {
                    return columnNames[col];
                public Object getValueAt(int row, int col) {
                    return data[row][col];
                public Class getColumnClass(int c) {
                    return getValueAt(0, c).getClass();
                public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
    public class FileTableCellEditor extends JScrollPane implements TableCellEditor , TableCellRenderer
        JEditorPane editor = new JEditorPane();
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();;
        private EventListenerList listenerList = new EventListenerList();
        private ChangeEvent event = new ChangeEvent(this);
        HashMap<Object, Action> actions;
        public FileTableCellEditor()
        getContentPane();
        editor.setContentType("text/html");
        doc=new HTMLDocument();
        editor.addMouseListener(new MouseHandler());
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        editor.setEditable(true);
        editor.setCaretColor(Color.RED);
        getViewport().setView(editor);
        createActionTable(editor);
        makeActionsPretty();
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public void makeActionsPretty(){
             Action a;
                      a=editor.getActionMap().get(HTMLEditorKit.cutAction);
                      a.putValue(Action.SHORT_DESCRIPTION,"Cut");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('X',Event.CTRL_MASK));
                      a=editor.getActionMap().get(HTMLEditorKit.copyAction);
                      a.putValue(Action.NAME,"Copy");
                      a.putValue(Action.SHORT_DESCRIPTION,"Copy");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('C',Event.CTRL_MASK));
                      a=editor.getActionMap().get(HTMLEditorKit.pasteAction);
                      a.putValue(Action.NAME,"Paste");
                      a.putValue(Action.SHORT_DESCRIPTION,"Paste");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('V',Event.CTRL_MASK));
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
            if (isSelected)
            table.editCellAt(row,column);
        table.editCellAt(row,column);
        return getTableCellEditorComponent(table,value,isSelected, row, column);
        public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column)
        editor.setDocument((Document)value);
        return this;
        public boolean isCellEditable(EventObject anEvent)
        { return true;
        public boolean shouldSelectCell(EventObject anEvent)
        { return true;
        public void cancelCellEditing()
        { fireEditingStopped();
        public boolean stopCellEditing()
        { return true;
        public Object getCellEditorValue()
        { return null;
        public void addCellEditorListener(CellEditorListener l)
        { listenerList.add(CellEditorListener.class, l);
        public void removeCellEditorListener(CellEditorListener l)
        { listenerList.remove(CellEditorListener.class, l);
        protected void fireEditingStopped()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingStopped(event);
        protected JPopupMenu createPopupMenu()
            JPopupMenu popup =new JPopupMenu();
            popup.add(getActionByName(DefaultEditorKit.cutAction));
            return popup;
        protected class MouseHandler extends MouseAdapter{
           public void mouseReleased(MouseEvent me){
               if(me.getButton()==MouseEvent.BUTTON3){
               Point p=me.getPoint();
               createPopupMenu().show((Component)me.getSource(),p.x,p.y);
        private void createActionTable(JTextComponent textComponent) {
            actions = new HashMap<Object, Action>();
            Action[] actionsArray = textComponent.getActions();
            for (int i = 0; i < actionsArray.length; i++) {
                Action a = actionsArray;
    actions.put(a.getValue(Action.NAME), a);
    private Action getActionByName(String name) {
    return actions.get(name);

Maybe you are looking for