Slip No.12
B) Write a java program to display multiplication table of a given number into the List box by clicking on button.1. Open Notepad.
2. Type the following code:
-
import java.awt.*;
import java.awt.event.*;
public class MultiplicationTable extends Frame implements ActionListener {
Label lbl;
TextField tf;
Button btn;
List list;
MultiplicationTable() {
// Set layout and title
setLayout(null);
setTitle("Multiplication Table");
// Label
lbl = new Label("Enter a number:");
lbl.setBounds(50, 50, 100, 30);
add(lbl);
// Text field
tf = new TextField();
tf.setBounds(160, 50, 100, 30);
add(tf);
// Button
btn = new Button("Show Table");
btn.setBounds(100, 100, 100, 30);
btn.addActionListener(this);
add(btn);
// Listbox
list = new List();
list.setBounds(80, 150, 150, 200);
add(list);
// Frame settings
setSize(300, 400);
setVisible(true);
// Close on exit
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
public void actionPerformed(ActionEvent e) {
list.removeAll(); // Clear previous entries
try {
int num = Integer.parseInt(tf.getText());
for (int i = 1; i <= 10; i++) {
list.add(num + " x " + i + " = " + (num * i));
}
} catch (NumberFormatException ex) {
list.add("Please enter a valid number.");
}
}
public static void main(String[] args) {
new MultiplicationTable();
}
}
4 Compile the Java program by typing:
javac MultiplicationTable.java
5 Run the compiled Java program by typing:
java MultiplicationTable
No comments:
Post a Comment