Java Programs - Grid and Buttons
Question: Write Java program to demonstrate Grid of 5*5 (Advanced Java Program)
Answer:
import javax.swing.*;
import java.awt.*;
public class GridDemo {
public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("5x5 Grid Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
// Set layout for the frame as GridLayout with 5 rows and 5 columns
frame.setLayout(new GridLayout(5, 5));
// Add 25 buttons to the frame
for (int i = 1; i <= 25; i++) {
JButton button = new JButton("Button " + i);
frame.add(button);
// Make the frame visible
frame.setVisible(true);
Question: Write a program to display the numbers on buttons from 0 to 9
Answer:
import javax.swing.*;
import java.awt.*;
public class NumberButtons {
public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Number Buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
// Set layout for the frame as GridLayout with 2 rows and 5 columns
frame.setLayout(new GridLayout(2, 5));
// Add buttons with numbers from 0 to 9
for (int i = 0; i <= 9; i++) {
JButton button = new JButton(String.valueOf(i));
frame.add(button);
// Make the frame visible
frame.setVisible(true);