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

Tuesday, September 1, 2009

How to make JTextArea transparent in Nimbus LAF of Java

Recently i encountered a problem while using Nimbus LAF of Java that i was not able to make components transparent by using setOpaque(false).
Though my Java 6 update version is a bit older than the current updated version, so it might be possible you may not experience this problem.

For my problem, i found out from the Bugs Section of Java website that this can be resolved like this:-

JTextArea jTextArea1=new JTextArea1();
................
................
jTextArea1.setOpaque(false);
jTextArea1.setBackground(new Color(0,0,0,0));

This bug might have been resolved in future updates but if you face problem, you can use this trick.

Saturday, July 25, 2009

Tutorial to minimize JFrame dynamically in Java

There is a very easy way to achieve the above functionality in your application.

The following statement will help you to do the exactly same thing:-

JFrame f=new JFrame();
.................
.........
//Now somewhere you want to minimize your JFrame then use below code

f.setExtendedState(JFrame.ICONIFIED);

Your work is done now.
This way of minimizing is also known as Iconifing your JFrame..i.e. make an icon in the taskbar.

Hope you liked this article then please consider bookmarking it. Thanks!!

Tutorial to remove JFrame titlebar in Java

This tip helps to remove the title bar of JFrame:-

To remove the title bar, just use following code

JFrame f=new JFrame();
....
f.setUndecorated(true);

This is very simple and just use of one statement helps us to do our job.

If you liked this tip, please consider bookmarking it!!

Sunday, July 12, 2009

Tutorial on how to use ArrayList

Many times , it is essential that we need to update the arrays which we have defined in our code.
However arrays are defined with a fixed size so they cannot be updated to larger size dynamically.
Some may use the trick of copying the contents of array to a new array of bigger size.
But we also have a nice way of getting this feature of dynamically updating arrays through ArrayList.

To define ArrayList object:-

ArrayList<object> al=new ArrayList<object>();

Ex:-
ArrayList<File> al=new ArrayList<File>();
We can use any Object type here.

To add in ArrayList at last:-
al.add(f);
This appends an Object 'f' at end of ArrayList.

To add in specific position:-
al.add(index,f);

To find size of ArrayList:-
int size=al.size();

To get an item at any specific position in ArrayList:-
f=al.get(index); //Here index is a integer from 0 to size-1
Here f is the Object Type of which we make the ArrayList.
If we make it of File type then al.get(index) will return a File type Object.

To remove an item at specific position:-
al.remove(index);

To remove all items:-
al.clear();

To replace an item with another item at specific index:-
al.set(index,f);
where f is object type of which ArrayList has been made.

Saturday, June 20, 2009

An update on what i am coding now!!

Well, i have just created a useful utility application known as WoodCutter. This application does the job of splitting a large file into lot of smaller files. This allows to send a large file over e-mail as normally there is a limit on the maximum size of attachment. By using this utility, we can get number of smaller size files which can then be sent over mail. The utility also provides way to merge the split files back into single file using batch file, shell file as well as the utility itself can merge all the files back using a merge file.
The application is working well but now i am going out of town for some time away from my computer so it will take almost 1 month in publishing it as still some final touches need to be given to make it a good release.
Hope you come back to download it at that time!!
Thanks for reading!!

How to set Nimbus as look and feel in Java GUI

Recently,in the Java SE Update N, Nimbus was provided as one of the bundled look and feels. It is a good looking L&F and if someone has worked in the new Solaris then one can understand what Nimbus is all about.
To use Nimbus in your Java application , the below code will work:-
try {

UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e)
{

}
This is a straight way to use Nimbus, however the problem with this code is that though it will work now, its a possibility that in Java 7, this way of using Nimbus can create problem as the location of Nimbus L&F class can change.

So a better way of using Nimbus is to find all the installed L&Fs by using UIManager.getInstalledLookAndFeels() ,then check if Nimbus is present and then use the getClassName to invoke the L&F.

The below steps will make it clear:-

UIManager.LookAndFeelInfo plafinfo[] = UIManager.getInstalledLookAndFeels();
boolean nimbusfound=false;
int nimbusindex=0;

for (int look = 0; look < plafinfo.length; look++) {
if(plafinfo[look].getClassName().toLowerCase().contains("nimbus"))
{
nimbusfound=true;
nimbusindex=look;
}
}

try {

if(nimbusfound)
{
UIManager.setLookAndFeel(plafinfo[nimbusindex].getClassName());
}
else

UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());

}
catch(Exception e)
{
}

By making use of this code, we make sure that our application will be able to use the Nimbus L&F even if the location of Nimbus L&F class changes in future version of Java.
Hope you liked the above information!!

Thursday, March 12, 2009

Tutorial on how to maximize the JFrame dynamically on display of JFrame

Here is a simple article which tells how to display a JFrame which is in the Maximized state.

Maximized state here refers to maximum size of JFrame on a desktop screen however not covering the taskbar.

This state of JFrame is sometimes needed so that a programmer can design the layout keeping in mind the maximum size which a JFrame can attain in a screen.

The code for such a frame will be:-

