ja9
- Write a Java program to create a thread for moving a ball inside a panel vertically. The
ball should be created when the user clicks on the start button. [15 M]
import javax.swing.;
import java.awt.;
import java.awt.event.*;
public class BallPanel extends JPanel implements ActionListener {
private int ballY = 0;
private Timer timer;
public BallPanel() {
timer = new Timer(100, this);
}
public void startAnimation() {
timer.start();
}
public void actionPerformed(ActionEvent e) {
ballY += 5;
if (ballY > getHeight()) {
ballY = 0;
}
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(getWidth() / 2 - 10, ballY, 20, 20);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BallPanel panel = new BallPanel();
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.startAnimation();
}
});
frame.add(startButton, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
- Write a Java program using Spring to display the message “If you can't explain it
simply, you don't understand it well enough”.
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringMessageApp {
@Bean
public String message() {
return "If you can't explain it simply, you don't understand it well enough.";
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringMessageApp.class);
String message = context.getBean("message", String.class);
System.out.println(message);
}
}