Friday, 11 November 2011

Java Swing, adding an image to a JFrame


How to add an image to a JFrame

In this tutorial we will look at how to add an image to a JFrame Form.
The first thing we should understand is that we cannot add an image directly to a JFrame. So we have to add it as an image of a JLabel or a JButton.

Tutorial contents

  • Adding images to a JLabel
  • Adding images to a JButton





Create a new project and a package in it as explained in previous tutorials. Add a JFrame in to the package. Add a JLabel and a JButton In to the JFrame.

Make sure that the button and label are large enough to display the image.

Now right click on the JLabel and go to properties.
Find the line that says icon and click the  three dots for more options.






Now select Import to project option and import an image to your project.






Now find an image and press next ( so that you can import it to the package ) press next...






Once you feel the location is right, press finish :D 







Now you will be able to see the imported image and where it is located. press OK.







Now the imported Image should look like this in the package like this ...






Now run the project and notice how the image is displayed.







Its the same method to add images or icons to the JButtons. Make sure you explore the options of the JButton and JLabel. Remember that you can also add images with the label text as well. try it out and ask me if you have any queries.

Cheers :D 

Thursday, 10 November 2011

Java swing, navigate through JFrames passing data


Navigate through JFrames and pass data...

Now that we know how to create a new project and do button click events, let’s see how we can navigate through different JFrame and pass data along...

In this tutorial we will look at,

  • How to navigate between different JFrames
  • How to pass data between JFrams
  • Initialising data in JFrames


So to start this tutorial, make a new Java project, create a new package and add two JFrames.
For this project I will be using the same package I created before.

In my case I will name the first Frame as JFrame1 and the other one as JFrame2. Project with new frames should look like this.





Now, in one JFrame add a JTextFiled, a JButton and in the other JFrame add 2  JLabels. Rename the elements as shown in the images below
Don’t forget to add, JPannels to both of those JFrames before you add anything. It’s not a must, but its a  good practice :D

JFrame1 should look like this




JFrame1 element names and hierarchy (From the inspector window)
(Change variable names accordingly)









JFrame2 should look like this (note that there are 2 JLabels here)






JFrame2 element names and hierarchy should look like this
(Change variable names accordingly)





Now that we are done with the naming, let’s add some code.

In JFrame1 in the button click method, create object of the JFrame2 and make it visible and dispose the current frame. The code should look like this

private void jButtonGoToFrame2ActionPerformed(java.awt.event.ActionEvent evt) {
       
        //creates a new JFrame2 object ... and passes a string parameter to its constuctor ..
        JFrame2 jFrame2 = new JFrame2(jTextFieldEnterName.getText());

        //new jFrame2 object is set to visible mode
        jFrame2.setVisible(true);

        //JFrame1 object is disposed...
        this.dispose();
       
    }


In the above code, first a new object of the JFrame2 class is created. For the constructor of the JFrame2 class, a string value is passed (the JTextFieldEnterName variable’s string value). Of course JFrame2 does not have a constructor that takes a String YET. We have to create it later on.
 In the second line it sets the new jFrame2 object visible.
On the third line it disposes the current JFrame1, releasing all its resources.

Next we need to go to JFrame2 and create a constructor that takes in a String parameter.
Here is how to do it,

Go to the source of JFrame2 and just below its empty constructor (which is JFrame2() ), create a new constructor called JFrame2(String var).

Here’s how the code should look like, in this method, we will load these values to the JFrame2’s JLabel, just as the frame loads.

public JFrame2(String var){
        initComponents();
        jLabelValuePrinter.setText(var);
    }


This initComponents() method will initialise all the elements in the JFrame2, and it is essential.
In the second line, the value that is passed to the JFrame2 constructor is passed to the jLabelValuePrinter’s setText method. Therefore it will display the value passed in to the constructor.

Remember, you DON’T have to delete the constructor that was already there (the empty constructor). The Java compiler will find the relevant constructors accordingly.

(For further information about how the Java compiler identifies the correct constructor, read about method signatures in java.)

Now that your coding is complete save all the documents and run the JFrame1, enter some values and click the button. You will see that the values are passed in to the new window :D
















Java Swing setting location of the JFrame form


Setting the location of the JFrame Form...




Tutorial content,

  • Continue from previous work
  • Setting the JFrame location 

If you have completed the previous tutorial, you might realize that, JFrame Form pops out from the top left side of the computer screen.

In order to get this window to pop out from the centre of the screen, you will have to do a small adjustment in the code.

Go to the Source code and find the constructor of the JFrame Form. In this case its NamePrinter() method.

Inside that method (the constructor), after the initComponents() method, call the method, setLocationRelativeTo(null)

so now the method should look like this,

 public NamePrinter() {
        initComponents();
        setLocationRelativeTo(null); // instead of null, you can add different relative terms as well
                                                   // play around with different values
    }


