Repainting a JScrollPane

Hi everyone,
I've search the forum for an answer to this question but I can't seem to find the solution to my problem.
I have a loop which updates the contents of a JTextArea with some text. The JtextArea is inside a JScrollPane. When I add text to the JTextArea i used the .paintImmediately method to paint the string in the JTextArea so it is visible during execution (otherwise the text is not displayed until the loop has finished and the GUI is repainted).
However, once the text has filled more than the visible rows, the JScrollPane doesn't scoll down so that you can see the new text., in fact, no scroll bar is displayed even though there is more text than is visible in the JTextArea. Only when the loop has finsihed executing does the scrollbar become visible. Does anyone know how to get around this problem so that each time a new line of text is added the scrollpane will automatically scroll to the bottom?
I've made this example class to demonstrate my problem:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TextArea extends JFrame {
    public static Container contentPane;
    public static JTextArea bodyField;
    public static JScrollPane bodyScroll;
    public static JButton generate;
    public static void main (String args[])
        TextArea textArea = new TextArea();
        textArea.pack();
        textArea.show();
    public TextArea()
         * Button
        JPanel generatePanel = new JPanel();
        generatePanel.setLayout(new BoxLayout(generatePanel, BoxLayout.X_AXIS));
        generatePanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        generatePanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
        generate = new JButton( "Generate" );
        generate.setMnemonic('G');
        generate.setToolTipText("Generare the link pages for your website");
        generate.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                Update update = new Update();
                update.run();
        generatePanel.add( generate );
         * Body
        JPanel bodyPanel = new JPanel();
        bodyPanel.setLayout(new BoxLayout(bodyPanel, BoxLayout.X_AXIS));
        bodyPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        bodyPanel.setPreferredSize( new Dimension(700, 600) );
        bodyPanel.setMaximumSize( bodyPanel.getPreferredSize() );
        bodyField = new JTextArea();
        bodyScroll = new JScrollPane( bodyField );
        bodyScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
        bodyPanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
        bodyPanel.add( bodyScroll );
        JPanel mainMainPanel = new JPanel();
        mainMainPanel.setLayout(new BoxLayout(mainMainPanel, BoxLayout.Y_AXIS));
        mainMainPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        mainMainPanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
        mainMainPanel.add( generatePanel );
        mainMainPanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
        mainMainPanel.add( bodyPanel );
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
        mainPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        mainPanel.add( Box.createRigidArea(new Dimension(5,0)) );
        mainPanel.add( mainMainPanel );
        contentPane = this.getContentPane();
        contentPane.add( new JScrollPane( mainPanel ) );
    static class Update extends Thread
        public void run()
            for ( int i = 0; i < 50; i++ )
                bodyField.append( i + "\n" );
                bodyField.paintImmediately( bodyField.getBounds() );
                bodyScroll.paintImmediately( bodyScroll.getBounds() );
}

sorry, I posted this again by accident. Please don't reply to it

