Monday, February 17, 2020

Exercise – 16 (Swings - Continued)


Exercise – 16 (Swings - Continued)

a). Write a JAVA program that to create a single ball bouncing inside a JPanel.



import java.awt.*;
import javax.swing.*;

public class BouncingBall extends JPanel {

  // Box height and width
  int width;
  int height;

  // Ball Size
  float radius = 40;
  float diameter = radius * 2;

  // Center of Call
  float X = radius + 50;
  float Y = radius + 20;

  // Direction
  float dx = 3;
  float dy = 3;

  public BouncingBall() {

    Thread thread = new Thread() {
      public void run() {
        while (true) {

          width = getWidth();
          height = getHeight();

          X = X + dx ;
          Y = Y + dy;

          if (X - radius < 0) {
            dx = -dx;
            X = radius;
          } else if (X + radius > width) {
            dx = -dx;
            X = width - radius;
          }

          if (Y - radius < 0) {
            dy = -dy;
            Y = radius;
          } else if (Y + radius > height) {
            dy = -dy;
            Y = height - radius;
          }
          repaint();

          try {
            Thread.sleep(50);
          } catch (InterruptedException ex) {
          }

        }
      }
    };
    thread.start();
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.fillOval((int)(X-radius), (int)(Y-radius), (int)diameter, (int)diameter);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Bouncing Ball");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 200);
    frame.setContentPane(new BouncingBall());
    frame.setVisible(true);
  }
}


b). Write a JAVA program JTree as displaying a real tree upside down



import javax.swing.*; 
import javax.swing.tree.DefaultMutableTreeNode; 
public class TreeExample extends JFrame { 
JFrame f; 
TreeExample(){ 
    f=new JFrame(); 
    DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style"); 
    DefaultMutableTreeNode color=new DefaultMutableTreeNode("color"); 
    DefaultMutableTreeNode font=new DefaultMutableTreeNode("font"); 
    style.add(color); 
    style.add(font); 
    DefaultMutableTreeNode red=new DefaultMutableTreeNode("red"); 
    DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue"); 
    DefaultMutableTreeNode black=new DefaultMutableTreeNode("black"); 
    DefaultMutableTreeNode green=new DefaultMutableTreeNode("green"); 
    color.add(red); color.add(blue); color.add(black); color.add(green);     
    JTree jt=new JTree(style); 
    f.add(jt); 
    f.setSize(200,200); 
    f.setVisible(true); 

public static void main(String[] args) { 
    new TreeExample(); 
}}

No comments:

Post a Comment

JAVA PROGRAMMING ASSIGNMENT 2 QUESTIONS

SIR C R REDDY COLLEGE OF ENGINEERING, ELURU DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING JAVA PROGRAMMING ASSIGNMENT 2 QUESTIONS ...