Now run this file. You will notice that the JFrame Form pops out from the centre of the screen.



I'll add navigation and some more stuff in my next tutorial :D 


Java swing, coding for a JButton


Java Swing Basics with Netbeans

Tutorial content,

  • Creating a new java project
  • JFrameForm
  • JPannel
  • JLabel
  • JTextField
  • Adding and writing code in a JButton...


1. I hope you have already installed JDK and Netbeans in your machine, so let us begin by creating a new java project ... In Netbeans go to File à New Project à in the categories section select Java, then in the projects area, select Java Application. Click Next.                                                                       




2.  This page allows you to enter the project details, let’s change the project name first. In the Project Name text box enter the new project name, I will name it as SwingTute1. Also pay attention to the Project Location and Project Folder text boxes, there you will find the location of the Netbeans project. Now, un-check Create Main Class. Click Finish





3. Now you will see an empty project. If you expand that project, you will see a folder called Source Packages. Right click it and go to New à Other à  in the categories section select Java and in the File Types section select Java Package.  Now click Next



4. In the new page, enter swingUI for the, Package Name, remember as a convention, we should enter package names staring with a simple letter. (This simple and capital letter naming convention, which will be used in this tutorial is called the camel notation, that is, the beginning of the name starts with a simple letter, all the other new words start with a capital letter, as an example ... thisIsCamelNotation  :D ). Click Finish




5. Now you will be able to see a newly created package called swingUI in the source packages folder ... 






6. Right click on the newly create swingUI package and go to New à Other à in this window, under the categories select Swing GUI Forms, and for the file type select JFrame Form. Then press Next.





7. In the new window, for the class name, enter NamePrinter, we start a class name with the capital letter. Make sure package is swingUI. Press Finish.





8. Now you can see the newly created JFrameForm inside the package ...





9. Now let’s add some elements to the JFrame form... but first let’s learn some interesting facts about JFrame forms. Remember, if you need to execute a file, you should always have a main method for that file, but we can run JFrameforms, why is that? Simple, it’s because JFrameform has a main method. The Netbeans auto generates that code. If you want to see the main method of the JFrameForm, click on the Source button and check out the code for the JFrameForm.Now let’s add some elements to the JFrameForm. First add a JPannel on to the JFrameForm and size it as necessary.Add 2 text boxes(jTextFields). Right click on each jTextField and select change variable name. Enter jTextFieldFirstName for one variable name and for the other put jTextFieldSurname.Add a jLabel to the panel and change its variable name to jLabelDisplay.Add a jButton to the jPannel and change its variable name to jButtonDisplayValues and change its display text to Click me.

Notice that we are using naming conventions, we use this because, if it will be easier to find those variables with the inteli-sence of Netbeans IDE. As an example, if you need to see all the text boxes in a particular JFrameForm, go to source and type in some part of the variable name ( ex. jTextFi ) and press Ctrl+Space, they you will be able to see all the variables and methods starting from the letters “jTextFi”

So, back to the frame form... the final form should look like this...

(oh and by the way get rid of those default names displayed in the jTextFields and jLabel) you can do it by right clicking a particular element in the inspector window and selecting Edit text.


(Notice you cant see the label once you remove the default text from it, make sure is its expanded enough to display text later)

10.  Now let’s add some code to the button (jButton). To add code, double click on the button. Then it will display the code behind, in this case the Netbeans will take you to the button click method. When you click that particular button, the code inside that method will start to execute ...


Initial Button Click method ...



private void jButtonDisplayValuesActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
             
    }



Enter the following code IN SIDE the button click method.

String fullName = jTextFieldFirstName.getText()+" "+jTextFieldSurName.getText();
        jLabelDisplay.setText(fullName);


Here, the getText method of the jTextFieldFirstName is called (which retrieves the entered text from that text field) and + concatenates the taken text with a “ “ (space) then the text from the other text field is retrieved and the full String is assigned to the String variable fullName.

In the next line,  setText method of the jLabelDisplay object is called and the String in the fullName variable is passed to that method as a parameter. 

so in the end, complete button click method should look like this,



private void jButtonDisplayValuesActionPerformed(java.awt.event.ActionEvent evt) {
           
        String fullName = jTextFieldFirstName.getText()+" "+jTextFieldSurName.getText();
        jLabelDisplay.setText(fullName);

    }


11. Now go to the source packages à swingUI à NamePrinter.java, right click it and select run.


12. Enter some values and press the button and you will see the out put values in the label




So, there you have it. A simple swing application, with user data input, out put and a button click event. Remember that, building of this small application will be the basis of other tutorials. When I was learning Java swing for the first time, I created a simple application like this.
I also played around with the properties of each element in the JFrameForm, therefore I hope you do the same.
Right click on an element on the JFrameForm and click properties, then change stuff and see what happens.



If you have any problems regarding this tutorial please post them in the comments section and I will be more than happy to reply you.

Thank you.