Search This Blog

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Why FileOutputStream or BufferedWriter Does Not Write New Line to File

The new-line character is system dependent. It depends on operating system. It can be \n, \r, \r\n or something else depending on the operating system. So, when we are writing a cross platform java program, it is important to take care when we use a line separator or new line character. It is always safe to use system specific line separator provided by JVM. You can get the system specific newline character in different ways.

Method 1:

System.lineSeparator() instead of new line character. The java method Sytem.lineSeparator() returns the newline character (line separator) as a strong. If you are appending a string on another with a line separator in between, it can be done as follows.

line1+System.lineSeparator()+line2

Method 2:

You can also get the line separator using the getProperty() method with property key line.separator.

System.getProperty("line.separator");

Method 3:

If your are using a BufferedReader object to write text into a file, you can use the newLine() method to write a newline into the file. If br is a BufferedReader object, br.newLine() will write a newline (line separator) into the file.

Method 4:

If you want to get the line separator as a character, you may use the static member Character.LINE_SEPARATOR. It returns the Unicode newline character.

Chat Room Application using UDP in Java

UDP chatroom application in java source code Chatting using java UDP java chat application java group chat application
Java Chat room application using UDP
The following is a Java program for chatting. This chatting application uses UDP (User Datagram
Protocol) for chatting. The application gives you to options. One is to create a new chat room and the other is to join a chat room. The one who creates the chat room acts as a server for the chatroom. Others can join this chatroom id they know his IP address. This simple java chat room application is enough for server and clients. The GUI is basic one and not too attractive. Also i have used JOptionPane to reduce code. You may make improvements to the code. The chat rooms are not password protected. Anyone who know the server's IP address are granted access to the chat room. If you wish, you may improve the program. This Group chat application using java can be used in Local area networks. This code for java group chat program can be modified to enable chatting in multiple chat rooms. Try it.

How to Easily Copy a File to Another File or Location in Java

The Files class in java has many useful static methods to copy and move files, create temporary files or folders etc. To copy a file from one location to another in Java, there is a static method copy in Files class. The Files class is in java.nio.file package. The method Files.copy() takes three arguments (parameters) : Path of source file (as object of Path class), Path of destination file ( as object of Path class ) and an option parameter. The option parameter can be one of the following:

StandardCopyOption.REPLACE_EXISTING
If the target file exists, then the target file is replaced.

StandardCopyOption.COPY_ATTRIBUTES
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes
that are copied is platform and file system dependent and therefore unspecified.

StandardCopyOption.NOFOLLOW_LINKS
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.

You have to import java.nio.file.StandardCopyOption to use option parameters.

