ja4
- Write a Java program using Runnable interface to blink Text on the frame. [15 M]
- import javax.swing.;
import java.awt.;
import java.awt.event.*;
public class BlinkText implements Runnable {
private JLabel label;
private boolean isBlinking;
public BlinkText(JLabel label) {
this.label = label;
isBlinking = true;
}
@Override
public void run() {
try {
while (isBlinking) {
Thread.sleep(1000); // Delay for 1 second
label.setVisible(!label.isVisible()); // Toggle visibility
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void stopBlinking() {
isBlinking = false;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Blinking Text");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
JLabel textLabel = new JLabel("Blinking Text");
frame.add(textLabel);
BlinkText blinker = new BlinkText(textLabel);
Thread blinkThread = new Thread(blinker);
blinkThread.start();
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
blinker.stopBlinking();
stopButton.setEnabled(false);
}
});
frame.add(stopButton);
frame.setVisible(true);
}
}
- Write a Java program to store city names and their STD codes using an appropriate
collection and perform following operations:
i. Add a new city and its code (No duplicates)
ii. Remove a city from the collection
iii. Search for a city name and display the code
import java.util.HashMap;
import java.util.Map;
public class CityCodes {
private Map<String, Integer> cityCodes;
public CityCodes() {
cityCodes = new HashMap<>();
}
public void addCity(String city, int code) {
cityCodes.put(city, code);
}
public void removeCity(String city) {
cityCodes.remove(city);
}
public int getCode(String city) {
return cityCodes.getOrDefault(city, -1);
}
public static void main(String[] args) {
CityCodes cityCodes = new CityCodes();
// Add cities and their codes
cityCodes.addCity("New York", 212);
cityCodes.addCity("Los Angeles", 213);
cityCodes.addCity("Chicago", 312);
// Remove a city
cityCodes.removeCity("Chicago");
// Search for a city name and display the code
String city = "Los Angeles";
int code = cityCodes.getCode(city);
if (code != -1) {
System.out.println("STD Code for " + city + ": " + code);
} else {
System.out.println(city + " not found");
}
}
}