Ajp Exp 13 Op
Ajp Exp 13 Op
Ajp Exp 13 Op
Practical Code:
1. Debug the following code and write the output of following code
import java.awt.*;
import java.awt.event.*;
public class WindowDemo {
Frame f;
public WindowDemo() {
f = new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new WindowDemo();
}
}
XIII. Exercise:
1. Write a program to demonstrate the use of WindowAdaptor class.
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterDemo {
Frame frame;
public WindowAdapterDemo() {
frame = new Frame("WindowAdapter Example");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing. Goodbye!");
frame.dispose();
}
});
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
public static void main(String[] args) {
new WindowAdapterDemo();
}
}
2. Write a program to demonstrate the use of anonymous inner class.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
public class Sample extends JFrame {
public Sample() {
setTitle("Anonymous Inner Class Demo");
setSize(300, 200);
JButton button = new JButton("Click Me");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button Clicked!");
}
});
}
public static void main(String[] args) {
Sample frame = new Sample();
frame.setVisible(true);
}
}
3. Write a program using MouseMotionAdaptor class to implement only one method
mouseDragged().
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sample1 extends JFrame {
private Point lastPoint = null;
public Sample1() {
setTitle("Mouse Motion Adapter Demo");
setSize(400, 300);
DrawingPanel drawingPanel = new DrawingPanel();
add(drawingPanel);
drawingPanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (lastPoint != null) {
Graphics g = drawingPanel.getGraphics();
g.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
}
lastPoint = e.getPoint();
}
});
drawingPanel.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
lastPoint = null;
}
});
}
private class DrawingPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Sample1 frame = new Sample1();
frame.setVisible(true);
});
}
}