Creating a Window or Frame in Java with Event Listener

The following script will Create a Window or Frame in Java with Event Listener for window closing :

public class MainWindowExample {

private Frame myWindow;
public static void main(String[] args) {
myWindow = new Frame("My Window");
myWindow.setSize(400,300);
myWindow.setLayout(new GridLayout(3, 1));
//Adding Window Closing event Listener
myWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
myWindow.setVisible(true);
}
}

Sending email in Java from localhost example

The following Java code snippet will send email:


public class SendEmail {

public static void main(String[] args) {

// Recipient's email ID needs to be mentioned.
String to = "to_address@gmail.com";

// Sender's email ID needs to be mentioned
String from = "from_address@gmail.com";

// Assuming you are sending email from localhost
String host = "smtp.gmail.com";

final String username = "sender_email_address@gmail.com";
final String password = "sender_gmail_password";

// Get system properties
Properties properties = System.getProperties();

// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");



Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Test mail");
message.setText("Consider this as a test");
Transport.send(message);
System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Adding action to JButton example

The following code will show you how to add action to JButton:

public class WindowExample {

public static void main (String[] args){
JFrame frame = new JFrame("My Window");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Adding JPanel to frame
JPanel panel = new JPanel();
frame.add(panel);

//Adding buttons to JPanel
JButton button = new JButton("Good Message");
panel.add(button);

//Adding buttons to JPanel
JButton button2 = new JButton("Bad Message");
panel.add(button2);

//Adding TextFieldto JPanel
JTextField txtMessage = new JTextField(20);
panel.add(txtMessage);

botton1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
txtMessage.setText("I like Java!");
}
});

botton2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
txtMessage.setText("I hate Java!");
}
});

}

}

Using JPanels in Window Example

The following code snippet will show you how to use JPanels:

public static void main (String[] args){
JFrame frame = new JFrame("My Window");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Adding JPanel to frame
JPanel panel = new JPanel();
frame.add(panel);

//Adding buttons to JPanel
JButton button = new JButton("Good Message");
panel.add(button);

//Adding buttons to JPanel
JButton button2 = new JButton("Bad Message");
panel.add(button2);
}

}

Creating a Window or Frame in Java

The following code snippet will create a window in java. You can use either eclipse or other IDE to execute the code.

public class WindowExample {

public static void main (String[] args){
JFrame frame = new JFrame("My Window");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Quartz Job Scheduler Example

Step1:

Create a Job like following:


public class TestJob implements Job {

public void execute(JobExecutionContext arg0) throws JobExecutionException {

System.out.println("test job executed succesfully");
}

}
Step2:

In the main java file add following:


public static void main(String[] args) {

try {

JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity("testjob")
.build();

Trigger trigger = TriggerBuilder.newTrigger()                        .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever()).build();

SchedulerFactory factory = new StdSchedulerFactory();
Scheduler sch = factory.getScheduler();
sch.start();

sch.scheduleJob(job,trigger);

}catch (Exception e) {
// TODO: handle exception
}

}

Spring Bean Auto-Wiring Example

The @Autowired annotation can be used to autowire bean on the setter method,  constructor, a property or methods:

@Autowired on Setter Methods:

public class HelloWorld {

private String message;
@Autowired
public void setMessage(String message){
this.message = message;
}

public void getMessage(){
System.out.println("Message : " + message);
}
}

Beans.xml file:

"<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

<bean id="helloWorld" class="com.schogini.Example.HelloWorld"/>
</beans>"

In the Main.java:

public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");

helloWorld.getMessage();
}
}

Java Based Spring Bean Configuration

For Java based spring bean configuration, you have to create a bean configuration class file(PersonConfig.java)  instead of bean.xml file

Example:

//PersonConfig.java

@Configuration
public class PersonConfig {
@Bean
public Person person() {
return new Person();
}

}

Secondly, you have to create a POJO file:

//Person.java

public class Person {

private String name;
private String gender;
private int age;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "Person [name=" + name + ", gender=" + gender + ", age=" + age
+ ", country=" + country + "]";
}

}

Finally, you have to add following in your main java file:

//Main.java

public class MainApps {

public static void main(String[] args) {

ApplicationContext ctx = new AnnotationConfigApplicationContext(PersonConfig.class);

Person person1 = (Person) ctx.getBean(Person.class);

person1.setName("Philip");
person1.setAge(20);
person1.setGender("Male");
person1.setCountry("US");

System.out.println(person1);

}

}

Java Singleton design pattern example

The Singleton class is used to ensure that there is only one instance of the object is created.  Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class,  just like static fields. Singletons often control access to resources such as database connections or sockets.

Example:


public class Singleton {

private static Singleton singleton = null;

private Singleton(){ }

public static Singleton getInstance( ) {
if (null == singleton) {
singleton = new Singleton();
}
return singleton;
}

public void printSingleton() {
System.out.println("Inside Singleton");
}
}

That’s it!