import java.awt.*;

import javax.swing.*;

public class MaxFrame

{

public static void main(String[] args)

{ GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();

JFrame f=new JFrame();

JPanel p =new JPanel();

f.add(p);

f.setMaximizedBounds(e.getMaximumWindowBounds());

f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

}

So put the setExtendedState code just before the f.setVisible(true) line. Also an important point is don't use the f.pack() or f.setResizable(false) in this code.

However this approach is not good when you don't want the user to resize the frame using the restore button as normally you would use setResizable(false) in the above code, but sometimes in that case, JFrame opens in minimized mode, why?? well i could not figure it out as well. So a code which does work smoothly all the time is needed.

So if you want the maximized frame to have no resizability in that case: we need to use below code.

import java.awt.*;

import javax.swing.*;

public class MaxFrame

{

public static void main(String[] args)

{ GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();

JFrame f=new JFrame();

JPanel p =new JPanel();

f.add(p);

f.setMaximizedBounds(e.getMaximumWindowBounds());

f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );

f.setSize(e.getMaximumWindowBounds().width, e.getMaximumWindowBounds().height);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setResizable(false);

f.setVisible(true);

}

}

The above code thus gives a basic idea of how to create a maximized frame both with resizability and without resizability, and not covering the taskbar.

Hope you liked the article, then please consider bookmarking it. Thanks!!

Wednesday, March 11, 2009

Find Operating System name in Java

In order to find the name of Operating System in Java, there is a simple code :-

String os=System.getProperty("os.name").toLowerCase();

if(os.indexOf("win")>=0)

{ System.out.println("It is Windows System");

}

if(os.indexOf("uni")>=0)

{ System.out.println("It is a Unix System");

}

if(os.indexOf("lin")>=0)

{ System.out.println("It is a Linux System");

}

Hope you found this useful!!

If you liked this article, please consider bookmarking or sharing it. Thanks!!

Friday, February 27, 2009

Some important String functions

Some Important String functions

String t="Important String functions";

----------------------
To get length of a String
length();

t.length();
It returns total number of characters in t which is length of string
----------------------
To get a single character
charAt()

char ch=t.charAt(1);

This will assign 'm' to ch
----------------------
To get more than one characters
getChars()

This is used to get more than one characters from the string

int start_index=4;
int end_index=10;

char buffer[]=new char[end_index-start_index];
t.getChars(start_index,end_index,buffer,0);

System.out.println(buf);
-----------------------
To create an array of characters
toCharArray()

This function can be used to create an array of all the characters present in the array

char[] test=t.toCharArray();
------------------------

To Compare two Strings

String anotherstring="...anything..";

Use t.equals(anotherstring);
if equals..returns true else false

Dont use == operator as it just finds whether two objects point to same instance.

Similarly we can use compareTo(anotherstring) which returns:
 Less than zero for t less than anotherstring
 Greater than zero for t greater than anotherstring
 And Zero when both the strings are equal.

 Both equals and compareto can be used with IgnoreCase extension as:
  equalsIgnoreCase(anotherstring) and compareTo(anotherstring)....

---------------------------
To replace a particular charcter with another character

t.replace('t','h');

---------------------------

To find whether a string contains a pattern

Here t.contains(anotherstring) is used which returns true or false depending

on whether t contains anotherstring in it.

Also contains cannot be used using IgnoreCase as no function like containsIgnoreCase
--------------------------

Monday, July 28, 2008

The Media Player fantasy in Java

These days, i am busy in coding a music player using Java..and definetly it has not been really easy. Java does not offer much in handling media files efficiently..anyone who has had some interests in this field must have heard of Java Sound and Java Media Framework.
Java Media Framework(JMF) has been a subject of lot of criticism as it has not really been able to deliver according to the expectations of Java developers. There has also not been much work done in JMF lately..its API is old and the support it offers is pretty limited..
If someone really wants to make a robust media Player using JMF, that person really needs to code to a very large extent to provide basic functionalities provided in common media player softwares around us..and if we dont do that, the software stands no chance, and has no takers..it justs helps in increasing our understanding of the topic, thats all!!
One of the biggest drawback of JMF is lack of support of different codecs, and this is something which makes people to go for third party libraries. In past, JMF had trouble with MP3 format license as well, but then it was sorted out after some time..really it would have been dreadful if JMF would not have been able to provide MP3 support.
In third party library support, Quicktime for Java has been told by many as the alternative but then it has a very serious drawback..There is no Quicktime for Java library for Linux platforms. This simply means that by using it to create a media player, we are going to miss a very important segment of users who use Linux.
Then what should we do?? There are other libraries as well such as JLayer and then Tritonus..if you are comfortable to use them, its well and good but they all have some drawbacks as well. So then it all comes down to what we want our media software to do!!
But if we want to look a bit differently, then there is another alternative as well.
Heard of MPlayer??
Yes there are ways of using the Open source MPlayer from within the Java Application according to your needs.. i.e. creating a Java Front end for using the power of MPlayer in a manner we want, in the background.
One of the big advantage is that MPlayer supports large number of formats so in a way our Java Application also will be able to support a large number of formats. So start working to use MPlayer from within Java, you will be astonished by the power you will be having at your hands!!

