JP-5
JAVA Swing
Q.1) Write a java program to design a swing application that randomly changes the colour on button click
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Swing1 implements ActionListener {
JFrame f;
Swing1() {
f = new JFrame();
JButton a = new JButton("blue");
a.setBounds(40, 100, 100, 40);
a.setBackground(Color.BLUE);
JButton b = new JButton("red");
b.setBounds(150, 100, 100, 40);
b.setBackground(Color.RED);
a.addActionListener(this);
b.addActionListener(this);
f.add(a);
f.add(b);
f.setSize(400, 500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("red")) {
f.getContentPane().setBackground(Color.RED);
} else if (e.getActionCommand().equals("blue")) {
f.getContentPane().setBackground(Color.BLUE);
}
}
public static void main(String args[]) {
Swing1 c = new Swing1();
}
}
Output:
> Text Field
Code:
import javax.swing.*;
public class SwingExample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextField textField = new JTextField();
textField.setBounds(130, 100, 100, 40);
JButton button = new JButton("Click Here");
button.setBounds(130, 150, 100, 40);
f.add(textField);
f.add(button);
f.setSize(400, 500);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
> Image
Code:
import javax.swing.*;
public class SwingExample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextField textField = new JTextField();
textField.setBounds(130, 100, 100, 40);
JButton button = new JButton(new ImageIcon("C:\\Car.jfif"));
button.setBounds(130, 150, 100, 40);
f.add(textField);
f.add(button);
f.setSize(400, 500);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Comments
Post a Comment