Similar Messages

  • JScrollPane wont scroll .. pls help

    hi to all,
    I have a scrollpane that i am displaying a graph in, and they will be large graphs, 10000 nodes with about cardinality 10 for each node.
    I can generate the graph output no problems but my scrollbars dont allow me to scroll the pane, and i cant figure out why.
    I'm assuming that i should be doing something with the viewport once i add the graph, but i dont know what.
    can anyone pls help me,
    also can anyone suggest how i go about zooming in and out. im thinking its just resizng the viewport, but i need to work out why i cant scroll before i tackle that.
    package graphappz.ui;
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import graphappz.graph.Graph;
    import java.util.Iterator;
    import graphappz.graph.Vertex;
    import graphappz.graph.Edge;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class GraphWindow
        extends JPanel {
      JEditorPane graphWindow;
      JScrollPane graphView;
      Dimension d = new Dimension();
      Point2D p = null;
      GraphViewer viewer;
      public GraphWindow() {
        graphWindow = new JEditorPane();
        graphWindow.setText("");
        viewer = new GraphViewer();
        graphView = new JScrollPane(viewer);
        graphView.setHorizontalScrollBarPolicy(JScrollPane.
                                               HORIZONTAL_SCROLLBAR_ALWAYS);
        graphView.setVerticalScrollBarPolicy(JScrollPane.
                                             VERTICAL_SCROLLBAR_ALWAYS);
        graphView.getViewport().setBackground(Color.white);
        graphView.setBorder(BorderFactory.createEtchedBorder());
        graphView.setToolTipText("Graph Output Display Window");
        repaint();
      public JScrollPane getGraphView() {
        return this.graphView;
      public Dimension getSize() {
        graphView.setPreferredSize(new Dimension(520, 440));
        return graphView.getPreferredSize();
      class GraphViewer
          extends JPanel {
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          int nodeWidth = 20;
          int nodeHeight = 20;
          if (graphappz.Main.graph != null) {
            Graph graph = graphappz.Main.graph;
            Iterator iter = graph.edgeIter();
            while (iter.hasNext()) {
              Edge e = (Edge) iter.next();
              Vertex v_0 = e.getv0();
              Vertex v_1 = e.getv1();
              if ( ( (v_0.getLayoutPosition() != null) ||
                    (v_1.getLayoutPosition() != null))) {
                Point2D.Double pos_0 = v_0.getLayoutPosition();
                Point2D.Double pos_1 = v_1.getLayoutPosition();
                // draw the edge
                g.setColor(Color.red);
                g.drawLine( (int) pos_0.x + (nodeWidth / 2),
                           (int) pos_0.y + (nodeHeight / 2),
                           (int) pos_1.x + (nodeWidth / 2),
                           (int) pos_1.y + (nodeHeight / 2));
                // draw the first node
                g.setColor(Color.blue);
                g.drawOval( (int) pos_0.x, (int) pos_0.y, nodeWidth, nodeHeight);
                g.fillOval( (int) pos_0.x, (int) pos_0.y, nodeWidth, nodeHeight);
                // draw the second node
                g.setColor(Color.blue);
                g.drawOval( (int) pos_1.x, (int) pos_1.y, nodeWidth, nodeHeight);
                g.fillOval( (int) pos_1.x, (int) pos_1.y, nodeWidth, nodeHeight);
                // draw the edge
                g.setColor(Color.black);
                g.drawString(v_0.getReference() + "", (int) pos_0.x + 5,
                             (int) pos_0.y + 14);
          else {
            graphappz.util.Debug.debugText.append("\n graph is null, can't draw it");
            //TODO: show new Alert_Dialog
        public GraphViewer() {
          this.setBackground(Color.white);
          this.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {}
            public void mousePressed(MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            public void mouseExited(MouseEvent e) {}
    }

    Scrollbars will appear when the preferred size of the panel is greater than the preferred size of the scrollpane.
    When you add components (JButton, JTextField...) to a panel then the preferred size can be calculated by the layout manager.
    When you draw on a panel the layout manager has no idea what the size of you panel is so you need to set the preferrred size yourself:
    panel.setPreferredSize(...);

  • Problem in refreshing display in TabbedPane

    Dear all,
    I have designed a very typical java application using JFrame, JTabbedPane inside JFrame, JPanel inside JTabbedPane.
    Inside Jpanel I have added JTextField, JButton and JScrollPane+JTable. Basically a value is set in JTextField and when clicking on Jbutton the JScrollPane should be updated with a list coming from database.
    When I update value of JTextField (with setText) and then call JTextField.repaint(), the value is correctly displayed on the sreen.
    When I update value of data in Jtable and then call JTable.repaint() and JScrollPane.repaint(), the values are correctly displayed on the sreen when using JRE 1.4 but nothing is displayed when using JRE1.3.1.
    Do you have any idea of why it doesn't work (I do not wish to migrate in version 1.4) ?
    Thank you.
    Thierry

    Calling repaint shouldn't be necessary, since your components call revalidate ()/repaint () themselves when their models have changed.
    Kind regards,
      Levi

  • Problems updating gui in JApplet

    Hi,
    I have a JApplet with a JPanel with another JPanel ? TreePanel ? containing a JScrollPane with a JTree.
    When init() is run in MyApplet, treePanel is initiated with a JTree, with test data hardcoded in TreePanel?s constructor. I want the tree to change every time a thread loops, by calling method treePanel.updateResultTree(root) from the thread, with a new root. To test this, I have hardcoded a new tree content in the thread to pass to the TreePanel. In method updateResultTree(root), I remove the existing JTree from JScrollPane and add a new JTree to it, with the new root. Then I repaint the JScrollPane.
    When I run the applet, the initial tree is displayed, but it is not updated with the new JTree for the first thread loop as expected. How is the gui in a JApplet refreshed/updated?? Will SwingWoker update the gui automatically without forcing repaint()?
    Please help, I'm so stuck! Thanks in advance!
    MyApplet
    public class MyApplet extends JApplet {
       private TreePanel _treePanel;
       private UpdateHandler _updateHandler;
       private Thread _updateThread;
       public void init() {
          super.init();
          _treePanel = new TreePanel();
          // Updating thread
          _updateHandler = new UpdateHandler();
          _updateThread = new Thread(_updateHandler);
          _updateThread.start();
          // Initialize gui
          JPanel bigPanel = new JPanel();
          bigPanel.setLayout(new BoxLayout(bigPanel, BoxLayout.X_AXIS));          
          getContentPane().add(bigPanel, BorderLayout.CENTER);   
          _treePanel = new JPanel();
          bigPanels.add(_treePanel);
       // Updates the GUI every X seconds
       private class UpdateHandler implements Runnable {
          public final static int UPDATE_INTERVAL = 10;
          public UpdateHandler() { }
          public void run() {
             try {
                _displayResults();
             } catch (InterruptedException ie) {
       private synchronized void _ displayResults () throws InterruptedException {
          while(true) {
             // Resolve a new DefaultMutableTreeNode object as root to be updated in GUI
             // (For test)
             DefaultMutableTreeNode root = new DefaultMutableTreeNode(new Result("Root"));
             DefaultMutableTreeNode child_1 = new DefaultMutableTreeNode(new Result("Result X"));
             DefaultMutableTreeNode child_2 = new DefaultMutableTreeNode(new Result("Result Y"));
             DefaultMutableTreeNode child_11 = new DefaultMutableTreeNode(new Result("Result X1"));
             root.add(child_1);
             root.add(child_2);
             child_1.add(child_11);
             // Update the GUI 
             _treePanel.updateTree(root);
             wait(UPDATE_INTERVAL*1000);
    }TreePanel
    public class TreePanel extends JPanel {
       private JScrollPanel _treeSrcoll;
       private JTree _tree;
       TreePanel() {
          super();
          // Test tree, displayed in applet?s init()
          DefaultMutableTreeNode root = new DefaultMutableTreeNode (new Result("Root"));
          DefaultMutableTreeNode child_1 = new DefaultMutableTreeNode (new Result("Result 1"));
          DefaultMutableTreeNode child_2 = new DefaultMutableTreeNode (new Result("Result 2"));
          DefaultMutableTreeNode child_11 = new DefaultMutableTreeNode (new Result("Result 4"));
          DefaultMutableTreeNode child_12 = new DefaultMutableTreeNode (new Result("Result 5"));   
          root.add(child_1);
          root.add(child_2);
          child_1.add(child_11);
          child_1.add(child_12);
          _tree = new JTree(root);
          _treeScroll = new JScrollPane(_tree);
          add(_treeScroll, BorderLayout.CENTER);
       public void updateTree(DefaultMutableTreeNode  theRoot) {
          if (theRoot != null) {
             if (_tree!= null) {
                _treeScroll.remove(_tree);
             _ tree = new QCTree(root);     
             _treeScroll.add(_tree);
          } else {
             JLabel label = new JLabel("No result tree structure is available");
            _treeScroll.add(label);
         _treeScroll.repaint();
    }Result
    public class Result {
       private String _name; 
       public Result(String name) {
          _name = name;
       public String toString() {
          return _name;

    I found the error:
    I need to use
    treeScroll.getViewPort().add(tree);
    and
    treeScroll.getViewPort().remove(tree);

  • Why Can't we have JCanvas for developing Custom LightWeight Components?

    Well!
    I am Sandeep - [email protected]
    I am developing a application for showing images
    and Every time I read a new Image ,
    I have to resize the Window 'MANUALLY'
    so that it appears .
    I am showing it on JPanel which is in JScrollPane
    I have tried all invalidate - validate() and repaint()
    on JScrollPane and JPanel also .
    I tried shuffling size of main JFrame also but failed.
    I have resize the JFrame manually to make Inage
    Appear.
    So I created new Object of 'myclass extends JPanel'
    and put it in JScrollPane as setViewportView(...)
    well I dont like to create new object of my
    JPanel-subclass.
    Can u help me.
    Also I tried to use Canvas but as my application
    is in SWING , it overlaps so i want some thing like
    JCanvas ?
    Do we Have It?

    if you're calling the methods on Toolkit to load the image, pass in the component as the ImageObserver. This way when the image is finished loading, it will repaint itself.

  • How to repaint a JTextArea inside a JScrollPane

    I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
    The following code doesnt run correctly.
    ((JTextArea)Destino).append('\n' + Mens);
    Destino.revalidate();
    Destino.paint(Destino.getGraphics());
    I tried also:
    Destino.repaint();
    Thanks a lot in advance

    Correct me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
    If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also.

  • How to repaint a table after a change in data?????????????3F????????

    hi there
    i have a table which contains some values. i am able to delete a row from it. but i need to repaint the table, so that the change can be shown. the table is contained in a scrollPane which is contained in a Pane. i understand that to repaint, i need to call revalidate() or repaint() on a component. in my case, which component should i call the function? or it is done in different way? thank you.
    my code..
    JTable inTable = new JTable(rowDataIn, columName);
    JScrollPane spIn = new JScrollPane(inTable);
    spIn.setPreferredSize(new Dimension(650,270));
    JPanel inPane = new JPanel();
    inPane.add(spIn);
    ..2C270));
    JPanel inPane = new JPanel();
    inPane.add(spIn);
    ..

    After ur modifications done in a JTable, I think u need to call this method.
    fireTableChanged(new TableModelEvent(this)) ;
    Here this is a instance of myModel object which extends AbstractTableModel.
    Hope it helps.

  • How to repaint a table after a change in data?????????????

    hi there
    i have a table which contains some values. i am able to delete a row from it. but i need to repaint the table, so that the change can be shown. the table is contained in a scrollPane which is contained in a Pane. i understand that to repaint, i need to call revalidate() or repaint() on a component. in my case, which component should i call the function? or it is done in different way? thank you.
    my code..
    JTable inTable = new JTable(rowDataIn, columName);
    JScrollPane spIn = new JScrollPane(inTable);
    spIn.setPreferredSize(new Dimension(650,270));
    JPanel inPane = new JPanel();
    inPane.add(spIn);
    ..

    After ur modifications done in a JTable, I think u need to call this method.
    fireTableChanged(new TableModelEvent(this)) ;
    Here this is a instance of myModel object which extends AbstractTableModel.
    Hope it helps.

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

  • Zooming an image and scrolling it using a JScrollPane

    Hi all, I know this is one of the most common problems in this forum but i cant get any of the replys to work in my code.
    The problem:
    I create an image with varying pixel colors depending on the value obtained from an AbstractTableModel and display it to the screen.
    I then wish to be able to zoom in on the image and make it scrollable as required.
    At the minute the scrolling method is working but only when i resize or un-focus and re-focus the JInternalFrame. Ive tried calling revalidate (and various other options) on the JScrollPane within the paintComponents(Graphics g) method but all to no avail.
    Has anyone out there any ideas cause this is melting my head!
    Heres the code im using (instance is called and added to a JDesktopPane):
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.AffineTransform;
    import uk.ac.qub.mvda.gui.MVDATableModel;
    import uk.ac.qub.mvda.utils.MVDAConstants;
    public class HCLSpectrumPlot extends JInternalFrame implements MVDAConstants
      AbstractAction zoomInAction = new ZoomInAction();
      AbstractAction zoomOutAction = new ZoomOutAction();
      double zoomFactorX = 1.0;
      double zoomFactorY = 1.0;
      private AffineTransform theTransform;
      private ImagePanel imageViewerPanel;
      private JScrollPane imageViewerScroller;
      public HCLSpectrumPlot(String title, MVDATableModel model)
        super(title, true, true, true, true);
        int imageHeight_numOfRows = model.getRowCount();
        int imageWidth_numOfCols = model.getColumnCount();
        int numberOfColourBands = 3;
        double maxValueInTable = 0;
        double[][] ValueAtTablePosition =
            new double[imageHeight_numOfRows][imageWidth_numOfCols];
        for(int i=0; i<imageHeight_numOfRows; i++)
          for(int j=0; j<imageWidth_numOfCols; j++)
         ValueAtTablePosition[i][j] = ((Double)model.getValueAt
                 (i,j)).doubleValue();
        for(int i=0; i<imageHeight_numOfRows; i++)
          for(int j=0; j<imageWidth_numOfCols; j++)
         if ( ValueAtTablePosition[i][j] > maxValueInTable)
           maxValueInTable = ValueAtTablePosition[i][j];
        BufferedImage newImage = new BufferedImage(imageWidth_numOfCols,
              imageHeight_numOfRows, BufferedImage.TYPE_3BYTE_BGR);
        WritableRaster newWritableImage = newImage.getRaster();
        int colourB;
        double pixelValue, cellValue, newPixelValue;
        for (int x = 0; x < imageHeight_numOfRows; x++)
          for (int y = 0; y < imageWidth_numOfCols; y++)
         colourB = 0;
         cellValue = ValueAtTablePosition[x][y];
         pixelValue = (1 - (cellValue / maxValueInTable)) * 767;
         pixelValue = pixelValue - 256;
         while (colourB < numberOfColourBands)
           if ( pixelValue < 0 )
             newPixelValue = 256 + pixelValue;
             newWritableImage.setSample(x, y, colourB, newPixelValue);
             colourB++;
                while ( colourB < numberOfColourBands )
               newWritableImage.setSample(x, y, colourB, 0);
               colourB++;
         else
           newWritableImage.setSample(x, y, colourB, 255);
         colourB++;
         pixelValue = pixelValue - 256;
          }//while
         }//for-y
        }//for-x
        imageViewerPanel = new ImagePanel(this, newImage);
        imageViewerScroller =     new JScrollPane(imageViewerPanel,
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                   JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(imageViewerScroller, BorderLayout.CENTER);
        JToolBar editTools = new JToolBar();
        editTools.setOrientation(JToolBar.VERTICAL);
        editTools.add(zoomInAction);
        editTools.add(zoomOutAction);
        this.getContentPane().add(editTools, BorderLayout.WEST);
        this.setVisible(true);
      class ImagePanel extends JPanel
        private int iWidth, iHeight;
        private int i=0;
        private BufferedImage bufferedImageToDisplay;
        private JInternalFrame parentFrame;
        public ImagePanel(JInternalFrame parent, BufferedImage image)
          super();
          parentFrame = parent;
          bufferedImageToDisplay = image;
          iWidth = bufferedImageToDisplay.getWidth();
          iHeight = bufferedImageToDisplay.getHeight();
          theTransform = new AffineTransform();
          //theTransform.setToScale(parent.getContentPane().getWidth(),
                                    parent.getContentPane().getHeight());
          this.setPreferredSize(new Dimension(iWidth, iHeight));
        }//Constructor
        public void paintComponent(Graphics g)
          super.paintComponent(g);
          ((Graphics2D)g).drawRenderedImage(bufferedImageToDisplay,
                                             theTransform);
          this.setPreferredSize(new Dimension((int)(iWidth*zoomFactorX),
                                          (int)(iHeight*zoomFactorY)));
        }//paintComponent
      }// end class ImagePanel
       * Class to handle a zoom in event
       * @author Ross McCaughrain
       * @version 1.0
      class ZoomInAction extends AbstractAction
       * Default Constructor.
      public ZoomInAction()
        super(null, new ImageIcon(HCLSpectrumPlot.class.getResource("../"+
                  MVDAConstants.PATH_TO_IMAGES + "ZoomIn24.gif")));
        this.putValue(Action.SHORT_DESCRIPTION,"Zooms In on the Image");
        this.setEnabled(true);
      public void actionPerformed(ActionEvent e)
        zoomFactorX += 0.5;
        zoomFactorY += 0.5;
        theTransform = AffineTransform.getScaleInstance(zoomFactorX,
                                                    zoomFactorY);
        repaint();
      // ZoomOut to be implemented
    }// end class HCLSpectrumPlotAll/any help greatly appreciated! thanks for your time.
    RossMcC

    Small mistake, the revalidate must be called on the panel not on the jsp.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class UsaZ extends JFrame 
         IPanel      panel = new IPanel();
         JScrollPane jsp   = new JScrollPane(panel);
    public UsaZ() 
         addWindowListener(new WindowAdapter()
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         setBackground(Color.lightGray);
         getContentPane().add("Center",jsp);
         setBounds(1,1,400,320);
         setVisible(true);
    public class IPanel extends JComponent
         Image  map;
         double zoom = 1;
         double iw;
         double ih;
    public IPanel()
         map = getToolkit().createImage("us.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(map,0);
         try {tracker.waitForID(0);}
         catch (InterruptedException e){}
         iw = map.getWidth(this);
         ih = map.getHeight(this);
         zoom(0);     
         addMouseListener(new MouseAdapter()     
         {     public void mouseReleased(MouseEvent m)
                   zoom(0.04);               
                   repaint();      
                   revalidate();
    public void zoom(double z)
         zoom = zoom + z;
         setPreferredSize(new Dimension((int)(iw*zoom)+2,(int)(ih*zoom)+2));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         g2.scale(zoom,zoom);
         g2.drawImage(map,1,1,null);
         g.drawRect(0,0,map.getWidth(this)+1,map.getHeight(this)+1);
    public static void main (String[] args) 
          new UsaZ();
    [/cdoe]
    Noah                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Changing Arrows and Color of a JScrollBar inside of a JScrollPane

    Hi. I can't believe this hasn't been asked and answered before but I can't find it in these forums if it has.
    I am trying to create a JScrollPane in a touchscreen based application - no mouse... The default scrollbar
    in my JScrollPane is too small for large fingers. I have successfully increased the size of the scrollbar
    to a usable size using: UIManager.put("scrollbar.width", 75).
    My next problem is two-fold.
    1) The arrows at top and bottom of the scrollbar are now heavily pixelated (i.e. jagged and blocky) and
    look like we zoomed in too much on a bitmap. How can I change these arrows to a graphic that is
    more related to the current size of my scrollbar?
    2) The color of the scrollbar is shades of 'baby blue'. My color scheme for my application is shades of
    beige or brown. This makes the scrollbar stand out like a sore thumb. How can I change the color
    of the scrollbar?
    Note: This is being coded in NetBeans 6.7.1 but I can't find any property in the visual editor that covers
    my problems.
    Also, I came across the UIManager.put("scrollbar.width", xx) from googling. Is there an official (complete)
    list of the properties available to the UIManager?
    Thanks

    To help out anyone who has been struggling with this as I have, here is the final solution we were able to use. We only needed to work with the vertical scroll bar, but it should be easy to work with now that a better part of the work is done. I do hope this is helpful.
         public ReportDisplayFrame()
              UIManager.put( "ScrollBar.width", 75);
              RDFScrollBarUI rdfScrlBarUI = new RDFScrollBarUI();
              rdfScrlBarUI.setButtonImageIcon( new ImageIcon( "C:/company/images/upArrow.jpg") , rdfScrlBarUI.NORTH);
              rdfScrlBarUI.setButtonImageIcon( new ImageIcon( "C:/company/images/downArrow.jpg") , rdfScrlBarUI.SOUTH);
              tempScrlBar = new JScrollBar();
              tempScrlBar.setBlockIncrement( 100);
              tempScrlBar.setUnitIncrement( 12);
              tempScrlBar.setUI( rdfScrlBarUI);
    // other constructor code //
              rdfScreenRedraw();
         private void rdfScreenRedraw()
              String methodName = "rdfScreenRedraw()";
              logger.log(Level.INFO, methodName + ": Revalidating: mainPanel Thread = ["+Thread.currentThread().getName()+"]");
              jPanelRpt.revalidate();
              jPanelRpt.repaint();
         class RDFScrollBarUI extends BasicScrollBarUI {
              private ImageIcon decImage = null;
              private ImageIcon incImage = null;
              public void setThumbColor(Color thumbColor) {
                   this.thumbColor = thumbColor;
              public void setThumbDarkShadowColor(Color thumbDarkShadowColor) {
                   this.thumbDarkShadowColor = thumbDarkShadowColor;
              public void setThumbHighlightColor(Color thumbHighlightColor) {
                   this.thumbHighlightColor = thumbHighlightColor;
              public void setThumbLightShadowColor(Color thumbLightShadowColor) {
                   this.thumbLightShadowColor = thumbLightShadowColor;
              public void setTrackColor(Color trackColor) {
                   this.trackColor = trackColor;
              public void setTrackHighlightColor(Color trackHighlightColor) {
                   this.trackHighlightColor = trackHighlightColor;
              public void setButtonImageIcon( ImageIcon theIcon, int orientation)
                   switch( orientation)
                        case NORTH:
                             decImage = theIcon;
                             break;
                        case SOUTH:
                             incImage = theIcon;
                             break;
                        case EAST:
              if (scrollbar.getComponentOrientation().isLeftToRight())
                                  decImage = theIcon;
                             else
                                  incImage = theIcon;
                             break;
                        case WEST:
              if (scrollbar.getComponentOrientation().isLeftToRight())
                                  incImage = theIcon;
                             else
                                  decImage = theIcon;
                             break;
              @Override
              protected JButton createDecreaseButton(int orientation) {
                   JButton button = null;
                   if ( decImage != null)
                        button = new JButton( decImage);
                   else
                        button = new BasicArrowButton(orientation);
                   button.setBackground( new Color( 180,180,130));
                   button.setForeground( new Color( 236,233,216));
                   return button;
              @Override
              protected JButton createIncreaseButton(int orientation) {
                   JButton button = null;
                   if ( incImage != null)
                        button = new JButton( incImage);
                   else
                        button = new BasicArrowButton(orientation);
                   button.setBackground( new Color( 180,180,130));
                   button.setForeground( new Color( 236,233,216));
                   return button;
         }

  • 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

  • How to keep a label at the left side of a JScrollPane

    Hi all
    I am essentially trying to make a text block that doesn't move as the scrollpane scrolls (horizontally in my case)
    Here's my code trying to do this simply using Graphics.drawString (not compilable - tell me if you need something that compiles):
              g.setFont(getTaskFont());
              g.setColor(getTaskLabelForeground());
              g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              JScrollPane sp = ComponentUtilities.getJScrollPaneAncester(this);
              for (int i = 0; i < tasks.size() - 1; i++) {
                   Task t = tasks.get(i + 1);
                   FontMetrics fm = g.getFontMetrics();
                   int y = i * (rowHeight + rowSpace) + fm.getAscent() + (rowHeight - fm.getHeight()) / 2;
                   int strlen = fm.stringWidth(t.getName().toUpperCase());
                   int start = getXLocationForTime(t.getStart());
                   int end = getXLocationForTime(t.getFinish());
                   int len = end - start;
                   int x = 0;
                   //System.out.println("task: " + t.getName());
                   if (strlen < len) {
                        x = Math.min(end + 5, Math.max(start + 3, sp.getHorizontalScrollBar().getValue()));
                   else {
                        x = end + 5;
                   g.drawString(t.getName().toUpperCase(), x, y);
              }Here's my code trying to do this using a JLabel
                   JScrollPane sp = ComponentUtilities.getJScrollPaneAncester(this);
                   int y = i * (rowHeight + rowSpace); //+ fm.getAscent() + (rowHeight - fm.getHeight()) / 2;
                   int strlen = fm.stringWidth(t.getName().toUpperCase());
                   int start = getXLocationForTime(t.getStart());
                   int end = getXLocationForTime(t.getFinish());
                   int len = end - start;
                   int x = 0;
                   //System.out.println("task: " + t.getName());
                   if (strlen < len) {
                        x = Math.min(end + 5, Math.max(start + 3, sp.getHorizontalScrollBar().getValue()));
                   else {
                        x = end + 5;
                   floaters.setLocation(x, y + (rowHeight - fm.getHeight()) / 4);
                   floaters[i].repaint();
    Both [i]almost work, but the scrolling is not smooth (blinks back & forth). It seemed like a double buffering problem, but when I added code to paint first to an image and then to screen the issue remained.
    I also tried adding labels to the JLayeredPane popup layer, but I this solution is problematic also, as labels start drawing all over the place. Plus, I'd rather not have to keep track of the labels and be repositioning them in the first place.
    Any advice on this is sincerely appreciated.
    Thanks!
    -Tom
    Anyone know how to fix this?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Darryl Burke wrote:
    a label at the left side of a JScrollPaneI take it <tt>setRowHeader</tt> / <tt>setRowHeaderView</tt> don't do what you want?
    dbThat's a very helpful suggestion, and I think would solve the problem as stated, however in reading your answer I see now that I didn't state my problem well, and that what I am trying to do is much more complex than I originally thought it was.
    Thanks tho, you have helped me gain clarity in what I am trying to do.

Maybe you are looking for