Friday, June 27, 2008

The Thumbnail drama

As i thought of making an image viewer with some nice features, i always wanted to have a decent looking, visually attractive Graphical interface in my software.
So I wanted to have thumbnails of the images shown in my program, however it was really all not that easy.
I was of the view that Java must be having a nice way to show thumbnails of the images,
but i was unable to find it..
Then i also heard about third party library support to ease out this tension..but i was never sure to use it in my program..
So i decided to code from scratch for this software..
Yes, what i knew was that there is this very general function drawImage of the Graphics object that can be used in a variety of ways to get what you want.
Infact i have no words to praise this function..this function can be used in various ways eliminating use of various other specific functions.
If someone wants to have this feature of Thumbnails in Java Software coded purely in J2SE then
there are only two options:-
Create Thumbnails- using On the Fly Scaling Approach using drawImage and display it.
or Create Thumbnails using getScaledInstance of Image object, save them and then show them.
What i prefer depends on Two things:
Firstly, What your Application intends to do, and secondly, getScaledInstance is not your friend as its pretty slow as compared to drawImage.
So what needs to be done? Confused i guess!!
The answer is that drawImage is at your rescue all the time.
Whenever you need to show scaled down versions of your images, always use drawImage function.
Then if your software is such that it has to display those scaled versions repeatedly, its better to save them on disk and then have the software read from disk when you need to display that scaled version again.
This approach is faster and much robust as well.
And yes how to use drawImage to create a scaled version?
The code for that will be:-
public void paintComponent(Graphics g)
{ g.drawImage(img, 0, 0, img.getWidth()*scale, img.getHeight()*scale, null);
}
Here scale is your scaling factor.
In case you want to create an instance of your thumb, the code for that will look like----
public BufferedImage createThumb(BufferedImage img)
{
thumb= new BufferedImage(133,100,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2=thumb.createGraphics();
g2.drawImage(img,0,0,133,100,null);
return thumb;
}
Here 133 is width and 100 is height.
Now you can directly show the thumb using drawImage of the component in which you are drawing, inside the paint(Graphics g) function by overriding it, or you can save it as well.
Alos Some people use AffineTransform for thumb creation, but my advise is: Always use drawImage, its the best as its faster , robust when you code using it, and secondly avoids creation of unnecessary Garbage objects in memory
Hope what i have written helps alot to many people as these are things which can be overlooked but are a matter of concern if you want your code to work efficiently..

Thursday, June 12, 2008

My Experiences with Java GUI and Swing

My experiences with Java regarding its GUI arose out of some serious coding in Swing. As i went deep into some serious stuff coding in Java, i always wanted to try out new features in Java ,in which i had little knowledge. After trying out basics of working of Java, i jumped into programming of Swing, as GUI coding always looked fascinating to me!!
But certainly, i had no clue about the dangerous territory where i was heading.
This was the fact i realized, when i started coding the Swing stuff.
The elements just never looked to obey my orders in the code. It was a real hard work to really control the looks of GUI. Then learning the Layouts, the rules which the components follow, and combining them with Event Handling Functionalities..
My first real GUI program with a bit of good coding was to display a list of files and directories in a user selected directory from the JFileChooser class, all in a GUI format. Initially i felt whats the big deal in it, but for a beginner, it was certainly a bit hard. But as i got success in it, my confidence grew in coding GUI programs.
Certainly that confidence helped me alot to take up more challenging coding in GUI and Image Handling in Java, which ultimately helped me to learn more about the way Java works.......

Wednesday, June 11, 2008

The API dilemma

So Java enhances its power by the vast resource of API which supports the language. Infact Java is nothing without its API.
As Java has just 49 keywords in it, but to really program in Java, one needs to have the ability to effectively use the classes provided in the API.
The API contains thousands of ready-made classes already present to make the job pretty easier.
Definetly the above line sounds more good than it is, as its really not a cakewalk to remember all the classes.
So whats the best way??
I guess and infact i believe that no one can remember all the classes, so the best way is to start with the basic classes which will help us start coding in Java. Afterwards as we require something which we dont know, search for it in the API.
When you get it, use it and yes, dont forget it!!
After some time in development, one realises that one will remember what is useful to us, and in this way, the very large API becomes a bit smaller for us!!

Tuesday, June 10, 2008

Why JAVA is attractive??

Well, Many times People may give different answers for the same question. The same trend also continues here!!
Some may say, its a new language as compared to C, some say its well documented and good resource material is available, but possibly the best reason which can be given is that Java is a Cross-platform language. In other words, its the Platform independence of Java, that has made it one of the most attractive languages for developers!!
So no worries for developers that how there code is going to work in different platforms, which they have developed taking lot of pains.
Yes, i do agree there are some secondary reasons which can also be given.
They are that it is object oriented and that it has a large bunch of API classes...
Definetly Object oriented programming is a good programming technique which Java provides, but its the API classes of Java which enhances the beauty of JAVA for me..

Share this Page:-