Write a
java program to display multiplication table of a given number into the List
box by clicking on button.
import
javax.swing.*;
import
java.awt.*;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
public
class MultiplicationTableApp extends JFrame {
private JTextField numberField;
private JButton displayButton;
private JList<String> tableList;
public MultiplicationTableApp() {
setTitle("Multiplication
Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));
numberField = new JTextField();
displayButton = new
JButton("Display");
DefaultListModel<String>
tableModel = new DefaultListModel<>();
tableList = new
JList<>(tableModel);
displayButton.addActionListener(new
ActionListener() {
@Override
public void
actionPerformed(ActionEvent e) {
tableModel.clear();
String numberInput =
numberField.getText();
try {
int number =
Integer.parseInt(numberInput);
for (int i = 1; i <= 10;
i++) {
int result = number *
i;
tableModel.addElement(number + " x " + i + " = " +
result);
}
} catch (NumberFormatException
ex) {
tableModel.addElement("Invalid input. Please enter a valid
number.");
}
}
});
panel.add(numberField);
panel.add(displayButton);
panel.add(new JScrollPane(tableList));
add(panel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MultiplicationTableApp app = new
MultiplicationTableApp();
app.setVisible(true);
});
}
}
C:\Program
Files\Java\jdk-11.0.17\bin>javac MultiplicationTableApp.java
C:\Program
Files\Java\jdk-11.0.17\bin>java MultiplicationTableApp