SetPreferredSize Error

We have a thick client java application that uses swing classes. One of our dialog windows uses the SetPreferredSize method from the JComponent class to set the dimension of a date data entry field. We recently noticed a problem starting to pop up at some of our installed sites. The horizontal dimension of the date data entry field on the dialog has changed to zero. This is only happening at a handful of installations. Our user can carefully click on that field and enter a date value, however, the data entry field has no horizontal dimension. Does anyone know what could be causing this?

I've seen problems something like this when using GridBagLayout:
import java.awt.*;
import javax.swing.*;
public class GridBagTest
     public static void main(String[] args)
          JFrame f = new JFrame("GridBagTest");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.getContentPane().setLayout( new GridBagLayout() );
          GridBagConstraints gbc = new GridBagConstraints();
          f.getContentPane().add(new JLabel("Name:"), gbc);
          f.getContentPane().add(new JTextField(10), gbc);
          f.pack();
          f.setLocationRelativeTo(null);
          f.setVisible(true);
}Run the code and decrease the width of the frame.
I think the following will help:
component.setMinimumSize( component.getPreferredSize() );

Similar Messages

  • "Class Circle not found in TryBouncingBalls" error message. Help !

    Dear People,
    I have an error message :
    "TryBouncingBalls.java": Error : class Circle not found in class stan_bluej_ch5_p135.TryBouncingBalls at line 67, "
    Circle circle = new Circle(xPos + 130, 30);
    below are the classes TryBouncingBalls, BouncingBall, BallDemo, Canvas
    Thank you in advance
    Stan
    package stan_bluej_ch5_p135;
    import java.awt.*;
    import java.awt.geom.*;
    public class TryBouncingBalls
    public static void main(String[] args)
    Canvas myCanvas = new Canvas("Creativity at its best");
    myCanvas.setVisible(true);
    BouncingBall ball = new BouncingBall(50,50,16, Color.red, 500, myCanvas);
    BouncingBall ball2 = new BouncingBall(70,80,20, Color.green, 500, myCanvas);
    BouncingBall ball3 = new BouncingBall(90,100,16, Color.red, 500, myCanvas);
    BouncingBall ball4 = new BouncingBall(30,30,20, Color.green, 500, myCanvas);
    ball.draw();
    ball2.draw();
    ball.draw();
    ball2.draw();
    // make them bounce
    boolean finished = false;
    while(!finished) {
    myCanvas.wait(50); // small delay
    ball.move();
    ball2.move();
    ball3.move();
    ball4.move();
    // stop once ball has travelled a certain distance on x axis
    if(ball.getXPosition() >= 550 && ball2.getXPosition() >= 550)
    finished = true;
    myCanvas.setFont(new Font("helvetica", Font.BOLD, 14));
    myCanvas.setForegroundColor(Color.red);
    myCanvas.drawString("We are having fun, ...\n\n", 20, 30);
    myCanvas.wait(1000);
    myCanvas.setForegroundColor(Color.black);
    myCanvas.drawString("...drawing lines...", 60, 60);
    myCanvas.wait(500);
    myCanvas.setForegroundColor(Color.gray);
    myCanvas.drawLine(200, 20, 300, 50);
    myCanvas.wait(500);
    myCanvas.setForegroundColor(Color.blue);
    myCanvas.drawLine(220, 100, 370, 40);
    myCanvas.wait(500);
    myCanvas.setForegroundColor(Color.green);
    myCanvas.drawLine(290, 10, 320, 120);
    myCanvas.wait(1000);
    myCanvas.setForegroundColor(Color.gray);
    myCanvas.drawString("...and shapes!", 110, 90);
    myCanvas.setForegroundColor(Color.red);
    myCanvas.drawString("to bring to focus creative ideas !", 310, 290);
    // the shape to draw and move
    int xPos = 10;
    Rectangle rect = new Rectangle(xPos + 40, 150, 30, 20);
    Rectangle rect2 = new Rectangle(xPos + 80, 120, 50, 25);
    Rectangle rect3 = new Rectangle(xPos+ 1200, 180, 30, 30);
    Rectangle rect4 = new Rectangle(xPos + 150, 220, 40, 15);
    myCanvas.fill(rect);
    myCanvas.fill(rect2);
    myCanvas.fill(rect3);
    myCanvas.fill(rect4);
    Circle circle = new Circle(xPos + 130, 30);
    // Circle circle2 = new Circle(xPos + 150, 50);
    // Circle circle3 = new Circle(xPos + 170, 30);
    // Circle circle4 = new Circle(xPos + 200, 40);
    // myCanvas.fill(circle);
    // myCanvas.fill(circle2);
    // myCanvas.fill(circle3);
    // myCanvas.fill(circle4);
    // move the rectangle and circles across the screen
    for(int i = 0; i < 200; i ++) {
    myCanvas.fill(rect);
    myCanvas.fill(rect2);
    myCanvas.fill(rect3);
    myCanvas.fill(rect4);
    myCanvas.wait(10);
    myCanvas.erase(rect);
    myCanvas.erase(rect2);
    myCanvas.erase(rect3);
    myCanvas.erase(rect4);
    xPos++;
    rect.setLocation(xPos, 150);
    rect2.setLocation(xPos, 120);
    rect3.setLocation(xPos, 180);
    rect4.setLocation(xPos, 220);
    // at the end of the move, draw once more so that it remains visible
    myCanvas.fill(rect);
    myCanvas.fill(rect2);
    myCanvas.fill(rect3);
    myCanvas.fill(rect4);
    package stan_bluej_ch5_p135;
    import java.awt.*;
    import java.awt.geom.*;
    * Class BouncingBall - a graphical ball that observes the effect of gravity. The ball
    * has the ability to move. Details of movement are determined by the ball itself. It
    * will fall downwards, accelerating with time due to the effect of gravity, and bounce
    * upward again when hitting the ground.
    * This movement can be initiated by repeated calls to the "move" method.
    * @author Bruce Quig
    * @author Michael Kolling (mik)
    * @author David J. Barnes
    * @version 1.1 (23-Jan-2002)
    public class BouncingBall
    private static final int gravity = 3; // effect of gravity
    private int ballDegradation = 2;
    private Ellipse2D.Double circle;
    private Color color;
    private int diameter;
    private int xPosition;
    private int yPosition;
    private final int groundPosition; // y position of ground
    private Canvas canvas;
    private int ySpeed = 1; // initial downward speed
    * Constructor for objects of class BouncingBall
    * @param xPos the horizontal coordinate of the ball
    * @param yPos the vertical coordinate of the ball
    * @param ballDiameter the diameter (in pixels) of the ball
    * @param ballColor the color of the ball
    * @param groundPos the position of the ground (where the wall will bounce)
    * @param drawingCanvas the canvas to draw this ball on
    public BouncingBall(int xPos, int yPos, int ballDiameter, Color ballColor,
    int groundPos, Canvas drawingCanvas)
    xPosition = xPos;
    yPosition = yPos;
    color = ballColor;
    diameter = ballDiameter;
    groundPosition = groundPos;
    canvas = drawingCanvas;
    * Draw this ball at its current position onto the canvas.
    public void draw()
    canvas.setForegroundColor(color);
    canvas.fillCircle(xPosition, yPosition, diameter);
    * Erase this ball at its current position.
    public void erase()
    canvas.eraseCircle(xPosition, yPosition, diameter);
    * Move this ball according to its position and speed and redraw.
    public void move()
    // remove from canvas at the current position
    erase();
    // compute new position
    ySpeed += gravity;
    yPosition += ySpeed;
    xPosition +=2;
    // check if it has hit the ground
    if(yPosition >= (groundPosition - diameter) && ySpeed > 0) {
    yPosition = (int)(groundPosition - diameter);
    ySpeed = -ySpeed + ballDegradation;
    // draw again at new position
    draw();
    * return the horizontal position of this ball
    public int getXPosition()
    return xPosition;
    * return the vertical position of this ball
    public int getYPosition()
    return yPosition;
    package stan_bluej_ch5_p135;
    import java.awt.*;
    import java.awt.geom.*;
    * Class BallDemo - provides two short demonstrations showing how to use the
    * Canvas class.
    * @author Michael Kolling and David J. Barnes
    * @version 1.0 (23-Jan-2002)
    public class BallDemo
    private Canvas myCanvas;
    * Create a BallDemo object. Creates a fresh canvas and makes it visible.
    public BallDemo()
    myCanvas = new Canvas("Ball Demo", 600, 500);
    myCanvas.setVisible(true);
    * This method demonstrates some of the drawing operations that are
    * available on a Canvas object.
    public void drawDemo()
    myCanvas.setFont(new Font("helvetica", Font.BOLD, 14));
    myCanvas.setForegroundColor(Color.red);
    myCanvas.drawString("We can draw text, ...", 20, 30);
    myCanvas.wait(1000);
    myCanvas.setForegroundColor(Color.black);
    myCanvas.drawString("...draw lines...", 60, 60);
    myCanvas.wait(500);
    myCanvas.setForegroundColor(Color.gray);
    myCanvas.drawLine(200, 20, 300, 50);
    myCanvas.wait(500);
    myCanvas.setForegroundColor(Color.blue);
    myCanvas.drawLine(220, 100, 370, 40);
    myCanvas.wait(500);
    myCanvas.setForegroundColor(Color.green);
    myCanvas.drawLine(290, 10, 320, 120);
    myCanvas.wait(1000);
    myCanvas.setForegroundColor(Color.gray);
    myCanvas.drawString("...and shapes!", 110, 90);
    myCanvas.setForegroundColor(Color.red);
    // the shape to draw and move
    int xPos = 10;
    Rectangle rect = new Rectangle(xPos, 150, 30, 20);
    // move the rectangle across the screen
    for(int i = 0; i < 200; i ++) {
    myCanvas.fill(rect);
    myCanvas.wait(10);
    myCanvas.erase(rect);
    xPos++;
    rect.setLocation(xPos, 150);
    // at the end of the move, draw once more so that it remains visible
    myCanvas.fill(rect);
    * Simulates two bouncing balls
    public void bounce()
    int ground = 400; // position of the ground line
    myCanvas.setVisible(true);
    // draw the ground
    myCanvas.drawLine(50, ground, 550, ground);
    // crate and show the balls
    BouncingBall ball = new BouncingBall(50, 50, 16, Color.blue, ground, myCanvas);
    ball.draw();
    BouncingBall ball2 = new BouncingBall(70, 80, 20, Color.red, ground, myCanvas);
    ball2.draw();
    // make them bounce
    boolean finished = false;
    while(!finished) {
    myCanvas.wait(50); // small delay
    ball.move();
    ball2.move();
    // stop once ball has travelled a certain distance on x axis
    if(ball.getXPosition() >= 550 && ball2.getXPosition() >= 550)
    finished = true;
    ball.erase();
    ball2.erase();
    package stan_bluej_ch5_p135;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    * Class Canvas - a class to allow for simple graphical
    * drawing on a canvas.
    * @author Michael Kolling (mik)
    * @author Bruce Quig
    * @version 1.8 (23.01.2002)
    public class Canvas
    private JFrame frame;
    private CanvasPane canvas;
    private Graphics2D graphic;
    private Color backgroundColor;
    private Image canvasImage;
    * Create a Canvas with default height, width and background color
    * (300, 300, white).
    * @param title title to appear in Canvas Frame
    public Canvas(String title)
    this(title, 600, 600, Color.white);
    * Create a Canvas with default background color (white).
    * @param title title to appear in Canvas Frame
    * @param width the desired width for the canvas
    * @param height the desired height for the canvas
    public Canvas(String title, int width, int height)
    this(title, width, height, Color.white);
    * Create a Canvas.
    * @param title title to appear in Canvas Frame
    * @param width the desired width for the canvas
    * @param height the desired height for the canvas
    * @param bgClour the desired background color of the canvas
    public Canvas(String title, int width, int height, Color bgColor)
    frame = new JFrame();
    canvas = new CanvasPane();
    frame.setContentPane(canvas);
    frame.setTitle(title);
    canvas.setPreferredSize(new Dimension(width, height));
    backgroundColor = bgColor;
    frame.pack();
    * Set the canvas visibility and brings canvas to the front of screen
    * when made visible. This method can also be used to bring an already
    * visible canvas to the front of other windows.
    * @param visible boolean value representing the desired visibility of
    * the canvas (true or false)
    public void setVisible(boolean visible)
    if(graphic == null) {
    // first time: instantiate the offscreen image and fill it with
    // the background color
    Dimension size = canvas.getSize();
    canvasImage = canvas.createImage(size.width, size.height);
    graphic = (Graphics2D)canvasImage.getGraphics();
    graphic.setColor(backgroundColor);
    graphic.fillRect(0, 0, size.width, size.height);
    graphic.setColor(Color.black);
    frame.show();
    * Provide information on visibility of the Canvas.
    * @return true if canvas is visible, false otherwise
    public boolean isVisible()
    return frame.isVisible();
    * Draw the outline of a given shape onto the canvas.
    * @param shape the shape object to be drawn on the canvas
    public void draw(Shape shape)
    graphic.draw(shape);
    canvas.repaint();
    * Fill the internal dimensions of a given shape with the current
    * foreground color of the canvas.
    * @param shape the shape object to be filled
    public void fill(Shape shape)
    graphic.fill(shape);
    canvas.repaint();
    * Fill the internal dimensions of the given circle with the current
    * foreground color of the canvas.
    public void fillCircle(int xPos, int yPos, int diameter)
    Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
    fill(circle);
    * Fill the internal dimensions of the given rectangle with the current
    * foreground color of the canvas. This is a convenience method. A similar
    * effect can be achieved with the "fill" method.
    public void fillRectangle(int xPos, int yPos, int width, int height)
    fill(new Rectangle(xPos, yPos, width, height));
    * Erase the whole canvas.
    public void erase()
    Color original = graphic.getColor();
    graphic.setColor(backgroundColor);
    Dimension size = canvas.getSize();
    graphic.fill(new Rectangle(0, 0, size.width, size.height));
    graphic.setColor(original);
    canvas.repaint();
    * Erase the internal dimensions of the given circle. This is a
    * convenience method. A similar effect can be achieved with
    * the "erase" method.
    public void eraseCircle(int xPos, int yPos, int diameter)
    Ellipse2D.Double circle = new Ellipse2D.Double(xPos, yPos, diameter, diameter);
    erase(circle);
    * Erase the internal dimensions of the given rectangle. This is a
    * convenience method. A similar effect can be achieved with
    * the "erase" method.
    public void eraseRectangle(int xPos, int yPos, int width, int height)
    erase(new Rectangle(xPos, yPos, width, height));
    * Erase a given shape's interior on the screen.
    * @param shape the shape object to be erased
    public void erase(Shape shape)
    Color original = graphic.getColor();
    graphic.setColor(backgroundColor);
    graphic.fill(shape); // erase by filling background color
    graphic.setColor(original);
    canvas.repaint();
    * Erases a given shape's outline on the screen.
    * @param shape the shape object to be erased
    public void eraseOutline(Shape shape)
    Color original = graphic.getColor();
    graphic.setColor(backgroundColor);
    graphic.draw(shape); // erase by drawing background color
    graphic.setColor(original);
    canvas.repaint();
    * Draws an image onto the canvas.
    * @param image the Image object to be displayed
    * @param x x co-ordinate for Image placement
    * @param y y co-ordinate for Image placement
    * @return returns boolean value representing whether the image was
    * completely loaded
    public boolean drawImage(Image image, int x, int y)
    boolean result = graphic.drawImage(image, x, y, null);
    canvas.repaint();
    return result;
    * Draws a String on the Canvas.
    * @param text the String to be displayed
    * @param x x co-ordinate for text placement
    * @param y y co-ordinate for text placement
    public void drawString(String text, int x, int y)
    graphic.drawString(text, x, y);
    canvas.repaint();
    * Erases a String on the Canvas.
    * @param text the String to be displayed
    * @param x x co-ordinate for text placement
    * @param y y co-ordinate for text placement
    public void eraseString(String text, int x, int y)
    Color original = graphic.getColor();
    graphic.setColor(backgroundColor);
    graphic.drawString(text, x, y);
    graphic.setColor(original);
    canvas.repaint();
    * Draws a line on the Canvas.
    * @param x1 x co-ordinate of start of line
    * @param y1 y co-ordinate of start of line
    * @param x2 x co-ordinate of end of line
    * @param y2 y co-ordinate of end of line
    public void drawLine(int x1, int y1, int x2, int y2)
    graphic.drawLine(x1, y1, x2, y2);
    canvas.repaint();
    * Sets the foreground color of the Canvas.
    * @param newColor the new color for the foreground of the Canvas
    public void setForegroundColor(Color blue)
    graphic.setColor(Color.blue);
    * Returns the current color of the foreground.
    * @return the color of the foreground of the Canvas
    public Color getForegroundColor()
    return graphic.getColor();
    * Sets the background color of the Canvas.
    * @param newColor the new color for the background of the Canvas
    public void setBackgroundColor(Color newColor)
    backgroundColor = newColor;
    graphic.setBackground(newColor);
    * Returns the current color of the background
    * @return the color of the background of the Canvas
    public Color getBackgroundColor()
    return backgroundColor;
    * changes the current Font used on the Canvas
    * @param newFont new font to be used for String output
    public void setFont(Font newFont)
    graphic.setFont(newFont);
    * Returns the current font of the canvas.
    * @return the font currently in use
    public Font getFont()
    return graphic.getFont();
    * Sets the size of the canvas.
    * @param width new width
    * @param height new height
    public void setSize(int width, int height)
    canvas.setPreferredSize(new Dimension(width, height));
    Image oldImage = canvasImage;
    canvasImage = canvas.createImage(width, height);
    graphic = (Graphics2D)canvasImage.getGraphics();
    graphic.drawImage(oldImage, 0, 0, null);
    frame.pack();
    * Returns the size of the canvas.
    * @return The current dimension of the canvas
    public Dimension getSize()
    return canvas.getSize();
    * Waits for a specified number of milliseconds before finishing.
    * This provides an easy way to specify a small delay which can be
    * used when producing animations.
    * @param milliseconds the number
    public void wait(int milliseconds)
    try
    Thread.sleep(milliseconds);
    catch (InterruptedException e)
    // ignoring exception at the moment
    * Nested class CanvasPane - the actual canvas component contained in the
    * Canvas frame. This is essentially a JPanel with added capability to
    * refresh the image drawn on it.
    private class CanvasPane extends JPanel
    public void paint(Graphics g)
    g.drawImage(canvasImage, 0, 0, null);

    Dear Miciuli,
    I found the definition for the circle in the canvas class and used it to creates circles ! Thank you for jaring my brain into thinking !
    Stan
    Ellipse2D.Double circle = new Ellipse2D.Double(xPos, 70, 30 , 30);

  • No errors but no sound output . Help !

    Dear Java People,
    I have a program that has a good look with buttons but the
    sound actionPerformed() play() sound does not work.
    Below is the coding and below that is the original version
    Thank you in advance
    Norman
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    public class MyMusicApplet3 extends JApplet implements ActionListener
      AudioClip[] acSounds= new AudioClip[9];
      public void init()
        try
            acSounds[0] = getAudioClip(getCodeBase(),"seashore21"  + ".mid");
            acSounds[1] = getAudioClip(getCodeBase(),"seashore22" + ".mid");
            acSounds[2] = getAudioClip(getCodeBase(),"seashore23"  + ".mid");
           acSounds[3] = getAudioClip(getCodeBase(),"seashore24" + ".mid");
           acSounds[4] = getAudioClip(getCodeBase(),"seashore25"  + ".mid");
           acSounds[5] = getAudioClip(getCodeBase(),"seashore26" + ".mid");
           acSounds[6] = getAudioClip(getCodeBase(),"seashore27"  + ".mid");
          acSounds[7] = getAudioClip(getCodeBase(),"seashore28" + ".mid");
            acSounds[8] = getAudioClip(getCodeBase(),"seashore29" + ".mid");
       catch (Exception e)
        System.out.println("Error here " );
            Container myContentPane = getContentPane();
            myContentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            myContentPane.add(getButton("1", Color.orange, Color.blue));
            myContentPane.add(getButton("2", Color.blue, Color.yellow));
            myContentPane.add(getButton("3", Color.black, Color.white));
            myContentPane.add(getButton("4", Color.black, Color.pink));
            myContentPane.add(getButton("5", Color.white, Color.red));
            myContentPane.add(getButton("6", Color.blue, Color.green));
            myContentPane.add(getButton("7", Color.black, Color.cyan));
            myContentPane.add(getButton("8", Color.black, Color.yellow));
            myContentPane.add(getButton("9", Color.black, Color.cyan));
        public void actionPerformed(ActionEvent e)
           String command = e.getActionCommand();
           int index = Integer.parseInt(command)-1;
           acSounds[index].play();
       public JButton getButton(String label, Color fore, Color back)
         {          JButton button = new JButton("sound "+label);
                    button.setPreferredSize(new Dimension(90,90));
                    button.setFont(new Font("Arial", Font.BOLD,14));
                    button.setBorder(BorderFactory.createRaisedBevelBorder());
                    button.setForeground(fore);
                    button.setBackground(back);
                    button.addActionListener(this);
                    button.setActionCommand(label);
                    return button;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    public class MyMusicApplet_1 extends JApplet implements ActionListener
         JButton myJButton;
         AudioClip acSound_1;
         AudioClip acSound_2;
         AudioClip acSound_3;
         AudioClip acSound_4;
         AudioClip acSound_5;
         AudioClip acSound_6;
         AudioClip acSound_7;
         AudioClip acSound_8;
         AudioClip acSound_9;
         JButton myJButtonSound1;
         JButton myJButtonSound2;
         JButton myJButtonSound3;
         JButton myJButtonSound4;
         JButton myJButtonSound5;
         JButton myJButtonSound6;
         JButton myJButtonSound7;
         JButton myJButtonSound8;
         JButton myJButtonSound9;
      public void init()
            try
             acSound_1 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_2 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_3 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_4 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_5 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_6 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_7 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_8 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_9 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             catch (MalformedURLException e)
               System.out.println("Error here " );
           Container myContentPane = getContentPane();
           myContentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            Dimension buttonSize = new Dimension(190,100);
           Font myFont = new Font("Arial", Font.BOLD,14);
           Border myEdge = BorderFactory.createRaisedBevelBorder();
                    //create 1st button's object
                     myJButtonSound1 = new JButton("sound #1");
                    myJButtonSound1.addActionListener(this);
                   //set the button's border and size, font background and foreground
                   myJButtonSound1.setBorder(myEdge);
                   myJButtonSound1.setPreferredSize(buttonSize);
                   myJButtonSound1.setFont(myFont);
                   myJButtonSound1.setBackground(Color.orange);
                   myJButtonSound1.setForeground(Color.black);
                    //create 2nd button's object
                     myJButtonSound2 = new JButton("sound #2");
                    myJButtonSound2.addActionListener(this);
                   //set the button's border and size, font, background and foreground
                   myJButtonSound2.setBorder(myEdge);
                   myJButtonSound2.setPreferredSize(buttonSize);
                   myJButtonSound2.setFont(myFont);
                   myJButtonSound2.setBackground(Color.blue);
                   myJButtonSound2.setForeground(Color.black);
                    //create 3rd button's object
                     myJButtonSound3 = new JButton("sound #3");
                    myJButtonSound1.addActionListener(this);
                   //set the button's border and size, font, background and foreground
                   myJButtonSound3.setBorder(myEdge);
                   myJButtonSound3.setPreferredSize(buttonSize);
                   myJButtonSound3.setFont(myFont);
                   myJButtonSound3.setBackground(Color.cyan);
                   myJButtonSound3.setForeground(Color.black);
                    //create 4th button's object
                     myJButtonSound4 = new JButton("sound #4");
                    myJButtonSound4.addActionListener(this);
                   //set the button's border and size, font background and foreground
                   myJButtonSound4.setBorder(myEdge);
                   myJButtonSound4.setPreferredSize(buttonSize);
                   myJButtonSound4.setFont(myFont);
                   myJButtonSound4.setBackground(Color.pink);
                   myJButtonSound4.setForeground(Color.black);
                   //create 5th button's object
                   myJButtonSound5 = new JButton("sound #5");
                  myJButtonSound5.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound5.setBorder(myEdge);
                 myJButtonSound5.setPreferredSize(buttonSize);
                 myJButtonSound5.setFont(myFont);
                 myJButtonSound5.setBackground(Color.red);
                 myJButtonSound5.setForeground(Color.black);
                  //create 6th button's object
                   myJButtonSound6 = new JButton("sound #6");
                  myJButtonSound6.addActionListener(this);
                 //set the button's border and size, font, background and foreground
                 myJButtonSound6.setBorder(myEdge);
                 myJButtonSound6.setPreferredSize(buttonSize);
                 myJButtonSound6.setFont(myFont);
                 myJButtonSound6.setBackground(Color.green);
                 myJButtonSound6.setForeground(Color.black);
                  //create 7th button's object
                   myJButtonSound7 = new JButton("Choice #7");
                  myJButtonSound7.addActionListener(this);
                 //set the button's border and size, font, background and foreground
                 myJButtonSound7.setBorder(myEdge);
                 myJButtonSound7.setPreferredSize(buttonSize);
                 myJButtonSound7.setFont(myFont);
                 myJButtonSound7.setBackground(Color.cyan);
                 myJButtonSound7.setForeground(Color.black);
                  //create 8th button's object
                   myJButtonSound8 = new JButton("Choice #8");
                  myJButtonSound8.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound8.setBorder(myEdge);
                 myJButtonSound8.setPreferredSize(buttonSize);
                 myJButtonSound8.setFont(myFont);
                 myJButtonSound8.setBackground(Color.yellow);
                 myJButtonSound8.setForeground(Color.black);
                  //create 9th button's object
                   myJButtonSound9 = new JButton("Choice #9");
                  myJButtonSound9.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound9.setBorder(myEdge);
                 myJButtonSound9.setPreferredSize(buttonSize);
                 myJButtonSound9.setFont(myFont);
                 myJButtonSound9.setBackground(Color.blue);
                 myJButtonSound9.setForeground(Color.black);
                   //add the buttons to the content pane
                   myContentPane.add(myJButtonSound1);
                   myContentPane.add(myJButtonSound2);
                   myContentPane.add(myJButtonSound3);
                   myContentPane.add(myJButtonSound4);
                   myContentPane.add(myJButtonSound5);
                   myContentPane.add(myJButtonSound6);
                   myContentPane.add(myJButtonSound7);
                   myContentPane.add(myJButtonSound8);
                   myContentPane.add(myJButtonSound9);
          public void actionPerformed(ActionEvent e)
             myJButton = (JButton)e.getSource();
            if(myJButton == myJButtonSound1)
              acSound_1.play();
            if(myJButton == myJButtonSound2)
              acSound_2.play();
            if(myJButton == myJButtonSound3)
              acSound_3.play();
            if(myJButton == myJButtonSound4)
              acSound_4.play();
            if(myJButton == myJButtonSound5)
              acSound_5.play();
             if(myJButton == myJButtonSound6)
               acSound_6.play();
                       if(myJButton == myJButtonSound7)
                         acSound_7.play();
                       if(myJButton == myJButtonSound8)
                         acSound_8.play();
                        if(myJButton == myJButtonSound9)
                          acSound_9.play();

    Norman-
    All outawater suggested is that you lop out the code that you are using
    for playing sounds and make sure that works, since that seems to be
    where your problem is. The rest of your (copious amounts of) applet-
    based code is just a distraction at this point.
    No, I have no clues as to your possible error. Though the first step that I would take, if this were my code, would be to isolate the part
    that's giving me troubles and get it as simple as possible - i.e. make
    sure I can write a console app that plays the midi file I want. Then I
    would build up from there - i.e. dump that into an applet with one
    button that does that.
    Good luck to you
    Lee

  • Adding a file to an already created Archive throws error

    Hello Experts,
    In one of the WLST python scripts, we had a piece of code which was adding a file to an already created archive. Below is the code snippet:
    import zipfile
    try:
    conn='1.properties'
    fileName='/home/pbnagara/temp/Zip1.par'
    myZip = zipfile.ZipFile(fileName, mode='a')
    myZip.write(conn)
    myZip.close()
    except Exception:
    print 'Exception occurred while writing to Zip file: ' + fileName
    --> it makes use of the standard python module [zipfile] to add a file to the archive.
    This code has started failing [for some strange unknown reason] when we upgraded.
    The same script works fine in a standalone mode[using the system's default python packages] but fails only when run within WLST.
    Does WLST package a different set of zipfile libraries? Can anyone point out what might be going wrong here?

    I did get a reply from someone on the jfreechart forum, but need to ask more questions. This was his reply:
    Hi Allyson,
    You are trying to add a (subclass of) JFrame to a JPanel...that won't work, of course, and Java tells you so.
    You need to create a ChartPanel to display your chart. This is a subclass of JComponent, which you can happily add to a JPanel (or any other container).
    Regards,
    Dave Gilbert
    Here is the code for the method:
    private void LineChartFrame() {
    double[][] data = new double[][] {
    { 1.0, 4.0, 3.0, 5.0, 5.0, 7.0, 7.0, 8.0 },
    { 5.0, 7.0, 6.0, 8.0, 4.0, 4.0, 2.0, 1.0 },
    { 4.0, 3.0, 2.0, 3.0, 6.0, 3.0, 4.0, 3.0 }
    DefaultCategoryDataset dataset = new DefaultCategoryDataset(data);
    // set the series names...
    String[] seriesNames = new String[] { "First", "Second", "Third" };
    dataset.setSeriesNames(seriesNames);
    // set the category names...
    String[] categories = new String[] { "Type 1", "Type 2", "Type 3", "Type 4", "Type 5", "Type 6", "Type 7", "Type 8" };
    dataset.setCategories(categories);
    // create the chart...
    chart = ChartFactory.createLineChart(
    "Line Chart Demo 1", // chart title
    "Category", // domain axis label
    "Value", // range axis label
    dataset, // data
    true, // include legend
    true, // tooltips
    false); // urls
    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    setContentPane(chartPanel);
    }And I tried this to add it to my panel:
    jPanel1.add(chartPanel, null);But I get this error:
    java.lang.NullPointerException
    ChartPanel is defined globally in this file.
    jPanel1 is my main panel that I want to add the chart to.
    I am putting my last duke dollar on this in the hopes that someone can help. Thanks.
    Allyson

  • "Class can't be instantiated " error message. Help !

    Dear Java People,
    In trying to do a program that outputs a sound with every button click
    I have no compilation errors but a runtime error that says:
    "class can't be instantiated"
    below is the program and below that the error message
    thank you in advance
    Norman
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    public abstract class MyMusicApplet_1 extends JApplet implements ActionListener, AppletContext
         //AppletContext myAppletContext =   new AppletContext();
         //Iterator i =   myAppletContext.getStreamKeys();
         JButton myJButton;
         AudioClip acSound_1;
         AudioClip acSound_2;
         AudioClip acSound_3;
         AudioClip acSound_4;
         AudioClip acSound_5;
         AudioClip acSound_6;
         AudioClip acSound_7;
         AudioClip acSound_8;
         AudioClip acSound_9;
         JButton myJButtonSound1;
         JButton myJButtonSound2;
         JButton myJButtonSound3;
         JButton myJButtonSound4;
         JButton myJButtonSound5;
         JButton myJButtonSound6;
         JButton myJButtonSound7;
         JButton myJButtonSound8;
         JButton myJButtonSound9;
      public void init()
            try
             acSound_1 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_2 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_3 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_4 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_5 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_6 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_7 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_8 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             acSound_9 = getAudioClip(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk"));
             catch (MalformedURLException e)
               System.out.println("Error here " );
           Container myContentPane = getContentPane();
           myContentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            Dimension buttonSize = new Dimension(190,100);
           Font myFont = new Font("Arial", Font.BOLD,14);
           Border myEdge = BorderFactory.createRaisedBevelBorder();
                    //create 1st button's object
                     myJButtonSound1 = new JButton("sound #1");
                    myJButtonSound1.addActionListener(this);
                   //set the button's border and size, font background and foreground
                   myJButtonSound1.setBorder(myEdge);
                   myJButtonSound1.setPreferredSize(buttonSize);
                   myJButtonSound1.setFont(myFont);
                   myJButtonSound1.setBackground(Color.orange);
                   myJButtonSound1.setForeground(Color.black);
                    //create 2nd button's object
                     myJButtonSound2 = new JButton("sound #2");
                    myJButtonSound2.addActionListener(this);
                   //set the button's border and size, font, background and foreground
                   myJButtonSound2.setBorder(myEdge);
                   myJButtonSound2.setPreferredSize(buttonSize);
                   myJButtonSound2.setFont(myFont);
                   myJButtonSound2.setBackground(Color.blue);
                   myJButtonSound2.setForeground(Color.black);
                    //create 3rd button's object
                     myJButtonSound3 = new JButton("sound #3");
                    myJButtonSound1.addActionListener(this);
                   //set the button's border and size, font, background and foreground
                   myJButtonSound3.setBorder(myEdge);
                   myJButtonSound3.setPreferredSize(buttonSize);
                   myJButtonSound3.setFont(myFont);
                   myJButtonSound3.setBackground(Color.cyan);
                   myJButtonSound3.setForeground(Color.black);
                    //create 4th button's object
                     myJButtonSound4 = new JButton("sound #4");
                    myJButtonSound4.addActionListener(this);
                   //set the button's border and size, font background and foreground
                   myJButtonSound4.setBorder(myEdge);
                   myJButtonSound4.setPreferredSize(buttonSize);
                   myJButtonSound4.setFont(myFont);
                   myJButtonSound4.setBackground(Color.pink);
                   myJButtonSound4.setForeground(Color.black);
                   //create 5th button's object
                   myJButtonSound5 = new JButton("sound #5");
                  myJButtonSound5.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound5.setBorder(myEdge);
                 myJButtonSound5.setPreferredSize(buttonSize);
                 myJButtonSound5.setFont(myFont);
                 myJButtonSound5.setBackground(Color.red);
                 myJButtonSound5.setForeground(Color.black);
                  //create 6th button's object
                   myJButtonSound6 = new JButton("sound #6");
                  myJButtonSound6.addActionListener(this);
                 //set the button's border and size, font, background and foreground
                 myJButtonSound6.setBorder(myEdge);
                 myJButtonSound6.setPreferredSize(buttonSize);
                 myJButtonSound6.setFont(myFont);
                 myJButtonSound6.setBackground(Color.pink);
                 myJButtonSound6.setForeground(Color.black);
                  //create 7th button's object
                   myJButtonSound7 = new JButton("Choice #7");
                  myJButtonSound7.addActionListener(this);
                 //set the button's border and size, font, background and foreground
                 myJButtonSound7.setBorder(myEdge);
                 myJButtonSound7.setPreferredSize(buttonSize);
                 myJButtonSound7.setFont(myFont);
                 myJButtonSound7.setBackground(Color.cyan);
                 myJButtonSound7.setForeground(Color.black);
                  //create 8th button's object
                   myJButtonSound8 = new JButton("Choice #8");
                  myJButtonSound8.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound8.setBorder(myEdge);
                 myJButtonSound8.setPreferredSize(buttonSize);
                 myJButtonSound8.setFont(myFont);
                 myJButtonSound8.setBackground(Color.yellow);
                 myJButtonSound8.setForeground(Color.black);
                  //create 9th button's object
                   myJButtonSound9 = new JButton("Choice #9");
                  myJButtonSound9.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound9.setBorder(myEdge);
                 myJButtonSound9.setPreferredSize(buttonSize);
                 myJButtonSound9.setFont(myFont);
                 myJButtonSound9.setBackground(Color.blue);
                 myJButtonSound9.setForeground(Color.black);
                   //add the buttons to the content pane
                   myContentPane.add(myJButtonSound1);
                   myContentPane.add(myJButtonSound2);
                   myContentPane.add(myJButtonSound3);
                   myContentPane.add(myJButtonSound4);
                   myContentPane.add(myJButtonSound5);
                   myContentPane.add(myJButtonSound6);
                   myContentPane.add(myJButtonSound7);
                   myContentPane.add(myJButtonSound8);
                   myContentPane.add(myJButtonSound9);
          public void actionPerformed(ActionEvent e)
             myJButton = (JButton)e.getSource();
            if(myJButton == myJButtonSound1)
              acSound_1.play();
            if(myJButton == myJButtonSound2)
              acSound_2.play();
            if(myJButton == myJButtonSound3)
              acSound_3.play();
            if(myJButton == myJButtonSound4)
              acSound_4.play();
            if(myJButton == myJButtonSound5)
              acSound_5.play();
             if(myJButton == myJButtonSound6)
               acSound_6.play();
                       if(myJButton == myJButtonSound7)
                         acSound_7.play();
                       if(myJButton == myJButtonSound8)
                         acSound_8.play();
                        if(myJButton == myJButtonSound9)
                          acSound_9.play();
    java.lang.InstantiationException
         at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    load: stan_my_music_applet_1.MyMusicApplet_1.class can't be instantiated.
         at java.lang.Class.newInstance0(Class.java:306)
         at java.lang.Class.newInstance(Class.java:259)
         at sun.applet.AppletPanel.createApplet(AppletPanel.java:566)
         at sun.applet.AppletPanel.runLoader(AppletPanel.java:495)
         at sun.applet.AppletPanel.run(AppletPanel.java:292)
         at java.lang.Thread.run(Thread.java:536)

    I also tried:
    try
    for(int a=0;a<8;a++)
    {acSounds[a] = getAudioClip(getCodeBase(),(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore" + (i + 1) + ".wrk")));
    and the error message still says:
    "MyMusicApplet3.java": Error #: 300 : method getAudioClip(java.net.URL, java.net.URL) not found in class stan_my_music_applet_3.MyMusicApplet3 at line 19
    Help !
    below is the revised code
    Norman
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.net.*;
    public class MyMusicApplet3 extends JApplet implements ActionListener
      AudioClip[] acSounds= new AudioClip[9];
      public void init()
       try
            for(int a=0;a<8;a++)
            {acSounds[a] = getAudioClip(getCodeBase(),(new URL ("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore" + (a + 1) + ".wrk")));
      catch (Exception e)
        System.out.println("Error here " );
            Container myContentPane = getContentPane();
            myContentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            myContentPane.add(getButton("1", Color.orange));
            myContentPane.add(getButton("2", Color.blue));
            myContentPane.add(getButton("3", Color.cyan));
            myContentPane.add(getButton("4", Color.pink));
            myContentPane.add(getButton("5", Color.red));
            myContentPane.add(getButton("6", Color.pink));
            myContentPane.add(getButton("7", Color.cyan));
            myContentPane.add(getButton("8", Color.yellow));
            myContentPane.add(getButton("9", Color.blue));
        public void actionPerformed(ActionEvent e)
           String command = e.getActionCommand();
           int index = Integer.parseInt(command)-1;
           acSounds[index].play();
       public JButton getButton(String label, Color fore)
         {          JButton button = new JButton("sound "+label);
                    button.setPreferredSize(new Dimension(190,100));
                    button.setFont(new Font("Arial", Font.BOLD,14));
                    button.setBorder(BorderFactory.createRaisedBevelBorder());
                    button.setForeground(fore);
                    button.setBackground(Color.orange);
                    button.addActionListener(this);
                    button.setActionCommand(label);
                    return button;
          }//"MyMusicApplet3.java": Error #: 300 :
    //method getAudioClip(java.net.URL, java.net.URL) not found in class
    // stan_my_music_applet_3.MyMusicApplet3 at line 19, column 24

  • Errors: can't find symbol, libraries Jung

    Hi, I was trying some graph libraries (Jung) when I got the following errors:
    line 43: cannot find symbol
    symbol : method setPreferredSize(java.awt.Dimension)
    location: class edu.uci.ics.jung.visualization.BasicVisualizationServer<java.lang.Integer,java.lang.String>
    vv.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size
    line 47: cannot find symbol
    symbol : method add(edu.uci.ics.jung.visualization.BasicVisualizationServer<java.lang.Integer,java.lang.String>)
    location: class java.awt.Container
    frame.getContentPane().add(vv);
    I have all the packages that I need, and I copied the code from the official tutorial. How can I solve these problems?
    The code is the following:
    import edu.uci.ics.jung.algorithms.layout.CircleLayout;
    import edu.uci.ics.jung.algorithms.layout.Layout;
    import edu.uci.ics.jung.graph.Graph;
    import edu.uci.ics.jung.graph.SparseMultigraph;
    import edu.uci.ics.jung.visualization.BasicVisualizationServer;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    public class SimpleGraphView {
        Graph<Integer, String> g;
        /** Creates a new instance of SimpleGraphView */
        public SimpleGraphView() {
            // Graph<V, E> where V is the type of the vertices and E is the type of the edges
            g = new SparseMultigraph<Integer, String>();
            // Add some vertices. From above we defined these to be type Integer.
            g.addVertex((Integer)1);
            g.addVertex((Integer)2);
            g.addVertex((Integer)3);
            // Note that the default is for undirected edges, our Edges are Strings.
            g.addEdge("Edge-A", 1, 2); // Note that Java 1.5 auto-boxes primitives
            g.addEdge("Edge-B", 2, 3); 
        public static void main(String[] args) {
            SimpleGraphView sgv = new SimpleGraphView(); //We create our graph in here
            // The Layout<V, E> is parameterized by the vertex and edge types
            Layout<Integer, String> layout = new CircleLayout(sgv.g);
            layout.setSize(new Dimension(300,300)); // sets the initial size of the layout space
            // The BasicVisualizationServer<V,E> is parameterized by the vertex and edge types
            BasicVisualizationServer<Integer,String> vv = new BasicVisualizationServer<Integer,String>(layout);      
            vv.setPreferredSize(new Dimension(350,350)); // <-- First Error
            JFrame frame = new JFrame("Simple Graph View");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(vv); // <-- Second Error
            frame.pack();
            frame.setVisible(true);      
    }

    There are a couple of things I would like to comment on,
    Firstly,
    LukeR. wrote:
    You said that this method is available since 1.5 for class Component, but isn't it called on class BasicVisualizationServer (variable vv)?Ya, you are right, setPreferredSize(Dimension preferredSize) is the method of class Component,
    LukeR. wrote:
    Also
    frame.getContentPane().add(vv), how can it work if the add method wants a Component but gets a BasicVisualizationServer object?If you look at the [JUNG 2.0 API|http://leda.science.uoit.ca/java-libraries/jung-2.0/apidocs/edu/uci/ics/jung/visualization/BasicVisualizationServer.html] BasicVisualizationServer class is inherited from java.awt.Component class, as a result BasicVisualizationServer inherits the properties/methods of its parent Component class!
    Second and more importantly,
    LukeR. wrote:
    I take a look on Jung API and this method doesn't exist.I get a feeling that you are using libraries of the [JUNG 2.0 API|http://leda.science.uoit.ca/java-libraries/jung-2.0/apidocs/overview-summary.html] while looking for the method in [JUNG 1.7.6|http://leda.science.uoit.ca/java-libraries/jung-1.7.6/doc/index.html] or lower API
    Edited by: anamupota on Jan 26, 2009 9:51 PM

  • Error Check does not work

    Hi, I'm having a problem with the following code, when I add alphabetic characters or even nothing at all in the principal amt text field, I expect to get an error message, but I do not. This happens no matter which method I choose to compute the mortgage.
    //Import required libraries
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.text.*;
    import java.math.*;
    import java.util.*;
    public class pos407checkbox extends JFrame implements ActionListener
         // implements ActionListener, ItemListener
         NumberFormat formatter = new DecimalFormat ("$###,###.00");
         //Common Variables
         String ErrorMsg;
         double principal;
         double IntRate;
         int Term;
         double monthlypymt;
         double EndBalance =0;
         double FirstEndBalance =0;
         double interestpmt = 0 ;
         double principlepmt = 0;
         int choice = 0;
         //Components for Menu items
         private JMenuBar menuBar;    
         private JMenuItem exitMenuItem; 
         private JMenu fileMenu; 
         //create the common components
         private JPanel jPanelRadioButton = new JPanel();
         private JPanel jPanelActionButtons = new JPanel();
         JRadioButton jRadiochoice1 = new JRadioButton("I want to enter my own principal, rate and term",false);
         JRadioButton jRadiochoice2 = new JRadioButton("I will enter my own principal, and choose rate and term",false);
         private JButton buttonCompute;
         private JButton buttonNew; 
         private JButton buttonClose;
         //create the components required for jRadiochoice1
         private JPanel jPanelUserEnterAllValues = new JPanel();
         private JLabel jLabelMortgageAmt = new JLabel("Principal Amt(No decimals or commas)");
         private JLabel jLabelMortgageAmt2 = new JLabel("Principal Amt(No decimals or commas)");   
         private JLabel jLabelIntRate = new JLabel("Interest Rate"); 
         private JLabel jLabelTerm = new JLabel("Term - In Years"); 
         private JTextField jTextFieldMortgageAmt = new JTextField();
         private JTextField jTextFieldMortgageAmt2 = new JTextField();
         private JTextField jTextFieldIntRate= new JTextField();
         private JTextField jTextFieldTerm = new JTextField();
         //create the components required for jRadiochoice2
         private JPanel jPanelRateAndTermSelection;
         private JLabel jLabelChooseRateAndTerm; 
         private JComboBox TermAndRate;
         //create the output area
         private JPanel jPanelAmoritizationSchedule;
         private JTextArea jTextAreaAmoritization;
         public pos407checkbox() {            
              super("Mortgage Application");      
               initComponents();      
          private void initComponents()
              setSize(800,460);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
              setVisible(true);           
              Container pane = getContentPane();
              //GridLayout grid = new GridLayout(5, 1);      
              FlowLayout grid = new FlowLayout();      
              pane.setLayout(grid);
              //**********************************MENU BAR**************************//
              menuBar = new JMenuBar();
              fileMenu = new JMenu();
              fileMenu.setText("File");        
              exitMenuItem = new JMenuItem(); 
               exitMenuItem.setText("Exit");
              fileMenu.add(exitMenuItem); 
              menuBar.add(fileMenu);
              //pane.add(menuBar);       
              setJMenuBar(menuBar);
              //*****************************RADIO BUTTON PANEL***************************//
              jPanelRadioButton = new JPanel();
              GridLayout Radio = new GridLayout(1,2);
              jPanelRadioButton.setLayout(Radio);
              ButtonGroup RadioButtons = new ButtonGroup();
              RadioButtons.add(jRadiochoice1);
              RadioButtons.add(jRadiochoice2);
              jPanelRadioButton.add(jRadiochoice1); 
              jPanelRadioButton.add(jRadiochoice2);       
              pane.add(jPanelRadioButton);
              //***********************USER INTERFACE FOR CHOICE 1*******************//
              GridLayout userchoice = new GridLayout(3,2);
              //FlowLayout userchoice = new FlowLayout();           
              jPanelUserEnterAllValues.setLayout(userchoice);
              jPanelUserEnterAllValues.add(jLabelMortgageAmt); 
              jPanelUserEnterAllValues.add(jTextFieldMortgageAmt);       
              jPanelUserEnterAllValues.add(jLabelIntRate);
              jPanelUserEnterAllValues.add(jTextFieldIntRate);       
              jPanelUserEnterAllValues.add(jLabelTerm);
              jPanelUserEnterAllValues.add(jTextFieldTerm); 
              jPanelUserEnterAllValues.setVisible(false);
              pane.add(jPanelUserEnterAllValues);
              //***********************USER INTERFACE FOR CHOICE 2*******************//
              // Create a label that will advise user to enter a principle amount
              jPanelRateAndTermSelection = new JPanel();
              TermAndRate = new JComboBox();
              //Add the selections to the combo box
              TermAndRate.addItem("7 years at 5.35%");
              TermAndRate.addItem("15 years at 5.5%");
              TermAndRate.addItem("30 years at 5.75%");
              //FlowLayout RateAndTerm = new FlowLayout(FlowLayout.CENTER);
              GridLayout RateAndTerm = new GridLayout(2,2);
              jPanelRateAndTermSelection.setLayout(RateAndTerm);
              jPanelRateAndTermSelection.add(jLabelMortgageAmt2);
              jPanelRateAndTermSelection.add(jTextFieldMortgageAmt2);   
              jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
              jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
              jPanelRateAndTermSelection.add(TermAndRate);
              jPanelRateAndTermSelection.setVisible(false);
              pane.add(jPanelRateAndTermSelection);
              //------------------THIRD PANEL CHOOSE ACTION----------------------
              jPanelActionButtons = new JPanel();
              buttonCompute = new JButton("Compute Mortgage");
              buttonNew = new JButton("New Mortgage");
              buttonClose = new JButton("Close");
              FlowLayout Actionbuttons = new FlowLayout(FlowLayout.CENTER);
              jPanelActionButtons.setLayout(Actionbuttons);
              jPanelActionButtons.add(buttonCompute);
              jPanelActionButtons.add(buttonNew);
              jPanelActionButtons.add(buttonClose);
              jPanelActionButtons.setVisible(false);
              pane.add(jPanelActionButtons);
              //*******************ADD THE TEXT AREA FOR OUTPUT TO THE GUI******************//
              jPanelAmoritizationSchedule = new JPanel();
              jTextAreaAmoritization = new JTextArea(26,50);
              JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization, 
              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollBar.setPreferredSize(new Dimension(500,250));
              FlowLayout Amoritization = new FlowLayout();
              jPanelAmoritizationSchedule.setLayout(Amoritization);
              // add scroll pane to output text area
              jPanelAmoritizationSchedule.add(scrollBar);
              jPanelAmoritizationSchedule.setVisible(false);
                pane.add(jPanelAmoritizationSchedule);
              setContentPane(pane);
              //pack();
              // Add Action Listeners
              exitMenuItem.addActionListener(this);
              buttonCompute.addActionListener(this);         
              buttonNew.addActionListener(this);
              buttonClose.addActionListener(this);
              TermAndRate.addActionListener(this);
              jRadiochoice1.addActionListener(this);
              jRadiochoice2.addActionListener(this);
    //create a method that will clear all fields when the New Mortgage button is chosen
    private void clearFields()
         jRadiochoice1.setSelected(false);
         jRadiochoice2.setSelected(false);
         jTextAreaAmoritization.setText("");
         jPanelAmoritizationSchedule.setVisible(false);
         jPanelActionButtons.setVisible(false);
         jTextFieldMortgageAmt.setText("");
         jTextFieldMortgageAmt2.setText("");
         jPanelRadioButton.setVisible(true);
         jPanelUserEnterAllValues.setVisible(false);
         jPanelRateAndTermSelection.setVisible(false);
      public void actionPerformed(ActionEvent e)
              Object source = e.getSource();  
              if (source == exitMenuItem)
                       System.exit(0);
              if(source == buttonClose)
                   System.exit(0);
              if (source == buttonNew)
                   clearFields();
              if (source == jRadiochoice1)
                   jPanelActionButtons.setVisible(true);
                   jPanelRadioButton.setVisible(false);
                   jPanelUserEnterAllValues.setVisible(true);
                   principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                   choice  = 1;
              }//End if for checkbox1
              if (source == jRadiochoice2)
                   jPanelRateAndTermSelection.setVisible(true);
                   jPanelAmoritizationSchedule.setVisible(true);
                   jPanelActionButtons.setVisible(true);
                   jPanelRadioButton.setVisible(false);
                   choice = 2;
              if (source == buttonCompute)
                   jPanelAmoritizationSchedule.setVisible(true);
                   //Make sure the user entered valid numbers for the principal
                   if (choice ==2)
                        int[] term = {7,15,30};
                        double[] rate = {5.35,5.50,5.75};
                        try
                             principal = Double.parseDouble(jTextFieldMortgageAmt2.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                             jTextAreaAmoritization.setText(ErrorMsg);
                        int loan = TermAndRate.getSelectedIndex();
                        Term = term[loan];
                        IntRate = rate[loan];
                   else
                        try
                             principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                             jTextAreaAmoritization.setText(ErrorMsg);
                        try
                             IntRate = Double.parseDouble(jTextFieldIntRate.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You entered an invalid Interest Rate");
                             jTextAreaAmoritization.setText(ErrorMsg);
                        try
                             Term = Integer.parseInt(jTextFieldTerm.getText());
                        catch(NumberFormatException nfe)
                             ErrorMsg = (" You entered an invalid Term value");
                             jTextAreaAmoritization.setText(ErrorMsg);
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal) );
                   double intdecimal = intdecimal = IntRate/(12 * 100);
                   int months = Term * 12;
                   int paymentNum = months;
                   double monthlypayment = principal *(intdecimal / (1- Math.pow((1 + intdecimal),-months)));
                   //Display the Amoritization schedule header info
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal)
                                                    + "\n"
                                                    + " Interest Rate is " +  IntRate + "%"
                                            + "\n"
                                            + " Term in Years "  + Term
                                            + " Monthly payment "+  formatter.format(monthlypayment)
                                            + "\n"
                                            + "  Amoritization is as follows:  "
                                            + "\n"
                                            + "****************************************************************************************************"
                                            + "\n"
                                            + "PAYMENT # " + "\t" + "UNPAIDBALANCE"
                                            + "\t" + "PRINCIPLE PAID" + "\t" + "INTEREST PMT" + "\n\n");
         public static void main(String[]args) { 
              pos407checkbox gui = new pos407checkbox(); 
    }

    it does actually get set.
    the problem is your actionperformed() falls throught to the final
    jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal) etc etc
    at every error handler you need to exit the method
    catch()
    ErrorMsg = (" You entered an invalid Interest Rate");
    jTextAreaAmoritization.setText(ErrorMsg);
    return;//<-------------------
    }

  • Error RE: add method in GUI application

    I'm trying to put three circles (red, yellow, green) in a sub panel called "trafficLight." Unfortunately, I keep getting the following error message that prevents me from compiling the program:
    *.\TrafficPanel.java:36: cannot find symbol*
    symbol  : method add(Circle)
    location: class javax.swing.JPanel
    *          trafficLight.add(red);*
    I believe I have all the import statements necessary, and the program will compile with the trafficLight.add(particular color - red, yellow or green) removed. In other words, if I leave the add(trafficLight); method, the program will compile, and I will see the sub panel trafficLight, just no circles. The class code with the add methods is below followed by my other classes.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class TrafficPanel extends JPanel
         private final int PRIMARY_PANEL_WIDTH = 1000;
         private final int PRIMARY_PANEL_HEIGHT = 700;
         private final int TRAFFICLIGHT_PANEL_WIDTH = 400;
         private final int TRAFFICLIGHT_PANEL_HEIGHT = 660;
         private final int DIAMETER = 30;
         private final int Xr = 10;
         private final int Yr = 10;
         private final int Xy = 10;
         private final int Yy = 200;
         private final int Xg = 10;
         private final int Yg = 400;
         private JPanel trafficLight;
         private Circle red, yellow, green;
         public TrafficPanel()
              setBackground(Color.gray);
              setPreferredSize(new Dimension(PRIMARY_PANEL_WIDTH, PRIMARY_PANEL_HEIGHT));
              trafficLight = new JPanel();
              trafficLight.setBackground(Color.black);
              trafficLight.setPreferredSize(new Dimension(TRAFFICLIGHT_PANEL_WIDTH, TRAFFICLIGHT_PANEL_HEIGHT));
              red = new Circle(Xr, Yr, DIAMETER, DIAMETER, Color.gray);
              yellow = new Circle(Xy, Yy, DIAMETER, DIAMETER, Color.gray);
              green = new Circle(Xg, Yg, DIAMETER, DIAMETER, Color.gray);
              trafficLight.add(red);
              trafficLight.add(yellow);        // PROBLEM AREA. I DON'T KNOW WHY??
              trafficLight.add(green);
              add(trafficLight);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              red.draw(page);
              yellow.draw(page);
              green.draw(page);
    import javax.swing.*;
    import java.awt.*;
    public class Circle
         private int X, Y, Width, Height;
         private Color color;
         public Circle(int x, int y, int width, int height, Color c )
              X = x;
              Y = y;
              Width = width;
              Height = height;
              color = c;
         public void draw(Graphics page)
              page.setColor(color);
              page.fillOval(X, Y, Width, Height);
         public void setColor(Color c)
              color = c;
    import javax.swing.*;
    public class TrafficLight
         public static void main(String[] args)
              JFrame frame = new JFrame("Traffic Light");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              TrafficPanel primary = new TrafficPanel();
              frame.getContentPane().add(primary);
              frame.pack();
              frame.setVisible(true);
    }

    Still having trouble getting the circles to appear on the sub panel "light." They are showing up on the primary panel and being covered by the sub panel. Here's the code. Please give me a strong hint, at least. This is not a school assignment; I'm just trying to learn this for school next fall.
    import javax.swing.*;
    import java.awt.*;
    public class TrafficLight extends JPanel
         Circle red, yellow, green;
         public static void main(String[] args)
              final int DIAMETER = 30;
               final int Xr = 500;
              final int Yr = 10;
              final int Xy = 500;
              final int Yy = 200;
              final int Xg = 500;
               final int Yg = 400;
              JFrame frame = new JFrame("Traffic Light");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              TrafficPanel primary = new TrafficPanel();
              Circle red = new Circle(Xr, Yr, DIAMETER, DIAMETER, Color.red);
              Circle yellow = new Circle(Xr, Yr, DIAMETER, DIAMETER, Color.yellow);
              Circle green = new Circle(Xr, Yr, DIAMETER, DIAMETER, Color.red);
              frame.getContentPane().add(primary);
              frame.pack();
              frame.setVisible(true);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              red.draw(page);
              yellow.draw(page);
              green.draw(page);
    import javax.swing.*;
    import java.awt.*;
    public class TrafficPanel extends JPanel
         private final int PRIMARY_PANEL_WIDTH = 1000;
         private final int PRIMARY_PANEL_HEIGHT = 700;
         private final int TRAFFICPANEL_PANEL_WIDTH = 400;
         private final int TRAFFICPANEL_PANEL_HEIGHT = 660;
         private JPanel light;
         public TrafficPanel()
              setBackground(Color.green);
              setPreferredSize(new Dimension(PRIMARY_PANEL_WIDTH, PRIMARY_PANEL_HEIGHT));
              light = new JPanel();
              light.setBackground(Color.black);
              light.setPreferredSize(new Dimension(TRAFFICPANEL_PANEL_WIDTH, TRAFFICPANEL_PANEL_HEIGHT));
              add(light);
    import javax.swing.*;
    import java.awt.*;
    public class Circle
         private int X, Y, Width, Height;
         private Color color;
         public Circle(int x, int y, int width, int height, Color c )
              X = x;
              Y = y;
              Width = width;
              Height = height;
              color = c;
         public void draw(Graphics page)
              page.setColor(color);
              page.fillOval(X, Y, Width, Height);
         public void setColor(Color c)
              color = c;
    }

  • Errors in code that captures images from webcam

    Here is the code
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture; // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture; // JMF 2.1.1e version
    public class JWebCam extends JFrame
    implements WindowListener, ComponentListener
    protected final static int MIN_WIDTH = 320;
    protected final static int MIN_HEIGHT = 240;
    protected static int shotCounter = 1;
    protected JLabel statusBar = null;
    protected JPanel visualContainer = null;
    protected Component visualComponent = null;
    protected JToolBar toolbar = null;
    protected MyToolBarAction formatButton = null;
    protected MyToolBarAction captureButton = null;
    protected Player player = null;
    protected CaptureDeviceInfo webCamDeviceInfo = null;
    protected MediaLocator ml = null;
    protected Dimension imageSize = null;
    protected FormatControl formatControl = null;
    protected VideoFormat currentFormat = null;
    protected Format[] videoFormats = null;
    protected MyVideoFormat[] myFormatList = null;
    protected boolean initialised = false;
    * Constructor
    public JWebCam ( String frameTitle )
    super ( frameTitle );
    try
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch ( Exception cnfe )
    System.out.println ("Note : Cannot load look and feel settings");
    setSize ( 320, 260 ); // default size...
    addWindowListener ( this );
    addComponentListener ( this );
    getContentPane().setLayout ( new BorderLayout() );
    visualContainer = new JPanel();
    visualContainer.setLayout ( new BorderLayout() );
    getContentPane().add ( visualContainer, BorderLayout.CENTER );
    statusBar = new JLabel ("");
    statusBar.setBorder ( new EtchedBorder() );
    getContentPane().add ( statusBar, BorderLayout.SOUTH );
    * Initialise
    * @returns true if web cam is detected
    public boolean initialise ( )
    throws Exception
    return ( initialise ( autoDetect() ) );
    * Initialise
    * @params _deviceInfo, specific web cam device if not autodetected
    * @returns true if web cam is detected
    public boolean initialise ( CaptureDeviceInfo _deviceInfo )
    throws Exception
    statusBar.setText ( "Initialising...");
    webCamDeviceInfo = _deviceInfo;
    if ( webCamDeviceInfo != null )
    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
    try
    setUpToolBar();
    getContentPane().add ( toolbar, BorderLayout.NORTH );
    ml = webCamDeviceInfo.getLocator();
    if ( ml != null )
    player = Manager.createRealizedPlayer ( ml );
    if ( player != null )
    player.start();
    formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
    videoFormats = webCamDeviceInfo.getFormats();
    visualComponent = player.getVisualComponent();
    if ( visualComponent != null )
    visualContainer.add ( visualComponent, BorderLayout.CENTER );
    myFormatList = new MyVideoFormat[videoFormats.length];
    for ( int i=0; i<videoFormats.length; i++ )
    myFormatList = new MyVideoFormat ( (VideoFormat)videoFormats );
    Format currFormat = formatControl.getFormat();
    if ( currFormat instanceof VideoFormat )
    currentFormat = (VideoFormat)currFormat;
    imageSize = currentFormat.getSize();
    visualContainer.setPreferredSize ( imageSize );
    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
    else
    System.err.println ("Error : Cannot get current video format");
    invalidate();
    pack();
    return ( true );
    else
    System.err.println ("Error : Could not get visual component");
    return ( false );
    else
    System.err.println ("Error : Cannot create player");
    statusBar.setText ( "Cannot create player" );
    return ( false );
    else
    System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
    statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
    return ( false );
    catch ( IOException ioEx )
    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
    return ( false );
    catch ( NoPlayerException npex )
    statusBar.setText ("Cannot create player");
    return ( false );
    catch ( CannotRealizeException nre )
    statusBar.setText ( "Cannot realize player");
    return ( false );
    else
    return ( false );
    * Dynamically create menu items
    * @returns the device info object if found, null otherwise
    public void setFormat ( VideoFormat selectedFormat )
    if ( formatControl != null )
    player.stop();
    imageSize = selectedFormat.getSize();
    formatControl.setFormat ( selectedFormat );
    player.start();
    statusBar.setText ( "Format : " + selectedFormat );
    currentFormat = selectedFormat;
    visualContainer.setPreferredSize ( currentFormat.getSize() );
    setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
    else
    System.out.println ("Visual component not an instance of FormatControl");
    statusBar.setText ( "Visual component cannot change format" );
    public VideoFormat getFormat ( )
    return ( currentFormat );
    protected void setUpToolBar ( )
    toolbar = new JToolBar();
    // Note : If you supply the 16 x 16 bitmaps then you can replace
    // the commented line in the MyToolBarAction constructor
    formatButton = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
    captureButton = new MyToolBarAction ( "Capture", "BtnCapture.jpg" );
    toolbar.add ( formatButton );
    toolbar.add ( captureButton );
    getContentPane().add ( toolbar, BorderLayout.NORTH );
    protected void toolbarHandler ( MyToolBarAction actionBtn )
    if ( actionBtn == formatButton )
    Object selected = JOptionPane.showInputDialog (this,
    "Select Video format",
    "Capture format selection",
    JOptionPane.INFORMATION_MESSAGE,
    null, // Icon icon,
    myFormatList, // videoFormats,
    currentFormat );
    if ( selected != null )
    setFormat ( ((MyVideoFormat)selected).format );
    else if ( actionBtn == captureButton )
    Image photo = grabFrameImage ( );
    if ( photo != null )
    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
    else
    System.err.println ("Error : Could not grab frame");
    * autoDetects the first web camera in the system
    * searches for video for windows ( vfw ) capture devices
    * @returns the device info object if found, null otherwise
    public CaptureDeviceInfo autoDetect ( )
    Vector list = CaptureDeviceManager.getDeviceList ( null );
    CaptureDeviceInfo devInfo = null;
    if ( list != null )
    String name;
    for ( int i=0; i<list.size(); i++ )
    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
    name = devInfo.getName();
    if ( name.startsWith ("vfw:") )
    break;
    if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
    return ( devInfo );
    else
    for ( int i = 0; i < 10; i++ )
    try
    name = VFWCapture.capGetDriverDescriptionName ( i );
    if (name != null && name.length() > 1)
    devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
    if ( devInfo != null )
    return ( devInfo );
    catch ( Exception ioEx )
    // ignore errors detecting device
    statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
    return ( null );
    else
    return ( null );
    * deviceInfo
    * @note outputs text information
    public void deviceInfo ( )
    if ( webCamDeviceInfo != null )
    Format[] formats = webCamDeviceInfo.getFormats();
    if ( ( formats != null ) && ( formats.length > 0 ) )
    for ( int i=0; i<formats.length; i++ )
    Format[] aFormat = formats;
    if ( aFormat[i] instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats.getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) { }
    public void windowClosed ( WindowEvent e ) { }
    public void windowDeactivated ( WindowEvent e ) { }
    public void windowDeiconified ( WindowEvent e ) { }
    public void windowIconified ( WindowEvent e ) { }
    public void windowOpened ( WindowEvent e ) { }
    public void componentHidden(ComponentEvent e) { }
    public void componentMoved(ComponentEvent e) { }
    public void componentShown(ComponentEvent e) { }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat _format )
    format = _format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MySnapshot extends JFrame
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();
    when I run it I get the following errors
    BufferToImage cannot convert buffer
    could not grab frame
    pls help

    Do you expect anyone to read this?
    http://forum.java.sun.com/help.jspa?sec=formatting
    By the way, you have a condition that makes it print those messages. Check why that condiiton isn't rue.

  • "should be declared abstract" error message Help !

    Dear People,
    I have two error messages in my program
    "should be declared abstract"
    "getAudioClip() not found "
    Your advice is appreciated
    Norman
    "MyMusicApplet_1.java": Error #: 454 : class stan_my_music_applet_1.MyMusicApplet_1 should be declared abstract; it does not define method getStreamKeys() in interface java.applet.AppletContext at line 9
    "MyMusicApplet_1.java": Error #: 300 : method getAudioClip(java.lang.String) not found in class stan_my_music_applet_1.MyMusicApplet_1
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.applet.*;
    import java.awt.event.*;
    public class MyMusicApplet_1 extends JApplet implements ActionListener, AppletContext
         //AppletContext myAppletContext =   new AppletContext();
         //Iterator i =   myAppletContext.getStreamKeys();
         JButton myJButton;
         AudioClip acSound_1 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk");
         AudioClip acSound_2 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_3 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_4 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_5 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_6 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_7 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_8 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         AudioClip acSound_9 = getAudioClip("c:/Program Files/Cakewalk/Cakewalk Pro Audio 9/seashore.wrk   ");
         JButton myJButtonSound1;
         JButton myJButtonSound2;
         JButton myJButtonSound3;
         JButton myJButtonSound4;
         JButton myJButtonSound5;
         JButton myJButtonSound6;
         JButton myJButtonSound7;
         JButton myJButtonSound8;
         JButton myJButtonSound9;
      public void init()
           Container myContentPane = getContentPane();
           myContentPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            Dimension buttonSize = new Dimension(190,100);
           Font myFont = new Font("Arial", Font.BOLD,14);
           Border myEdge = BorderFactory.createRaisedBevelBorder();
                    //create 1st button's object
                     myJButtonSound1 = new JButton("sound #1");
                    myJButtonSound1.addActionListener(this);
                   //set the button's border and size, font background and foreground
                   myJButtonSound1.setBorder(myEdge);
                   myJButtonSound1.setPreferredSize(buttonSize);
                   myJButtonSound1.setFont(myFont);
                   myJButtonSound1.setBackground(Color.orange);
                   myJButtonSound1.setForeground(Color.black);
                    //create 2nd button's object
                     myJButtonSound2 = new JButton("sound #2");
                    myJButtonSound2.addActionListener(this);
                   //set the button's border and size, font, background and foreground
                   myJButtonSound2.setBorder(myEdge);
                   myJButtonSound2.setPreferredSize(buttonSize);
                   myJButtonSound2.setFont(myFont);
                   myJButtonSound2.setBackground(Color.blue);
                   myJButtonSound2.setForeground(Color.black);
                    //create 3rd button's object
                     myJButtonSound3 = new JButton("sound #3");
                    myJButtonSound1.addActionListener(this);
                   //set the button's border and size, font, background and foreground
                   myJButtonSound3.setBorder(myEdge);
                   myJButtonSound3.setPreferredSize(buttonSize);
                   myJButtonSound3.setFont(myFont);
                   myJButtonSound3.setBackground(Color.cyan);
                   myJButtonSound3.setForeground(Color.black);
                    //create 4th button's object
                     myJButtonSound4 = new JButton("sound #4");
                    myJButtonSound4.addActionListener(this);
                   //set the button's border and size, font background and foreground
                   myJButtonSound4.setBorder(myEdge);
                   myJButtonSound4.setPreferredSize(buttonSize);
                   myJButtonSound4.setFont(myFont);
                   myJButtonSound4.setBackground(Color.pink);
                   myJButtonSound4.setForeground(Color.black);
                   //create 5th button's object
                   myJButtonSound5 = new JButton("sound #5");
                  myJButtonSound5.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound5.setBorder(myEdge);
                 myJButtonSound5.setPreferredSize(buttonSize);
                 myJButtonSound5.setFont(myFont);
                 myJButtonSound5.setBackground(Color.red);
                 myJButtonSound5.setForeground(Color.black);
                  //create 6th button's object
                   myJButtonSound6 = new JButton("sound #6");
                  myJButtonSound6.addActionListener(this);
                 //set the button's border and size, font, background and foreground
                 myJButtonSound6.setBorder(myEdge);
                 myJButtonSound6.setPreferredSize(buttonSize);
                 myJButtonSound6.setFont(myFont);
                 myJButtonSound6.setBackground(Color.pink);
                 myJButtonSound6.setForeground(Color.black);
                  //create 7th button's object
                   myJButtonSound7 = new JButton("Choice #7");
                  myJButtonSound7.addActionListener(this);
                 //set the button's border and size, font, background and foreground
                 myJButtonSound7.setBorder(myEdge);
                 myJButtonSound7.setPreferredSize(buttonSize);
                 myJButtonSound7.setFont(myFont);
                 myJButtonSound7.setBackground(Color.cyan);
                 myJButtonSound7.setForeground(Color.black);
                  //create 8th button's object
                   myJButtonSound8 = new JButton("Choice #8");
                  myJButtonSound8.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound8.setBorder(myEdge);
                 myJButtonSound8.setPreferredSize(buttonSize);
                 myJButtonSound8.setFont(myFont);
                 myJButtonSound8.setBackground(Color.yellow);
                 myJButtonSound8.setForeground(Color.black);
                  //create 9th button's object
                   myJButtonSound9 = new JButton("Choice #9");
                  myJButtonSound9.addActionListener(this);
                 //set the button's border and size, font background and foreground
                 myJButtonSound9.setBorder(myEdge);
                 myJButtonSound9.setPreferredSize(buttonSize);
                 myJButtonSound9.setFont(myFont);
                 myJButtonSound9.setBackground(Color.blue);
                 myJButtonSound9.setForeground(Color.black);
                   //add the buttons to the content pane
                   myContentPane.add(myJButtonSound1);
                   myContentPane.add(myJButtonSound2);
                   myContentPane.add(myJButtonSound3);
                   myContentPane.add(myJButtonSound4);
                   myContentPane.add(myJButtonSound5);
                   myContentPane.add(myJButtonSound6);
                   myContentPane.add(myJButtonSound7);
                   myContentPane.add(myJButtonSound8);
                   myContentPane.add(myJButtonSound9);
          public void actionPerformed(ActionEvent e)
             myJButton = (JButton)e.getSource();
            if(myJButton == myJButtonSound1)
              acSound_1.play();
            if(myJButton == myJButtonSound2)
              acSound_2.play();
            if(myJButton == myJButtonSound3)
              acSound_3.play();
            if(myJButton == myJButtonSound4)
              acSound_4.play();
            if(myJButton == myJButtonSound5)
              acSound_5.play();
             if(myJButton == myJButtonSound6)
               acSound_6.play();
                       if(myJButton == myJButtonSound7)
                         acSound_7.play();
                       if(myJButton == myJButtonSound8)
                         acSound_8.play();
                        if(myJButton == myJButtonSound9)
                          acSound_9.play();
      }

    The "should be declared abstract" error message means that you have either extended an abstract class with abstract methods that you have not implemented, or you have implemented an interface and not implemented all of its methods. Non abstract classes have to implement all methods that their base classes or interfaces declare.
    The "getAudioClip() not found" error message means that the compiler could not find the method getAudioClip(). Either your class or one of its base classes has to define this method.

  • Error with swing

    Hi,
    I am having the error with a basic start to a swing application, any hel;p would me much appreciated
    this is the error i keep receiving (it is not always child 11)
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: No such child: 11
    at java.awt.Container.getComponent(Unknown Source)
    at javax.swing.JComponent.rectangleIsObscured(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintToOffscreen(Unknown Source)
    at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
    at javax.swing.RepaintManager.paint(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    The code to produce this error is as follows.
    import javax.swing.*;
    import java.awt.*;
    class play
    public monster monster_arr[]=new monster[30];
    int move_dirx;
    boolean game_playing=true;
    public play()
        for(int i=0,num=0,pos=0;i<30;i++)
            if(i%10==0) { num++; pos=0;}
            //new monster;
            monster_arr=new monster(pos,(num*50)+5);
    pos+=25;
    public void start_play()
    JFrame win = new JFrame("window");
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    win.setLocation(426,250);
    win.setSize(400,400);
    JPanel panel = new JPanel();
    JPanel bufpanel = new JPanel();
    //win.setDefaultL&F(true);
    //win.pack();
    win.setVisible(true);
    for(/*JPanel tmppanel=update_pane()*/int s=1;game_playing==true;/*tmppanel=update_pane()*/)
    //for(;;)
    /*if(i%5!=0) continue;
    else if(i>9999) i=0;*/
    try
    Thread.sleep(80);
    catch(Exception e)
    //System.out.println("i : "+i);
    //panel=tmppanel;
    panel = update_pane();
    //panel.updateUI();
    //win.remove(bufpanel);
    win.remove(panel);
    win.add(panel);
    //win.getContentPane().add(panel);
    win.validate();
    System.out.println("game over");
    public JPanel update_pane()
    JPanel pane = new JPanel(true);
    pane.setPreferredSize(new Dimension(400,400));
    pane.setLayout(null);
    pane.setBackground(Color.black);
    /*for(int i=0,num=0,pos=0;i<30;i++)
    if(i%10==0) { num++; pos=0;}
    monster_arr[i]= new monster(pos,(num*50)+5);
    pos+=25;
    if(monster_arr[9].getPosx()>=380)
    move_dirx=-1;
    incremnt_posy();
    else if(monster_arr[0].getPosx()<=0)
    move_dirx=+1;
    incremnt_posy();
    for(int i=0;i<30;i++)
    //System.out.println("i : "+i);
    monster_arr[i].setPosx(monster_arr[i].getPosx()+move_dirx);
    monster_arr[i].setBounds(monster_arr[i].getPosx(),monster_arr[i].getPosy(),20,29);// X , Y , Width , Heigh
    pane.add(monster_arr[i]);
    return pane;
    public void incremnt_posy()
    for(int i=0;i<30;i++)
    monster_arr[i].setPosy(monster_arr[i].getPosy()+5);
    if(monster_arr[i].getPosy()>351)
    game_playing=false;
    break;
    Monster Classimport javax.swing.*;
    import java.awt.*;
    class monster extends JLabel
    int posx, posy;
    //JLabel lab_img;
    int height, width;
    public monster(int x,int y)
    posx=x;
    posy=y;
    this.setIcon( new ImageIcon ("alien.gif"));
    public int getPosx()
    return posx;
    public int getPosy()
    return posy;
    public void setPosx(int x)
    posx=x;
    public void setPosy(int y)
    posy=y;
    Any assistance would be amazing i have come to a wits end
    Thanks for your time
    Edited by: mousehunt on Apr 2, 2009 4:51 AM
    Edited by: mousehunt on Apr 2, 2009 4:54 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Ok sorry i mark this as answered to get it out the way
    Thanks

  • Error: NullPointerException

    HI All ,
    Error : NullPointerException .
    I have got this above error in the Reciever comm channel of JMS Adapter ,
    Could anyone answer detailly .
    Regards.
    Syed Nayeem.

    Umm, this is what my code looks like. I tried it, but it doesn't work.
    import model.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.*;
    public class ButtonPanel extends JPanel implements View
        private Prison prison;
        private LeftInputPanel leftInput = new LeftInputPanel(prison);
        private DaysPanel days;
        private MonthsPanel months;
        private YearsPanel years;
        private CrimePanel crime;
        private AllocateListener aListener = new AllocateListener();
        public ButtonPanel(Prison prison)
            this.prison = prison;
            setup();
            build();
        public void setup()
        public void build()
            JButton button = new JButton("Allocate Cell");
            Dimension size = new Dimension(240, 70);
            button.setPreferredSize(size);
            button.setMinimumSize(size);
            button.setMaximumSize(size);
            button.addActionListener(aListener);
            add(button);
            update();
        public void update()
            leftInput.update();
    private class AllocateListener implements ActionListener
        public void actionPerformed(ActionEvent e)
            Criminal criminal = new Criminal(leftInput.name());
            Period period = new Period(days.days(), months.months(), years.years());  //nullPointerException here
            criminal.set(new Crime(crime.getCrime()));
            prison.add(criminal);
    }Edited by: karen.tao on Oct 24, 2009 6:11 AM

  • Property change listener error with jtabbedpane

    Greetings
    I have a property change listener on my jtabbedpane (2 panes (index 0 of course and index 1). my problem is when i want to run my app it gives me a java null pointer exception. I believe it is b/c it is starting the app and it see the property change of the first tab at index 0 which is the first tab it sees and tries to run the method that makes the buttons visibility to true. but the buttons are already true. Basically how can I get the property change to run only after the app is visible? I made the buttons visibility false on startup to see if it can run the app but I still got the same error. I hope I am clear enough, if I am not please and I will attempt to reiterate the situation better. thanks for anyones help.
    tabs = new JTabbedPane();
              tabs.addChangeListener(this);
              tabs.setPreferredSize(new java.awt.Dimension(800, 400));
              tabs.addTab("Q", tab1.getMa());
              tabs.addTab("R", tab2);
      public void stateChanged(ChangeEvent changeEvent) {
                JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
               int index = sourceTabbedPane.getSelectedIndex();
               //System.out.println("Tab changed to: " + sourceTabbedPane.getTitleAt(index)+"  Index: "+index);
               if (index==1){
                         changeButtonsF();
                             ///makes buttons false on side panel
               else if (index==0){
                    changeButtonsT();
                     //makes buttons true on side panel
           }

    Basically how can I get the property change to run only after the app is visible?Add the PropertyChangeListener to the tabbed pane after the JFrame is visible.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

  • Error after compiling because of scroll

    I would like to get scrollbars (vertical and horizontal) after doing the Pascal's Triangle that appends in the JTextArea named "prog", inside the JPanel "dret".
    I've tried lots of things in teh code, but I get, after compiling:
    "Exception in thread "main" java.kang.IllegalArgumentException: adding container's parent to itself
    at java.awt.Container.addImpl(Container.java:309)
    at java.awt.Container.add(Container.java:210)
    at cerni.<init>(cerni.java:218)
    at cerni.main(cerni.java:261)
    Here the java code:
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.IOException.*;
    import javax.swing.text.*;
    import java.util.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class cerni extends JFrame {
         //declaraci� de variables.
         JPanel principal, centre, esquerre, dret, intro, esquerrealt, esquerrebaix;
         JButton element2, element3, element4, element6;
         JTextArea prog;
         JTextField element1, element5, introtext;
         static String newline = System.getProperty("line.separator");
         //funci� binominal.     
         public static int binominal (int n, int p) {
              if (p * (n-p) == 0)
                   return(1);
              else
                   return(binominal(n-1, p-1) + binominal(n-1,p));
         //funci� cerni.
         public cerni() {
              //t�tol.
              super(" �-_JavaPascal_-`");
              //definici� de variables.
              principal = new JPanel();
              centre = new JPanel();
              esquerre = new JPanel();
              dret = new JPanel();
              intro = new JPanel();
              esquerrealt = new JPanel();
              esquerrebaix = new JPanel();     
              element2 = new JButton("Informaci�");
              element4 = new JButton("Fer el triangle");
              element3 = new JButton("Sortir");     
              element6 = new JButton("Netejar la pantalla");          
              element1 = new JTextField("");
              element5 = new JTextField(" Entreu el valor d' n+1 files del triangle de Pascal.");
              introtext = new JTextField(" Benvinguts al programa JavaPascal, el programa escrit i compilat en java que dibuixa el triangle de Pascal.");
              prog = new JTextArea();
              //propietats de texts.
              introtext.setFont(new Font("Serif", Font.ITALIC, 16));          
              prog.setFont(new Font("Serif", Font.ITALIC, 16));
              prog.setLineWrap(true);
              prog.setCaretPosition(prog.getText().length());
              element5.setEditable(false);
              introtext.setEditable(false);
              prog.setEditable(false);
              //minimissatge del principi.          
              JOptionPane.showMessageDialog(principal, " Benvinguts al programa JavaPascal.", " -> Bon dia!! <- ",JOptionPane.INFORMATION_MESSAGE);
              //bot� netejar.
              element6.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e){
                        String o = new String();
                        prog.setText(o);
              //bot� informaci�.
              element2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e){
                        JOptionPane.showMessageDialog(principal, "El programa JavaPascal ha estat escrit per Cerni Pol durant els dies 11 i 12 de maig del 2002.\nAmb una estructura de JFrame i JPanels, m�s JButtons i components de text, l'aplicaci� en q�esti� us exposar�\nel triangle de Pascal, en tantes files com li demaneu, al camp de text de la dreta.\nNo �s recomanable demanar un n m�s gran de 25, per aix� tenir un millor rendiment en l'operaci� de la compu-\ntadora. (rendiment provat en un processador Pentium2 a 450 mhz)\nQue us ho passeu b� amb aquest programa.\n(Enjoy.)");
              //bot� sortir.
              element3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e){
                        System.exit (0);
              //bot� pascal.
              element4.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e){
                        int n, p, c;
                        c = 10;
                        String s1 = element1.getText();
                        c = Integer.parseInt(s1);
                        n = 0;
                        p = 0;
                        for (n=0; n<c+1; n++){
                             prog.append(cerni.newline);
                             for (p=0; p<n+1;p++){
                                  String s = Integer.toString(binominal (n,p));
                                  prog.append(s);
                                  prog.append(" ");
                   prog.append(cerni.newline);     
              //panell esquerrealt.
              esquerrealt.setLayout(new GridLayout(4, 0));
         esquerrealt.setBorder(BorderFactory.createEmptyBorder(
         30, //top
         20, //left
         40, //bottom
         20) //dret
              esquerrealt.add(element5);
              esquerrealt.add(element4);
              esquerrealt.add(element1);
              esquerrealt.add(element6);
              //panell esquerrebaix.
              esquerrebaix.setLayout(new GridLayout(0, 2));
              esquerrebaix.setBorder(BorderFactory.createEmptyBorder(30, 30, 20, 30));
              esquerrebaix.add(element2);
              esquerrebaix.add(element3);     
              //panell esquerre.
              esquerre.setLayout(new BorderLayout());
              esquerre.add(esquerrealt, "North");
              esquerre.add(esquerrebaix, "South");
              JScrollPane dretScrollPane = new JScrollPane(dret);
              dretScrollPane.createVerticalScrollBar();
              dretScrollPane.createHorizontalScrollBar();          
              dretScrollPane.setVerticalScrollBarPolicy
              (JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
              dretScrollPane.setHorizontalScrollBarPolicy
              (JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              dret.add(dretScrollPane);          
              //panell dret.          
              dret.setLayout(new BorderLayout());
              dret.add(prog, "Center");
              //panell centre.
              centre.setPreferredSize(new Dimension(800, 700));
              centre.setBorder(BorderFactory.createEmptyBorder(30, 30, 20, 30));     
              centre.setLayout(new GridLayout(0, 2));
              centre.add(esquerre);
              centre.add(dret);     
              //panell intro.          
              intro.setLayout(new BorderLayout());
              intro.add(introtext, "Center");
              //panell principal.
              principal.setLayout(new BorderLayout());
              principal.setBorder(BorderFactory.createEmptyBorder(30, 30, 20, 30));
              principal.add(centre, "Center");
              principal.add(intro, "North");
              setContentPane(principal);
         //main.     
         public static void main (String[] args) {
              JFrame principal = new cerni();
              principal.addWindowListener (new WindowAdapter () {
                   public void windowClosing (WindowEvent e) {System.exit(0);}
         principal.show();
         principal.pack();
         principal.setSize(800, 700);
    Thanks to help me.

    Hi...
    The line is error is below...
    dret.add(dretScrollPane);You've already added dret to the scrollpane in the constructor of the scrollpane (some 6/7 lines above the line above). Simply add the scrollpane to the main frame (pane) now.
    Merry Christmas

  • Help me w/ the method setPreferredSize

    guyz, im having problems w/ this....when i compiled it it gave me an error..it says the method cannot be resolved...pls help me.... heres the prog...thanks in advance
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import java.awt.*;
    * Il vostro primo componente Swing!
    public class SimpleFrame extends JFrame {
    * Costruisce un nuovo JFrame contenente una JLabel
    SimpleFrame() {
    super();
    setTitle("Il mio primo componente Swing!");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    add(new JLabel("Benvenuti in Swing!", JLabel.CENTER));
    // setPreferredSize(new Dimension(150, 100));
    pack();
    setVisible(true);
    * Crea un'istanza di questa classe
    public static void main(String[] args) {
    SimpleFrame sf = new SimpleFrame();
    }

    setPreferredSize is not a method of JFrame. Use SetSize instead.

Maybe you are looking for