Scrollbar in awt

how to control scrolling of 50 textfields using independent scrollbar in AWT?

extend Panel
setlayout to GridLayout (dimensions how many components you want)
make an array of components.
if the scrollbar fires an adjustmentevent put the "right" components on your panel.
take care that you don't do any adding if you display the correct component anyway (scrollbars tend to fire more events then necessary)
i have done that and it works well but i fear i can't send you the code since i think its property of the company i work for. If you are desperate enough to buy the code mail me at [email protected] and i talk to my boss.

Similar Messages

  • Scrollbars and awt.List

    Hello,
    I'm a first year student form the Netherlands in software design. And as of this semester I'm getting Java (finally a new language to learn!). Everything has gone very smoothly, I was hoping of more of a challenge trying to learn it, but it goes very easily (maybe I shouldn't have programmed in C++ for 3 years :P).
    Though now I'm having a slight problem with my code. v _ v '
    My project has to be competly in awt widget's, and I thought I'd do something more than required (it would seem that my teachers expect me to ^ _ ^).
    In this list I'm required to use a fixed width font to "simulate" 2 panels (almost similar to the TableList in Swing) with a pipe ( | ) character as a line. It means that I need to cut off words that cross the boundry.
    The above (and the rest of the assignment) works perfectly (and I've done the actual required part in less than 30 minutes), but now I've come to want to add tool tips to all the elements.
    I've made a tooltip class (it works btw), but I need to get the item in the list my mouse is hovering over.
    I believe a row is 20 pixels high (or something like that), so I divide the y value (of the local mouse position) by 20 and use the integer part as the index.
    And here comes the problem.
    When the list scrolls then the method I described above won't work anymore.
    I think that my method is (atleast) similar as to what other programs do, save that it adds the scroll info as well.
    Now here's my real problem. I can't (or don't know how) to get the scrollbar info from the list. I know there's a handy function is Swing, but I'm only allowed to use awt.
    I've also read that the scrollbars are part of the peer's (native to the OS) so I can't access them.
    So my true question is, what (if any) event should I listen to, to get scroll movements (not mouse wheel scrolling)?
    And if there isn't any way to listen to the events, then do you have any idea how to tackle this problem?
    Thank you for your time,
    MLeoDaalder

    Showing me your misbehaving output is not helpful.
    I have successfully implemented what you are attempting, using Swing which I understand you cannot use but it should work the same way using AWT.
    My main class extends JFrame (you would extend Frame) and implements MouseMotionListener. The mouseMoved(MouseEvent evt) method in the main class updates the tool tip, based on the evt.getX() and evt.getY().
    I have a class (call it LCanvas) that extends JPanel (you would extend Panel) . The class adds a MouseMotionListener and has a paint(Graphics g) method that records the borders of each line that gets painted by g.drawString(String s, int x, int y). (Some of the painted lines may be outside of the displayed area.)
    When I construct LCanvas, I pass it the JFrame (you would use Frame) of the main class. So my contructor looks like:
    public LCanvas(JFrame f) {
    addMouseMotionListener((MouseMotionListener) f);
    Back in main(String [ ] args), I set up my scrollable window as:
    MainClass f = new MainClass();
    LCanvas lc = new LCanvas(f);
    JScrollPane sp = new JScrollPane(lc);
    content_pane.add(sp);
    I don't know how you are trying to implement this but you should be able to compare it to my implementation that works and, since you are such a clever guy, figure out what's going wrong.

  • Removing scrollbar from AWT List

    Hi,
    I have an instance of List on my screen. I noticed when I have more than one item on the list, it shows automatically a vertical and horizontal scrollbars.
    I have to disable scrollbars, but cannot find out if it is possible with AWT List or should I opt for a different Component than List.
    Could anyone give me a hand?
    Thank you,
    Caren

    List is what you want. Use this constructor...List(int, boolean). First argument is number of items to display in the list, second is if List is mulitle selection list. So for a normal list with 5 items do this:
    List myList = new List5, false);
    This should stop a scrollbar being put in (unless you add more than 5 items). If this doesn't work it's proably your layout manager set up.
    Hope this helps

  • AWT Scrollbar flickering on Windows

    I have a problem with AWT ScrollBar. On Windows, once I touch AWT scrollbar, they flickers until I touch other components. In addition, it leaves gray colors on thumbs. I am looking for a solution. I am considering custom widgets as a last resort. I tried Swing JScrollbar, but it does not mix with AWT frames. Note that the styles of Scrollbar is also classical ones, not XP-style!
    Anyone good sugestions?

    I should have written as "blinking". It's a bug Sun does not want to fix. I don't understand the reason. Swing is not an option as it will bring far more problems. If I change, I will change it to SWT or VC++.

  • Error Scrollbar AWT java.

    The "Scrollbar" not working properly, because the maximum value of the bar can not be accessed from visual part of the component. It can only be edited by their method "setValue ()."
    Could you please check, thanks.
    This is my example:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Frame;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.Scrollbar;
    import java.awt.event.AdjustmentEvent;
    import java.awt.event.AdjustmentListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    * @author Oscar Uribe Brenes
    public class Ejemplo_011_Scrollbar {
    static int r=0,g=0,b=0;
    * @param args the command line arguments
    public static void main(String[] args) {
    Frame frame = new Frame();
    Panel panel = new Panel();
    final Label label = new Label();
    final Label label1 = new Label();
    final Label label2 = new Label();
    final Label label3 = new Label();
    Scrollbar scrollbar = new Scrollbar();
    Scrollbar scrollbar1 = new Scrollbar();
    Scrollbar scrollbar2 = new Scrollbar();
    BorderLayout borderLayout = new BorderLayout();
    GridLayout gridLayout = new GridLayout();
    frame.setTitle("Ejemplo_011_Scrollbar");
    frame.setSize(300, 100);
    label.setText("Rojo: 0");
    label.setAlignment(Label.RIGHT);
    label.setSize(50, label.getHeight());
    label1.setText("Verde: 0");
    label1.setAlignment(Label.RIGHT);
    label1.setSize(50, label.getHeight());
    label2.setText("Azul: 0");
    label2.setAlignment(Label.RIGHT);
    label2.setSize(50, label.getHeight());
    label3.setText("");
    scrollbar.setMinimum(0);
    scrollbar.setMaximum(255);
    scrollbar.setValue(0);
    scrollbar.setName("scrollbar");
    scrollbar.setOrientation(Scrollbar.HORIZONTAL);
    scrollbar1.setMinimum(0);
    scrollbar1.setMaximum(255);
    scrollbar1.setValue(0);
    scrollbar1.setName("scrollbar1");
    scrollbar1.setOrientation(Scrollbar.HORIZONTAL);
    scrollbar2.setMinimum(0);
    scrollbar2.setMaximum(255);
    scrollbar2.setValue(0);
    scrollbar2.setName("scrollbar2");
    scrollbar2.setOrientation(Scrollbar.HORIZONTAL);
    gridLayout.setColumns(2);
    gridLayout.setRows(3);
    gridLayout.setHgap(1);
    gridLayout.setVgap(2);
    frame.setLayout(borderLayout);
    panel.setLayout(gridLayout);
    WindowListener windowListener = new WindowListener() {
    @Override
    public void windowOpened(WindowEvent e) {
    @Override
    public void windowClosing(WindowEvent e) {
    Frame frame;
    if (e.getSource() instanceof Frame) {
    frame = (Frame) e.getSource();
    frame.dispose();
    @Override
    public void windowClosed(WindowEvent e) {
    System.exit(0);
    @Override
    public void windowIconified(WindowEvent e) {
    @Override
    public void windowDeiconified(WindowEvent e) {
    @Override
    public void windowActivated(WindowEvent e) {
    @Override
    public void windowDeactivated(WindowEvent e) {
    frame.addWindowListener(windowListener);
    AdjustmentListener adjustmentListener = new AdjustmentListener() {
    @Override
    public void adjustmentValueChanged(AdjustmentEvent e) {
    Scrollbar scrollbar;
    Color color = null;
    if(e.getSource()instanceof Scrollbar){
    scrollbar = (Scrollbar) e.getSource();
    if(scrollbar.getName().equals("scrollbar")){
    r = scrollbar.getValue();
    label.setText("Rojo: " + r);
    if (scrollbar.getName().equals("scrollbar1")) {
    g = scrollbar.getValue();
    label1.setText("Verde: " + g);
    if (scrollbar.getName().equals("scrollbar2")) {
    b = scrollbar.getValue();
    label2.setText("Azul: " + b);
    color = new Color(r, g, b);
    label3.setBackground(color);
    scrollbar.addAdjustmentListener(adjustmentListener);
    scrollbar1.addAdjustmentListener(adjustmentListener);
    scrollbar2.addAdjustmentListener(adjustmentListener);
    panel.add(label);
    panel.add(scrollbar);
    panel.add(label1);
    panel.add(scrollbar1);
    panel.add(label2);
    panel.add(scrollbar2);
    frame.add(panel, BorderLayout.CENTER);
    frame.add(label3, BorderLayout.SOUTH);
    frame.setLocation(200, 200);
    frame.setResizable(false);
    frame.setVisible(true);
    }

    Sorry, I could not find the edit button, so I post it again, with the format you said.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Frame;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.Scrollbar;
    import java.awt.event.AdjustmentEvent;
    import java.awt.event.AdjustmentListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    public class Ejemplo_011_Scrollbar {
        static int r = 0, g = 0, b = 0;
        public static void main(String[] args) {
            Frame frame = new Frame();
            Panel panel = new Panel();
            final Label label = new Label();
            final Label label1 = new Label();
            final Label label2 = new Label();
            final Label label3 = new Label();
            Scrollbar scrollbar = new Scrollbar();
            Scrollbar scrollbar1 = new Scrollbar();
            Scrollbar scrollbar2 = new Scrollbar();
            BorderLayout borderLayout = new BorderLayout();
            GridLayout gridLayout = new GridLayout();
            frame.setTitle("Ejemplo_011_Scrollbar");
            frame.setSize(300, 100);
            label.setText("Rojo: 0");
            label.setAlignment(Label.RIGHT);
            label.setSize(50, label.getHeight());
            label1.setText("Verde: 0");
            label1.setAlignment(Label.RIGHT);
            label1.setSize(50, label.getHeight());
            label2.setText("Azul: 0");
            label2.setAlignment(Label.RIGHT);
            label2.setSize(50, label.getHeight());
            label3.setText("");
            scrollbar.setMinimum(0);
            scrollbar.setMaximum(255);
            scrollbar.setValue(0);
            scrollbar.setName("scrollbar");
            scrollbar.setOrientation(Scrollbar.HORIZONTAL);
            scrollbar1.setMinimum(0);
            scrollbar1.setMaximum(255);
            scrollbar1.setValue(0);
            scrollbar1.setName("scrollbar1");
            scrollbar1.setOrientation(Scrollbar.HORIZONTAL);
            scrollbar2.setMinimum(0);
            scrollbar2.setMaximum(255);
            scrollbar2.setValue(0);
            scrollbar2.setName("scrollbar2");
            scrollbar2.setOrientation(Scrollbar.HORIZONTAL);
            gridLayout.setColumns(2);
            gridLayout.setRows(3);
            gridLayout.setHgap(1);
            gridLayout.setVgap(2);
            frame.setLayout(borderLayout);
            panel.setLayout(gridLayout);
            WindowListener windowListener = new WindowListener() {
                @Override
                public void windowOpened(WindowEvent e) {
                @Override
                public void windowClosing(WindowEvent e) {
                    Frame frame;
                    if (e.getSource() instanceof Frame) {
                        frame = (Frame) e.getSource();
                        frame.dispose();
                @Override
                public void windowClosed(WindowEvent e) {
                    System.exit(0);
                @Override
                public void windowIconified(WindowEvent e) {
                @Override
                public void windowDeiconified(WindowEvent e) {
                @Override
                public void windowActivated(WindowEvent e) {
                @Override
                public void windowDeactivated(WindowEvent e) {
            frame.addWindowListener(windowListener);
            AdjustmentListener adjustmentListener = new AdjustmentListener() {
                @Override
                public void adjustmentValueChanged(AdjustmentEvent e) {
                    Scrollbar scrollbar;
                    Color color = null;
                    if (e.getSource() instanceof Scrollbar) {
                        scrollbar = (Scrollbar) e.getSource();
                        if (scrollbar.getName().equals("scrollbar")) {
                            r = scrollbar.getValue();
                            label.setText("Rojo: " + r);
                        if (scrollbar.getName().equals("scrollbar1")) {
                            g = scrollbar.getValue();
                            label1.setText("Verde: " + g);
                        if (scrollbar.getName().equals("scrollbar2")) {
                            b = scrollbar.getValue();
                            label2.setText("Azul: " + b);
                        color = new Color(r, g, b);
                    label3.setBackground(color);
            scrollbar.addAdjustmentListener(adjustmentListener);
            scrollbar1.addAdjustmentListener(adjustmentListener);
            scrollbar2.addAdjustmentListener(adjustmentListener);
            panel.add(label);
            panel.add(scrollbar);
            panel.add(label1);
            panel.add(scrollbar1);
            panel.add(label2);
            panel.add(scrollbar2);
            frame.add(panel, BorderLayout.CENTER);
            frame.add(label3, BorderLayout.SOUTH);
            frame.setLocation(200, 200);
            frame.setResizable(false);
            frame.setVisible(true);
    }Edited by: screeen on May 28, 2010 1:45 AM

  • AWT Scrollbar Issue

    I have made my own scrollbar by extending from java.awt.Scrollbar. See below.
    private class movableScrollbar extends Scrollbar {
    public movableScrollbar() {
    super(0);
    public boolean isFocusTraversable() {
    return true;
    As you can see, the only difference that I'd like movableScrollbar to have from a normal Scrollbar is to make it traversable (i.e. to have the ability to tab to it and then to the next component).
    Here's my problem. When I tab to a movableScrollbar, I can't tab to the next component. To get to the next component, I have to move the movableScrollbar and then press Shift+Tab, which for some reason puts me 2 components backwards instead of 1, then I am able to tab past it. What the heck is happening???
    Please Help!!!

    If you are implementing the Interface, FocusListener, you have to do more work. But if you extend a SuperClass of FocusAdapter you can control the focus the way you are attempting by overriding the methods that you want.
    Another way is to implement ActionListener and FocusListener. Listen for the Tab and Shift-Tab. When you see the keyboard event, check to see what Component has the focus, better yet check only the Components before and after the scroll bar.
    If (textBox.hasFocus()) {
    movableScrollBar.requestFocus()
    Do the same thing for each of the Components before and after the Scroll Bar. Do it for the ScrollBar as well controlling where it goes.
    Now to manipulate specific focus events like above, you will have to implement the FocusListener() Interface. I hope this helps.

  • How to enable a scrollbar in a JPanel

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

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

  • How to restrict the maximum size of a java.awt.ScrollPane

    Dear all,
    I would like to implement a scroll pane which is resizable, but not to a size exceeding the maximum size of the java.awt.Canvas that it contains.
    I've sort of managed to do this by writing a subclass of java.awt.ScrollPane which implements java.awt.event.ComponentListener and has a componentResized method that checks whether the ScrollPane's viewport width (height) exceeds the content's preferred size, and if so, resizes the pane appropriately (see code below).
    It seems to me, however, that there ought to be a simpler way to achieve this.
    One slightly weird thing is that when the downsizing of the pane happens, the content can once be moved to the left by sliding the horizontal scrollbar, but not by clicking on the arrows. This causes one column of gray pixels to disappear and the rightmost column of the content to appear; subsequent actions on the scrollbar does not have any further effect. Likewise, the vertical scrollbar can also be moved up once.
    Also, I would like a java.awt.Frame containing such a restrictedly resizable scrollpane, such that the Frame cannot be resized by the user such that its inside is larger than the maximum size of the scrollpane. The difficulty I encountered with that is that setSize on a Frame appears to set the size of the window including the decorations provided by the window manager (fvwm2, if that matters), and I haven't been able to find anything similar to getViewportSize, which would let me find out the size of the area inside the Frame which is available for the scrollpane which the frame contains.
    Thanks in advance for hints and advice.
    Here's the code of the componentResized method:
      public void componentResized(java.awt.event.ComponentEvent e)
        java.awt.Dimension contentSize = this.content.getPreferredSize();
        this.content.setSize(contentSize);
        java.awt.Dimension viewportSize = getViewportSize();
        System.err.println("MaxSizeScrollPane: contentSize = " + contentSize);
        System.err.println("MaxSizeScrollPane: viewportSize = " + viewportSize);
        int dx = Math.max(0, (int) (viewportSize.getWidth() - contentSize.getWidth()));
        int dy = Math.max(0, (int) (viewportSize.getHeight() - contentSize.getHeight()));
        System.err.println("MaxSizeScrollPane: dx = " + dx + ", dy = " + dy);
        if ((dx > 0) || (dy > 0))
          java.awt.Dimension currentSize = getSize();
          System.err.println("MaxSizeScrollPane: currentSize = " + currentSize);
          setSize(new java.awt.Dimension(((int) currentSize.getWidth()) - dx, ((int) currentSize.getHeight()) - dy));
        System.err.println();
      }Best regards, Jan

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class ScrollPaneTest
        GraphicCanvas canvas;
        CustomScrollPane scrollPane;
        private Panel getScrollPanel()
            canvas = new GraphicCanvas();
            scrollPane = new CustomScrollPane();
            scrollPane.add(canvas);
            // GridBagLayout allows scrollPane to remain at
            // its preferred size during resizing activity
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            panel.add(scrollPane, gbc);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        private Panel getUIPanel()
            int w = canvas.width;
            int h = canvas.height;
            int visible = 100;
            int minimum = 200;
            int maximum = 500;
            final Scrollbar
                width  = new Scrollbar(Scrollbar.HORIZONTAL, w,
                                       visible, minimum, maximum),
                height = new Scrollbar(Scrollbar.HORIZONTAL, h,
                                       visible, minimum, maximum);
            AdjustmentListener l = new AdjustmentListener()
                public void adjustmentValueChanged(AdjustmentEvent e)
                    Scrollbar scrollbar = (Scrollbar)e.getSource();
                    int value = scrollbar.getValue();
                    if(scrollbar == width)
                        canvas.setWidth(value);
                    if(scrollbar == height)
                        canvas.setHeight(value);
                    canvas.invalidate();
                    scrollPane.validate();
            width.addAdjustmentListener(l);
            height.addAdjustmentListener(l);
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addComponents(new Label("width"),  width,  panel, gbc);
            addComponents(new Label("height"), height, panel, gbc);
            gbc.anchor = GridBagConstraints.CENTER;
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        public static void main(String[] args)
            ScrollPaneTest test = new ScrollPaneTest();
            Frame f = new Frame();
            f.addWindowListener(test.closer);
            f.add(test.getScrollPanel());
            f.add(test.getUIPanel(), "South");
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
            f.addComponentListener(new FrameSizer(f));
    class GraphicCanvas extends Canvas
        int width, height;
        public GraphicCanvas()
            width = 300;
            height = 300;
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int dia = Math.min(width, height)*7/8;
            g2.setPaint(Color.blue);
            g2.draw(new Rectangle2D.Double(width/16, height/16, width*7/8, height*7/8));
            g2.setPaint(Color.green.darker());
            g2.draw(new Ellipse2D.Double(width/2 - dia/2, height/2 - dia/2, dia-1, dia-1));
            g2.setPaint(Color.red);
            g2.draw(new Line2D.Double(width/16, height*15/16-1, width*15/16-1, height/16));
        public Dimension getPreferredSize()
            return new Dimension(width, height);
        public Dimension getMaximumSize()
            return getPreferredSize();
        public void setWidth(int w)
            width = w;
            repaint();
        public void setHeight(int h)
            height = h;
            repaint();
    class CustomScrollPane extends ScrollPane
        Dimension minimumSize;
        public Dimension getPreferredSize()
            Component child = getComponent(0);
            if(child != null)
                Dimension d = child.getPreferredSize();
                if(minimumSize == null)
                    minimumSize = (Dimension)d.clone();
                Insets insets = getInsets();
                d.width  += insets.left + insets.right;
                d.height += insets.top + insets.bottom;
                return d;
            return null;
        public Dimension getMinimumSize()
            return minimumSize;
        public Dimension getMaximumSize()
            Component child = getComponent(0);
            if(child != null)
                return child.getMaximumSize();
            return null;
    class FrameSizer extends ComponentAdapter
        Frame f;
        public FrameSizer(Frame f)
            this.f = f;
        public void componentResized(ComponentEvent e)
            Dimension needed = getSizeForViewport();
            Dimension size = f.getSize();
            if(size.width > needed.width || size.height > needed.height)
                f.setSize(needed);
                f.pack();
         * returns the minimum required frame size that will allow
         * the scrollPane to be displayed at its preferred size
        private Dimension getSizeForViewport()
            ScrollPane scrollPane = getScrollPane(f);
            Insets insets = f.getInsets();
            int w = scrollPane.getWidth() + insets.left + insets.right;
            int h = getHeightOfChildren() + insets.top + insets.bottom;
            return new Dimension(w, h);
        private ScrollPane getScrollPane(Container cont)
            Component[] c = cont.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j] instanceof ScrollPane)
                    return (ScrollPane)c[j];
                if(((Container)c[j]).getComponentCount() > 0)
                    return getScrollPane((Container)c[j]);
            return null;
        private int getHeightOfChildren()
            Component[] c = f.getComponents();
            int extraHeight = 0;
            for(int j = 0; j < c.length; j++)
                int height;
                if(((Container)c[j]).getComponent(0) instanceof ScrollPane)
                    height = ((Container)c[j]).getComponent(0).getHeight();
                else
                    height = c[j].getHeight();
                extraHeight += height;
            return extraHeight;
    }

  • Scrollbar help~

    hi..
    the code below are in working condition.. means can be compiled & run.. when drag the scrollbar, the "Welcome To Java" string message will be move left, right or up, down depend on which scrollbar u drag..
    just wanna ask if the "Welcome To Java" text be changed to image?? so instead of the text shifting.. its the image tt is moving.. can anyone help me.. ??
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ScrollbarDemo extends Applet implements AdjustmentListener
         //declare scrollbars
         Scrollbar scbHort, scbVert;
         //declare a canvas
         ScrollMessageCanvas c;
         public static void main(String[] args)
              ScrollbarDemo f = new ScrollbarDemo();
              f.setSize(300,200);
              f.setVisible(true);
         public ScrollbarDemo()
              setLayout(new BorderLayout());
              //create scrollbars
              scbVert = new Scrollbar();
              scbVert.setOrientation(Scrollbar.VERTICAL);
              scbHort = new Scrollbar();
              scbHort.setOrientation(Scrollbar.HORIZONTAL);
              add("Center", c = new ScrollMessageCanvas());
              add("East", scbVert);
              add("South", scbHort);
              //register listener for the scrollbars
              scbHort.addAdjustmentListener(this);
              scbVert.addAdjustmentListener(this);
         public void adjustmentValueChanged(AdjustmentEvent e)
              if(e.getSource() == scbHort)
                   /*getValue() and getMaximumValue() return int, but for better precision, use double*/
                   double value = scbHort.getValue();
                   double maximumValue = scbHort.getMaximum();
                   double newX = (value*c.getSize().width/maximumValue);
                        c.setX((int)newX);
              else if(e.getSource() == scbVert)
                   /*getValue() and getMaximumValue() return int, but for better precision, use double*/
                   double value = scbVert.getValue();
                   double maximumValue = scbVert.getMaximum();
                   double newY = (value*c.getSize().height/maximumValue);
                        c.setY((int)newY);
    class ScrollMessageCanvas extends Canvas
         private int x = 10;
         private int y = 20;
         private String message = "Welcome to Java!";
         public ScrollMessageCanvas()
              repaint();
         public void setX(int x)
              this.x = x;
              repaint();
         public void setY(int y)
              this.y = y;
              repaint();
         public void paint(Graphics g)
              g.drawString(message, x, y);
    }

    what should i replace this line with??
    [[  private String message = "Welcome to Java!";  ]]
    public void paint(Graphics g)
    g.drawString(message, x, y);
    can be replaced by
    public void paint(Graphics g)
    g.drawImage(image, 0,0);
    }

  • Need Help with scrollbars

    hu..
    i have this JFrane that has a table which has scrollbars...
    i have included in my code setResizable(false) so the user will not be able to maximize the page..
    i have a function AdScroll()[that adds scrollbars] that will be called every time i add ,delete ,update a user ..
    my problem is when i click on the delete and update buttons the user will not be deleted or updated from the table, but when i remove AddScroll() the user will be deleted and updated from the table but the scroll bars will not be added..
    so can some one help me with this problem.
    thankx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.io.*;
    import javax.swing.JPanel;
    import java.applet.*;
    import sun.audio.*;
    import java.net.*;
    import java.text.*;
    class UtilityMethods extends JFrame implements ActionListener
      private boolean tabsVisible=false;
      private File fileName;
      private RandomAccessFile output;
      AudioStream voice;
      UtilityMethods utilities;
      Connection conn;
      Statement stat;
      String dsnName, userStatus;
      String appTable = "CUSTOMER";
      Container c = getContentPane();
       JTabbedPane tabs;
        //JScrollPane scrollpane;
      JTable dataTable, addataTable;
      static String[][] tableData, adtableData;
      JScrollPane scrollpane, adscrollpane,vscrollpane;
      JTextField id, name, address, phone, sex, dob, photo,audio,template;
      JTextArea comments;
      JButton search, update, clear, add, delete, close,audio1,faceBrowse,voiceBrowse,voice1;
      JPanel customerPanel, adminPanel;
      JPanel backPanel, inputPanel, middlePanel, buttonPanel1, buttonPanel2, photoHolder;
      JTextField adname, adusername, adpassword;
      JPanel adbackPanel, adinputPanel, admiddlePanel, adbuttonPanel1, adbuttonPanel2, radioPanel;
      JButton adsearch, adupdate, adclear, adadd, addelete, adclose;
      JRadioButton userStat, adminStat, cleared;
      ButtonGroup statusGroup;
      //===================================================================================================
      /*public UtilityMethods()
        makeGUI();
      //Create the GUI:
      void makeGUI()
        c.setLayout(new BorderLayout());
        tabs = new JTabbedPane();
        customerPanel = new JPanel(new BorderLayout());
        adminPanel = new JPanel(new BorderLayout());
    //    voicePanel= new JPanel(new BorderLayout());
        //1. Construct customers tab:
          //The data input section:
        inputPanel      = new JPanel(new GridLayout(4, 4));
         id = new JTextField(20);
                 name = new JTextField(20);
                 address = new JTextField(20);
                 phone = new JTextField(20);
                 sex = new JTextField(20);
                 dob = new JTextField(20);
                 photo = new JTextField(20);
                 audio = new JTextField(20);
                 template = new JTextField(20);
                 faceBrowse = new JButton("...");
                 faceBrowse.setBounds(210, 150, 25, 25);
        inputPanel.add(new JLabel("CPR", JLabel.CENTER));
        inputPanel.add(id);
        inputPanel.add(new JLabel("Name", JLabel.CENTER));
        inputPanel.add(name);
        inputPanel.add(new JLabel("Address", JLabel.CENTER));
        inputPanel.add(address);
        inputPanel.add(new JLabel("Phone", JLabel.CENTER));
        inputPanel.add(phone);
        inputPanel.add(new JLabel("Sex", JLabel.CENTER));
        inputPanel.add(sex);
        inputPanel.add(new JLabel("Date Of Birth", JLabel.CENTER));
        inputPanel.add(dob);
        inputPanel.add(new JLabel("Customer Photo ", JLabel.CENTER));
        inputPanel.add(photo);
        inputPanel.add(new JLabel("Voice ", JLabel.CENTER));
        inputPanel.add(audio);
    customerPanel.add(inputPanel, BorderLayout.NORTH);
          //The buttons section:
        backPanel = new JPanel();
        middlePanel = new JPanel(new BorderLayout());
        buttonPanel1 = new JPanel();
        buttonPanel2 = new JPanel();
        search   = new JButton("SEARCH");
        update   = new JButton("UPDATE");
        clear    = new JButton("CLEAR");
        add      = new JButton("ADD");
        delete   = new JButton("DELETE");
        close    = new JButton("EXIT");
        audio1    =new JButton("Voice");
        //faceBrowse    = new JButton("...");
        //voiceBrowse    =new JButton("...");
        search.setPreferredSize(new Dimension(102, 26));
        update.setPreferredSize(new Dimension(102, 26));
        clear.setPreferredSize(new Dimension(102, 26));
        add.setPreferredSize(new Dimension(102, 26));
        delete.setPreferredSize(new Dimension(102, 26));
        close.setPreferredSize(new Dimension(102, 26));
        audio1.setPreferredSize(new Dimension(102, 26));
        faceBrowse.setPreferredSize(new Dimension(26, 26));
        //voiceBrowse.setPreferredSize(new Dimension(26, 26));
        search.addActionListener(this);
        update.addActionListener(this);
        clear.addActionListener(this);
        add.addActionListener(this);
        delete.addActionListener(this);
        close.addActionListener(this);
        audio1.addActionListener(this);
        //faceBrowse.addActionListener(this);
        //voiceBrowse.addActionListener(this);
        buttonPanel1.add(search);
        //buttonPanel1.add(faceBrowse);
        buttonPanel1.add(update);
        buttonPanel1.add(clear);
        buttonPanel2.add(add);
        buttonPanel2.add(delete);
        buttonPanel2.add(close);
        buttonPanel2.add(audio1);
        //buttonPanel1.add(voiceBrowse);
        middlePanel.add(buttonPanel1, BorderLayout.NORTH);
        middlePanel.add(buttonPanel2, BorderLayout.CENTER);
        photoHolder = new JPanel();
        Icon curPhoto = new ImageIcon("");
        Icon[] custPhotos = {curPhoto};
        JList photosList = new JList(custPhotos);
        photosList.setFixedCellHeight(100);
        photosList.setFixedCellWidth(80);
        photoHolder.add(photosList);
        makeComments();
        backPanel.add(middlePanel);
        backPanel.add(photoHolder);
        backPanel.add(comments);
        customerPanel.add(backPanel, BorderLayout.CENTER);
      pack();
        setVisible(true);
        setSize(500,700);
      } //makeGUI
    void updateTable()
          ResultSet results = null;
          ResultSet results1 = null;
          try
            //Get the number of rows in the table so we know how big to make the data array..
            int rowNumbers  = 0;
            int columnCount = 6;
            results = stat.executeQuery("SELECT COUNT(*) FROM CUSTOMER ");
            if(results.next())
              rowNumbers = results.getInt(1);
            } //if
            if(rowNumbers == 0)
            rowNumbers = 1;
            tableData = new String[rowNumbers][columnCount];
            //Initialize the data array with "" so we avoid possibly having nulls in it later..
            for(int i =0;i<tableData.length;i++)
              for(int j=0;j<tableData[0].length;j++)
              tableData[i][j] = "";
            //Populate the data array with results of the query on the database..
            int currentRow = 0;
            results1 = stat.executeQuery("SELECT * FROM CUSTOMER ORDER BY ID");
            while (results1.next())
              for(int i = 0; i < columnCount; i++)
              tableData[currentRow] = results1.getString(i + 1);
    currentRow++;
    } //while
    //Create the table model:
    final String[] colName = { "CPR", "Name", "Address", "Phone", "Sex", "Date OF Birth" };
    TableModel pageModel = new AbstractTableModel()
    public int getColumnCount()
    return tableData[0].length;
    } //getColumnCount
    public int getRowCount()
    return tableData.length;
    } //getRowCount
    public Object getValueAt(int row, int col)
    return tableData[row][col];
    } //getValueAt
    public String getColumnName(int column)
    return colName[column];
    } //getcolName
    public Class getColumnClass(int col)
    return getValueAt(0, col).getClass();
    } //getColumnClass
    public boolean isCellEditable(int row, int col)
    return false;
    } //isCellEditable
    public void setValueAt(String aValue, int row, int column)
    tableData[row][column] = aValue;
    } //setValueAt
    //dataTable.setValue( new JScrollBar(JScrollBar.HORIZONTAL), 2,1 );
    }; //pageModel
    //Create the JTable from the table model:
    JTable dataTable = new JTable(pageModel);
    // dataTable.setModel();
    /*if (scrollpane != null)
    scrollpane.setVisible(false);
    scrollpane = null;
    } //if*/
    //scrollpane = new JScrollPane(dataTable);
    //scrollpane.setVisible(true);
    if (inputPanel == null)
    makeGUI();
    JScrollPane scrollpane =new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // Create vertical box for second tab
    Box box = Box.createVerticalBox();
    // Create component for top
    box.add(customerPanel);
    // Place glue between components
    box.add(Box.createVerticalGlue());
    // Create component for middle
    box.add(middlePanel);
    // Place glue between components
    box.add(Box.createVerticalGlue());
    // Create component for middle
    box.add(backPanel);
    // Place glue between components
    box.add(Box.createVerticalGlue());
    // Create component for bottom
    box.add(scrollpane);
    // Add box to JTabbedPane
    tabs.add(box, "Customer");
              setResizable(false);
    id.grabFocus();
    pack();
    repaint();
    adupdateTable();
    } //try
    catch (Exception e)
    System.out.println("Caught updateTable exception: " + e);
    e.printStackTrace();
    } //catch
    } //updatetable
    //===================================================================================================
    //===================================================================================================
    //Update the customer table from the database:
    void updateTable(String userStatus)
    this.userStatus = userStatus;
         updateTable();
         if(userStatus.equals("user"))
         delete.setEnabled(false);
         tabs.setEnabledAt(1, false);
    public void actionPerformed(ActionEvent e)
    FileInputStream fis = null;
    if (e.getSource() == add) //The ADD button.
    //User has not populated all the input fields.
    if(name.getText().equals("")|| address.getText().equals("")|| phone.getText().equals("")|| sex.getText().equals("")|| dob.getText().equals("")|| photo.getText().equals(""))
    JOptionPane.showMessageDialog(null, "Please fill in all the fields","Missing Fields",JOptionPane.INFORMATION_MESSAGE);
    else
    // save the new customer:
    try
    //1. take the customer's data and photo:
    int userId          = Integer.parseInt(id.getText());
    String userName      = name.getText();
    String userAddress      = address.getText();
    String userPhone      = phone.getText();
    String userSex      = sex.getText();
    String userDateBirth      = dob.getText();
    String photoName      = photo.getText();
    String audioName= audio.getText();
    File file           = new File(photoName);
    int fileLength      = (int)file.length();
    //2. Set the user's photo into the photoHolder:
    photoHolder.setVisible(false);
    photoHolder = null;
    comments.setVisible(false);
    comments = null;
    Icon[] custPhotos = {new ImageIcon(photoName)};
    JList photosList = new JList(custPhotos);
    photosList.setFixedCellHeight(100);
    photosList.setFixedCellWidth(80);
    photoHolder = new JPanel();
    photoHolder.add(photosList);
    makeComments();
    //3. Insert the data and photo into the database:
    if(fileLength > 0)
    fis = new FileInputStream(file);
    String query = " INSERT INTO CUSTOMER VALUES('"+userId+"', '"+ userName+ "', '"+ userAddress+ "', " +" '"+ userPhone+ "', '"+ userSex+ "', '"+ userDateBirth+ "', ?,?,? ) ";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBinaryStream(1, fis, fileLength);
              pstmt.setString(2,photoName);
              pstmt.setString(3,audioName);
    pstmt.executeUpdate();
    comments.setText(userName+", added.");
    else
    String query = " INSERT INTO CUSTOMER (id, name, address, phone, sex, dob) VALUES('"+userId+"', '"+userName+"', '"+userAddress+"', '"+userPhone+"', '"+userSex+"', '"+userDateBirth+"') ";
    stat.executeUpdate(query);
    comments.setText("Customer saved without a photo.");
    backPanel.add(photoHolder);
    backPanel.add(comments);
    //updateTable();
    AddScroll();
    } //try
    catch (Exception ee)
    //The danger of putting creating the JOptionPane in here is that it will show the same message regardless of the error.
              JOptionPane.showMessageDialog(null, "Customers CPR already exits!!Please enter another CPR","Invalid",JOptionPane.INFORMATION_MESSAGE);
    System.out.println("Caught exception in add action: " + ee);
    } //catch
    } //if
    }//add button
    void AddScroll()
         JScrollPane scrollpane =new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollpane.getViewport().add(dataTable);

    hi i tryed the JTable.revalidate() but i still did't work...
    i did this :
    public void actionPerformed(ActionEvent e)
        FileInputStream fis = null;
        if (e.getSource() == add) //The ADD button.
          //User has not populated all the input fields.
          if(name.getText().equals("")|| address.getText().equals("")|| phone.getText().equals("")|| sex.getText().equals("")|| dob.getText().equals("")|| photo.getText().equals(""))
            JOptionPane.showMessageDialog(null, "Please fill in all the fields","Missing Fields",JOptionPane.INFORMATION_MESSAGE);
          else
            // save the new customer:
            try
              //1. take the customer's data and photo:
              int    userId          = Integer.parseInt(id.getText());
              String userName      = name.getText();
              String userAddress      = address.getText();
              String userPhone      = phone.getText();
              String userSex      = sex.getText();
              String userDateBirth      = dob.getText();
              String photoName      = photo.getText();
              String audioName=   audio.getText();
              File   file           = new File(photoName);
              int    fileLength      = (int)file.length();
              //2. Set the user's photo into the photoHolder:
              photoHolder.setVisible(false);
              photoHolder = null;
              comments.setVisible(false);
              comments = null;
              Icon[] custPhotos = {new ImageIcon(photoName)};
              JList photosList = new JList(custPhotos);
              photosList.setFixedCellHeight(100);
              photosList.setFixedCellWidth(80);
              photoHolder = new JPanel();
              photoHolder.add(photosList);
              makeComments();
              //3. Insert the data and photo into the database:
              if(fileLength > 0)
                fis = new FileInputStream(file);
                String query = " INSERT INTO CUSTOMER VALUES('"+userId+"', '"+ userName+ "', '"+ userAddress+ "', " +" '"+ userPhone+ "', '"+ userSex+ "', '"+ userDateBirth+ "', ?,?,? ) ";
                PreparedStatement pstmt = conn.prepareStatement(query);
                pstmt.setBinaryStream(1, fis, fileLength);
                  pstmt.setString(2,photoName);
                  pstmt.setString(3,audioName);
                pstmt.executeUpdate();
                comments.setText(userName+", added.");
              else
                String query = " INSERT INTO CUSTOMER (id, name, address, phone, sex, dob) VALUES('"+userId+"', '"+userName+"', '"+userAddress+"', '"+userPhone+"', '"+userSex+"', '"+userDateBirth+"') ";
                stat.executeUpdate(query);
                comments.setText("Customer saved without a photo.");
              backPanel.add(photoHolder);
              backPanel.add(comments);
              //updateTable();
              dataTable.revalidate();
               AddScroll();
            } //try
            catch (Exception ee)
               //The danger of putting creating the JOptionPane in here is that it will show the same message regardless of the error.
                JOptionPane.showMessageDialog(null, "Customers CPR already exits!!Please enter another CPR","Invalid",JOptionPane.INFORMATION_MESSAGE);
              System.out.println("Caught exception in add action: " + ee);
                ee.printStackTrace();
            } //catch
          } //if
        }//add buttonand i included this function AddScroll() that i will add the scroll bars :
    void AddScroll()
          JScrollPane scrollpane =new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollpane.getViewport().add(dataTable);
    // AbstractTableModel pageModel  = (AbstractTableModel)dataTable.getModel();
    //            pageModel .fireTableDataChanged();
    //dataTable.updateUI();
    }thankx

  • Scroll Bar code in Awt Required Plz Help me

    Hi,
    My requirment is to add Vertical Scrollbar to the table.There are 12 rows in a table like from January to December.
    I am able to see data of rows as jan,feb,mar,apr only .
    i want to see the data of rows of next months by adding vertical scroll bar using Awt code.
    I added vertical scroll bar using awt code. When i click on that Vertical scroll bar event is going to below method.
    public void adjustmentValueChanged(AdjustmentEvent e) {
    I tried with some logic inside above method but it is not working.what is the code i have to write inside the above method inorder to scroll the next months.
    Plz Help me.
    Thanks In Advance.........

    But i want to do this code In Using Awt only......Well, a JTable is a Swing component so I have no idea what you are talking about.
    To control the size of the table you can use:
    table.setPreferredScrollableViewportSize(???);
    JScrollPane scrollPane = new JScrollPane( table );

  • Scrollbar not working in a JScrollPane

    In the JDialog there is a JScrollPane. JTextPane is in a the scroll pane. For some reason the scrollbars are not working.
    Any suggestions on this why the scrollbars not working?
    Thanks.

    using the setText() method the text is set to the text pane from some other package. the Dialog displays the text too with the vertical scroll bar that doesn't work.
    public MyDialog(JFrame frame) {
    super(frame);
    initialize();
    private void initialize() {
    this.setResizable(true);
    this.setName("");
    this.setUndecorated(false);
    this.setContentPane(getScrl());
    this.setSize(400, 300);
    this.centerDialog();
    private javax.swing.JScrollPane getScrl() {
    if (scrl == null) {
    scrl = new javax.swing.JScrollPane();
    scrl.setViewportView(getTxt());
    return scrl;
    private javax.swing.JTextPane getTxt() {
    if (txt == null) {
    txt = new javax.swing.JTextPane();
    txt.setBackground(java.awt.SystemColor.info);
    txt.setEditable(false);
    return txt;
    public void setText(String text) {
    if (txt.getEditorKit() == null) {
    txtToolTip.setEditorKit(new StyledEditorKit());
    txt.setContentType("text/html");
    txt.setOpaque(true);
    txt.setText(text);

  • Applet repainting error in IE 5.5 using the scrollbars

    I've created a real straight forward applet using swing components to test out this error. It consists of a couple of JButtons & JLabels added to a JPanel that's the JPanel is added to the ContentPane. I'm using the Java Plug-in 1.3 on a Windows 2000 box using IE 5.5. When I view my applet everything is just fine. But when I'm using the browser scrollbars to view the rest of my applet and try to scroll down, the applet controls and everything within the applet does not get repainted properly onto the screen. Everything in the applet gets painted on top of their old controls a couple of pixels off making it impossible to use. When I scroll to the bottom and top of the page the applet repaints just fine, but it's when I'm scrolling in the middle of the page is where the applet can not repaint properly. I have tested this in Netscape 6.0 and everything works just fine. I'mnot sure what could be causing this but maybe one of you have cameacross this problem before and could help out.
    thanks,
    Peter Landis.

    Here's the code:
    import java.awt.*;
    import javax.swing.*;
    public class TestRepaint extends JApplet
    public void init()
         Container contentPane = getContentPane();
         JPanel panel = new JPanel();
    panel.setBackground(Color.lightGray);
    controls(panel);
         // Grid
         contentPane.add(panel);
    public void controls(JPanel p)
    JLabel imagelabel = new JLabel();
    JLabel imagelabel2 = new JLabel();
    // Create some labels
    JLabel label_1 = new JLabel("TEST 1");
    JLabel label_2 = new JLabel("TEST 2");
    JLabel label_3 = new JLabel("TEST 3");
    JLabel label_4 = new JLabel("TEST 4");
    JLabel label_5 = new JLabel("TEST 5");
    JLabel label_6 = new JLabel("TEST 6");
    JLabel label_7 = new JLabel("TEST 7");
    setLabelControl(label_1);
    setLabelControl(label_2);
    setLabelControl(label_3);
    setLabelControl(label_4);
    setLabelControl(label_5);
    setLabelControl(label_6);
    setLabelControl(label_7);
    // Buttons
    JButton b1 = new JButton("Button 1");
    JButton b2 = new JButton("Button 2");
    JButton b3 = new JButton("Button 3");
    JButton b4 = new JButton("Button 4");
    JButton b5 = new JButton("Button 5");
    JButton b6 = new JButton("Button 6");
    JButton b7 = new JButton("Button 7");
    setButtonControl(b1);
    setButtonControl(b2);
    setButtonControl(b3);
    setButtonControl(b4);
    setButtonControl(b5);
    setButtonControl(b6);
    setButtonControl(b7);
    // Layout
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();
    p.setLayout(gridbag);
    c.anchor = GridBagConstraints.WEST;
         c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.gridwidth = 1;
    // Note Inset is (Top, Left, Bottom, Right);
    c.insets = new Insets(0,5,20,0);
         p.add(label_3,c);
         c.insets = new Insets(0,5,20,1);
    p.add(b3,c);
    c.insets = new Insets(0,5,20,0);
         p.add(label_4,c);
    c.gridwidth = GridBagConstraints.REMAINDER;
         c.insets = new Insets(0,5,20,1);
    p.add(b4,c);
    c.gridwidth = 1;
    c.insets = new Insets(0,5,20,0);
         p.add(label_5,c);
         c.insets = new Insets(0,5,20,1);
    p.add(b5,c);
    c.insets = new Insets(0,5,20,0);
         p.add(label_6,c);
    c.gridwidth = GridBagConstraints.REMAINDER;
         c.insets = new Insets(0,5,20,1);
    p.add(b6,c);
    public void setButtonControl(JButton button)
              button.setBackground(Color.white);
    void setLabelControl(JLabel l)
              l.setFont(new Font("Helvetica", Font.BOLD, 14) );
    l.setForeground(Color.black);
    ||||||||||||||||||||| HTML CODE |||||||||||||||||||
    <title>Test</title>
    <hr>
    <!--"CONVERTED_APPLET"-->
    <!-- CONVERTER VERSION 1.3 -->
    <SCRIPT LANGUAGE="JavaScript"><!--
    var info = navigator.userAgent; var ns = false;
    var ie = (info.indexOf("MSIE") > 0 && info.indexOf("Win") > 0 && info.indexOf("Windows 3.1") < 0);
    //--></SCRIPT>
    <COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
    var ns = (navigator.appName.indexOf("Netscape") >= 0 && ((info.indexOf("Win") > 0 && info.indexOf("Win16") < 0 && java.lang.System.getProperty("os.version").indexOf("3.5") < 0) || (info.indexOf("Sun") > 0) || (_info.indexOf("Linux") > 0)));
    //--></SCRIPT></COMMENT>
    <SCRIPT LANGUAGE="JavaScript"><!--
    if (_ie == true) document.writeln('<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH = 500 HEIGHT = 425 codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0"><NOEMBED><XMP>');
    else if (_ns == true) document.writeln('<EMBED type="application/x-java-applet;version=1.3" CODE = "TestRepaint.class" WIDTH = 500 HEIGHT = 425 scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html"><NOEMBED><XMP>');
    //--></SCRIPT>
    <APPLET CODE = "TestRepaint.class" WIDTH = 500 HEIGHT = 425></XMP>
    <PARAM NAME = CODE VALUE = "TestRepaint.class" >
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
    <PARAM NAME="scriptable" VALUE="false">
    </APPLET>
    </NOEMBED></EMBED></OBJECT>
    <!--
    <APPLET CODE = "TestRepaint.class" WIDTH = 500 HEIGHT = 425>
    </APPLET>
    -->
    <!--"END_CONVERTED_APPLET"-->
    <hr>

  • Disappearing Scrollbars

    Hi,
    I have a problem with the JScrollPane.
    When adding some components to a panel inside a JScrollPane whereby most components are invisible at the start and made visible by user actions, the scrollbars disappear when making components visible.
    More precisely, I always resize the whole frame when making a component visible. If the frame is too big to fit on the screen, they first appear, but when making one more component visible, they disappear again.
    Very strange is also, that when I minimize the dialog and then maximize it again, they reappear again. This sounds like a bug for me...
    Any help would be appreciated. BTW, I'm using Java 1.6.0.
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JToolBar;
    public class ScrollBarTest
         public static void main(String[] args)
              final JFrame frame = new JFrame("ScrollBar Test");
              frame.setLayout(new BorderLayout());
              Font font = new Font(Font.DIALOG, Font.PLAIN, 80);
              JPanel panel = new JPanel(new GridBagLayout());
              GridBagConstraints cons = new GridBagConstraints();
              cons.gridwidth = GridBagConstraints.REMAINDER;
              final List<JLabel> labels = new ArrayList<JLabel>(20);
              for (int i = 0; i < 20; i++)
                   JLabel label = new JLabel("Label " + i);
                   label.setFont(font);
                   labels.add(label);
                   if (i > 0)
                        label.setVisible(false);
                   panel.add(label, cons);
              frame.add(new JScrollPane(panel), BorderLayout.CENTER);
              JToolBar toolbar = new JToolBar();
              JButton button = new JButton("Klick");
              button.addActionListener(new ActionListener()
                   int     firstInvisible     = 1;
                   @Override
                   public void actionPerformed(ActionEvent e)
                        labels.get(firstInvisible).setVisible(true);
                        firstInvisible++;
                        frame.pack();
              toolbar.add(button);
              frame.add(toolbar, BorderLayout.NORTH);
              frame.pack();
              frame.setVisible(true);
    }

    If the frame is too big to fit on the screen, they first appear, but when making one more component visible, they disappear again.I reset the maximum frame height and it works the way I would expect it to. That is the frame height doesn't change and scrollbars appear.
    frame.pack();
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Rectangle bounds = env.getMaximumWindowBounds();
    int height = bounds.height;
    Dimension d = frame.getSize();
    if (d.height > height)
         d.height = height;
         frame.setSize(d);
    }

  • Scrollbars and Mouse monitoring in a JFrame

    class Akim extends JFrame
         public Akim()
              super("Drawing lines");
              pack();
              setSize(640,640);
              setVisible(true);
         public void paint(Graphics g)
              super.paint(g);
              g.setColor(new Color(200,200,250));
              g.fillRect(40,40,400,400);
              g.setColor(new Color(255,255,255));
              for(int i = 2; i<=22; i++)
                   g.drawLine(20*i,40,20*i,440);
              for (int i=1;i<=22;i++)
                   g.drawLine(40,20*i,440,20*i);
    class blah
         public static void main(String[] args)
              Akim me = new Akim();
              me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }I am keeping the size down because if it gets bigger it goes off the screen. I would like to know how to add scrollbars.
    I would also like to display something whenever someone clicks in one of the squares. How do I get the location where the mouse was pressed?
    I only started working with JFrames yesterday so please keep it simple(if possible).
    Thanks for any help.

    Here is an example with a little of everything I mentioned:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.net.URL;
    import javax.imageio.*;
    import java.io.IOException;
    public class SwingExample extends JFrame implements MouseListener {
        public SwingExample() {
            super("This is an example");
            try {
                Image largeImage = ImageIO.read(new URL("http://today.java.net/jag/bio/JagHeadshot.jpg"));
                // ImagePanel is a JComponent subclass (see below)
                ImagePanel displayPanel = new ImagePanel(largeImage);
                // by addint a mouse listener to it, we can listen for clicks on the image
                displayPanel.addMouseListener(this);
                // content pane is the main container for the frame
                Container cp = getContentPane();
                // wraps the image panel in a scroll pane
                JScrollPane scroller = new JScrollPane(displayPanel);
                // tell the scrollbar what size you would like it to be, otherwise
                // it will try to be as large as the viewport component
                scroller.setPreferredSize(new Dimension(100, 100));
                // add the scrollpane to our frame here
                cp.add(scroller);
            catch (IOException ioe) {
                ioe.printStackTrace();
            // swing components use layout managers to help with resizing frames.
            // pack() tries to resize all components to their preferred size using
            // the layout managers. By setting the layout of a component to null,
            // you can use setBounds or setSize to explicitly tell components how
            // big they should be, but they won't automatically resize.
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        // since we said we implement the MouseListener interface, we must include
        // all the methods. Of course, you can leave the body blank if you are not
        // interested in an event
        public void mousePressed(MouseEvent evt) {
            System.out.println("Pressed at " + evt.getX() + "," + evt.getY());
        public void mouseReleased(MouseEvent evt) {
            System.out.println("Released at " + evt.getX() + "," + evt.getY());
        public void mouseClicked(MouseEvent evt) {
            System.out.println("Clicked at " + evt.getX() + "," + evt.getY());
        public void mouseEntered(MouseEvent evt) {
            System.out.println("Entered at " + evt.getX() + "," + evt.getY());
        public void mouseExited(MouseEvent evt) {
            System.out.println("Exited at " + evt.getX() + "," + evt.getY());
        // simple overwritten component to display an image
       class ImagePanel extends JComponent {
           private Image drawImage;
           public ImagePanel(Image image) {
              setImage(image);
           public void setImage(Image image) {
              if (image == null) {
                 this.drawImage = null;
                 return;
              int width = image.getWidth(this);
              // if the image is not fully loaded, it's width will
              // return 0
              if (width <= 0) {
                 MediaTracker tracker = new MediaTracker(this);
                 tracker.addImage(image, 0);
                 try {
                    tracker.waitForID(0);
                 catch (InterruptedException ie) {}
                 width = image.getWidth(this);
              int height = image.getHeight(this);
              this.setPreferredSize(new Dimension(width, height));
              this.drawImage = image;
           // overwrite paintComponent here instead of paint
           public void paintComponent(Graphics g) {
              g.drawImage(drawImage, 0, 0, this);
        public static void main(String[] args) {
            JFrame frame = new SwingExample();
            frame.setVisible(true);
    }

Maybe you are looking for

  • Why does itunes say that my iphone has 9GB of video data even though I've deleted every video I've ever made

    Hello, When I use itunes on my macbook to view the contents of my iphone 5, the bar at the bottom of the window that shows me how much data is taken up for different categories says that I have 9 GB of video data. The thing is, I deleted all of the v

  • After re-install I no longer have iPhoto

    I recently had to carry out a complete erase and install on my G4 12inch PowerBook. (See this thread - http://discussions.apple.com/thread.jspa?threadID=616332&tstart=0) Instead of using the discs that came with my PB I used the newer Tiger OS X DVD

  • Posting date as Baseline Date in Residual item

    Hello, While clearing a document with Residual Clearing method through F-28 system is automatically proposing end of the month as Baseline Date for the residual item (newly created item for the balance amount), whereas we want it to be the posting/do

  • Changing file date name of screenshots

    i had to do a fresh install and now my screenshots are showing up out of order because the default setting is basically dumb as far as AM PM is concerned. can someone remind me if there was a non-applescript or non-terminal way to fix this? i seem to

  • Turn off banner/titlebar from inside customize...

    Is it possible to turn off the banner/titlebar programmatically from your Edit/Edit Defaults page rather than from the Edit Region Settings (for the entire page) The call to PortletRendererUtil.renderPortletHeader(pr, out, headerTitle); seems to dete