try{
File sourcefile=new File("audio.mp3");
File destination=new File(System.getProperty("java.io.tmpdir")+"\\temp.mp3");
Files.copy(sourcefile.toPath(),destination.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException ex) {
ex.printStackTrace();
}

For the copy method, there are two other overloaded method definitions. In one, instead of source file's path, inputstream is the first parameter and the rest are same. For the other overloaded definition, an outputstream object is the second parameter instead of destination path object and the rest are same.

Similarly, to move a file from one location to another, there is a method move() in Files class. The parameters of this method is also same as those of copy method.

How to Get Center Point of Screen in Java

If you want position your JFrame in center of screen, there is method for that. Read this post:

The LocalGraphicsEnvironment in Java will give you the center point of the display or screen. There is a static method getLocalGraphicsEnvironment() in GraphicsEnvironment class. To get the center point of the screen, you may use the following java code:


Point centre=GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();

You should include these import statements in the file.

import java.awt.Point; import java.awt.GraphicsEnvironment;

How to Set JFrame in Center of Screen

By default, a java application appears at top left corner of the screen. You might have seen that most of the applications appear in the middle of the screen. I will tell you how to center your java application on screen.

To set JFrame in center of Just call this.setLocationRelativeTo(null); in constructor of the JFrame. If you are using Netbeans IDE, it should be after calling initComponents() method. But if you call setLocation() method of JFrame after this, your JFrame will get relocated.

In most cases this works and this is enough. if you want to get the center point of the screen, just refer to the following post:

How to Get Center Point of Screen in Java

How to Set Background Color of a JFrame in Java

It is easy to set Background color of a JFrame in java. But still many people cannot do it (me too was once like this). Most such people may have tried this java code to set java JFrame background color: setBackground(Color.BLACK);. But this won't work. Instead, you should set the background color of the ContentPane of the JFrame. So, use the following code to set Background color of Frame in your Java Application.

getContentPane().setBackground(Color.BLACK);

or


getContentPane().setBackground(new Color(34,172,176));

Keep in mind that you have to import java.awt.Color; You can use the first one if you don't know RGB values of the desired color. Most common colors are defined as constants in Font class. If you know the RGB color values for your desired color, you can use the second example.

Java Application Source Code to Scroll Text Along JFrame

This is a simple java program for beginners to show how to scroll text in the JFrame. The program uses an anonymous (unnamed) thread object to move the scroll or move the text. The Thread moves two JLabel objects (containing text) by repeatedly calling setLocation(int x, int y) method of JLabel. The speed of the motion of text in this program can be changed by changing value of i or changing sleep period of the thread.


Free, Simple and Light weight Download Manager Java Application - Application and Source Code

This is a free Internet Download Manager Application for PC developed in java and free to use. It is
very light weight with size only below 50KB. This download manager allows pause and resume for downloads and requires java jre 1.8 to run. The program source code is given below. This will help you to understand how to download files from internet using java. The program may help you to understand how to pause and resume downloads in a java program. The application also provides drag and drop support. You can drag a link to file to be downloaded from browser in to the drag and drop area (drop target) in the application and it will automatically start download or add to the download queue. This will also help you study how to use Drag and Drop and how to set a drop target.

Download free Download Manager Application for Computer


You may download the  lightweight java Download Manager Software from following link:

https://drive.google.com/file/d/0B5WYaNmq5rbueUl5bW03VllIc2M/view?usp=sharing

View Source code


Free Two Person Text Chatting Application Software for Local Networks using Java With Source Code

two person text chat program java program java code java source code program code free chatting application free local network chatting free LAN Chatting LAN messenger
Java text Chatting program
Free two person chat program for local networks. This java text chatting application can be used for two person chatting within private or local networks. This java application uses TCP connection.

How to use

Both users should open this java application in their computer. One of them should click Make a Connection  while the other should enter the first person's ip address in the textfield provided and click Connect to this IP.

Bank Application in Java - Simulation of Banking Services in Java

Java Banking services simulation application java program java source code java code java simple sample banking application banking software
Java Banking services simulation application
This is a simple bank simulation application in java. The application first asks username and password. The default username and password for the application :

username: operator1
password: password

You can change this username and password in the application. This java bank application software supports following banking services.


  • Opening a new account
  • Money Withdrawal from the bank account
  • Making Deposits in the accout
  • Transfer of funds


TCP Server Client Two Person Chat Program in Java with GUI

Server-Client chat program or two way chat using TCP connection is a common problem for java practical labs or networking labs. Here this post introduces a simple lightweight Server client two person chat program using java. The program uses ServerSocket and Socket classes available in java.net package. This program is written so as to use the same as server or as client. Both the persons who chat use the same program. One should select hosting (acting as server) while the other could connect to him by entering the server ip address. I have added screenshots of the program also.
See Screenshots

Clock Application using Java - Java Source Code for Analog Clock Application

For my java practical lab experiments, i had to create an analog clock using java. So, i created a
Java analogue clock application applicaion program source code Analogue clock using java programming language. Analog clock application using java
Analog Clock Application using Java.
simple analog clock using java. The program source code is added below. It makes use of java 2D Graphics Object and draws the clock in the screen. The clock displays all the three hands (hour hand, second hand and minute hand). The program source code is as follows. The screenshot of the java analog clock application is also added.

How to Remove Title bar from JFrame of Java Application

To remove the title bar completely, there is a method called setUndecorated() in java. It takes a boolean variable. If the boolean is true, the title bar will be removed. The following one is an example. The method setUndecorated() invoked with a true boolean argument, will remove the title bar from the JFrame MyJFrame. The method is called here from the constructor. You may call it anywhere from within the class scope.

How to Close or Exit a Java App When some Button is Clicked

To close a Java app, System.exit() can be used. This function can be used to close the app if an error occurs or no error is occurred. If no, error occurred, the argument  of the function should be 0. This method terminates the currently running Java Virtual Machine. The argument stands for status code; by convention, a nonzero status code indicates abnormal termination. If you are calling the System.exit() function without any errors (in normal case), just give the argument as zero. This method calls the exit method in class Runtime.

How to Use System.getProperty() - Keys for System Properties

There is a method getProperty() in System class in java. As the name indicates, this java method is used to get System specific, operating system specific or user specific properties. There are different keys which are strings passed as parameter to the getProperty() method.

Usage

The following sample java code will show you how to use the getProperty method in System class. The key is a string. The System.getProperty() method takes a string parameter (argument). Based on the string passed, the method System.getProperty() returns different properties as string. In this example,we pass "java.io.tmpdir" as the parameter, which is the key to get the temporary directory (temp directory) for the current user account.

String property = "java.io.tmpdir"; String tempDir = System.getProperty(property); System.out.println("temp directory ="+ tempDir );


Similarly, for each property, there is a key. Below, the keys for different properties are listed.
"file.separator"
Gives the character that separates components of a file path. This is "/" on UNIX and "\" on Windows. This character is used in File paths for cross platform java applications
"java.class.path"
Returns the path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
"java.home"
Returns the installation directory for Java Runtime Environment (JRE)
"java.vendor"
Returns the name of JRE vendor
"java.vendor.url"
Returns the URL of JRE vendor
"java.version"
Returns the version number of JRE
"line.separator"
Returns the character sequence used by operating system to separate lines in text files. This is operating system specific. It can be '\n', '\r' or "\r\n".
"os.arch"
Returns the operating system architecture
"os.name"
Returns the name of the Operating system
"os.version"
Returns the version of the Opposing system.
"path.separator"
Returns path separator character used in java.class.path
"user.dir"
Returns the path to the working directory of current user in the computer.
"user.home"
Returns the path to the home directory of current user.
"user.name"
Returns the name of current user (user account name)

Plane Shooter Game for PC -Java Game Project with Source code

tank shoot down bomber planes free java game Multi level using Greenfoot .Plane Shooter is a single player lightweight Java game for Computers. It is a 2D game that works well even on  low end computers. The game size is only a few Kilobytes. You play as a tank and shoot down planes and what they drop. The game is in 7 or more levels. This is my first complete Greenfoot project. The source code of this game is also uploaded for those who want to see.

PanzerFight - Two player Action Game (Java Game) For Any OS

multi player Tank fight game free download for Windows Linux MAC and Solaris in Java Greenfoot platform mines shoot
PanzerFight is an interesting two player game for PC. The game is played between two players on same computer (can be on same keyboard). Each player controls a tank. The tanks can plant land mines or fire each other. Ammunition and health are supplied at times. The game is interesting since it is a multi player game. This multiplayer shooting game is supported on, Windows, Linux, Solaris, Mac etc. The game is developed in Java platform (using Greenfoot). JRE (Java Run time Environment) is a prerequisite to run this game.

How to Change Image in JButton in Java - Set Icon of JButton

In this post we are discussing how to change the image in button in Java. There may be situations in
change jbutton image java jbutton image jbutton background image jbutton image icon how to add image to jbutton in java swing jbutton picture adding image to jbutton add image to jbutton
Jbutton with Image set
programming where we want to know how to set JButton image in java or to change button icon in java. The java code to change the icon of a Jbutton is so short. We use the
setIcon()
method in JButton class. The setIcon method takes an ImageIcon object as an argument. I will show you a sample java code in which the icon of  button is set. First of all,  you have to copy the icon image (jpg, bmp, png or gif image) to the src folder in the project directory. You may also place it in some folder inside the src folder. If you are using netbeans IDE, you can simply drag and drop the image file into the desired folder in the projects pane. After copying the icon image to src folder (or any subfolder in it), use the following code to set it as the button's icon.
playbtn.setIcon(new ImageIcon(getClass().getResource("/manhaj/images/play.png")));

How to Change Shape of JFrame - Rounded Rectangle, Circle, Ellipse etc

You can change the shape of the JFrame. By default its shape is rectangular and assumes the size set using setSize() method. In this post we will discuss how to change the shape of  JFrame. You can change JFrame's shape into rounded rectagle, cirlce, ellipse, etc. We will see how to set the shape of JFrame with java code sample and screenshots. To change the shape of JFrame to any shape, we use the setShape() method.

Prerequisites

There are some prerequisites for setting or changing the shape of JFrame. They are:
The Frame should be undecorated. You should call the setUndecorated(true) method before calling setShape() method. When you set the frame undecorated, you will lose the title-bar,close button, maximise and minimise buttons. So you will have to create these button syourself.