Java Swing GUI- Chemical Properties of Elements

Standard

      In one of my previous posts, I made a C program, which would find the atomic number of an element from a text file and display it. Here today I have an upgraded version of that same program which is far more efficient than the C program. It is written in Java and when you search an element in the search box, it shows the atomic number, atomic radius, electronic configuration, electronegativity, first ionization energy and its chemical name in a beautiful graphical user interface.

swing

Atomic Properties

swingpane

J panel/ Message box

       Now let us look it to this program. This Java program is using the Swing GUI Components, which works far more better and looks better than the AWT. It includes everything from buttons to split panes to tables. Many components are capable of sorting, printing, and drag and drop, to name a few of the supported features. So, basically any Java GUI program gets divide in to three section; the first is your Action listener, second your main method and the third Action performed section. First we need to import the necessary packages like awt, swing, io, etc. To run the program use this method;

public void init(){
    {   
      (new Runnable(){
            public run(){
                makeGUI();}
                            });
            }catch(Exception exc){ System.out.println("Error occured due to"+exc);}
   }

Now we create our frame, which holds all the GUI components on the frame, and implement an Action Listener to it. The Action Listener listens to the activities of our components.

    public class swin extends JApplet implements ActionListener {

We now initialize all the text fields, buttons and labels required in this program so; here particularly we require seven text fields, four buttons, 7 labels. Then we write a main method that runs this program. To code the buttons, text fields, labels, etc. we write a constructor to the class, in this case makeGUI() and design the GUI in it. We specify the buttons and name them, then the labels and the text fields. For the proper arrangement and look of these components, we select a layout, GridBagLayout. GridBagLayout is one of the most flexible and complex layout managers the Java platform provides. A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height. Similarly, not all columns necessarily have the same width. Here is how to initialize the GridBagLayout;

    GridBagLayout gbag=new GridBagLayout();
    GridBagConstraints gbc=new GridBagConstraints();      
    setLayout(gbag);

Essentially, GridBagLayout places components in rectangles (cells) in a grid, and then uses the components’ preferred sizes to determine how big the cells should be.The way the program specifies the size and position characteristics of its components is by specifying constraints for each component.Specify the number of columns (for gridwidth) or rows (for gridheight) in the component’s display area. These constraints specify the number of cells the component uses, not the number of pixels it uses. The default value is one. Use GridBagConstraints.REMAINDER to specify that the component be the last one in its row (for gridwidth) or column (for gridheight). Use GridBagConstraints.RELATIVE to specify that the component be the next to last one in its row (for gridwidth) or column (for gridheight).Anchor is used when the component is smaller than its display area to determine where (within the area) to place the component. Specifying weights is an art that can have a significant impact on the appearance of the components a GridBagLayout controls. Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty); this is important for specifying resizing behavior. A sample of how to design the layout;

       gbc.weighty=1.0;
       gbc.gridwidth=GridBagConstraints.REMAINDER;
       gbc.anchor=GridBagConstraints.NORTH;
       gbag.setConstraints(h, gbc);
       gbc.anchor=GridBagConstraints.EAST;
       gbc.gridwidth=GridBagConstraints.;
       gbag.setConstraints(l1, gbc);
       gbc.gridwidth=GridBagConstraints.REMAINDER;
       gbag.setConstraints(t1, gbc);

After positioning all the components, we add them on our frame sequentially one by one. In addition, we add action listener to the components with which we are going to interact.

       add(l1);add(t1);add(l2);add(l2);
          t1.addActionListener(this);
          t2.addActionListener(this);

An action event occurs, whenever an action is performed by the user. When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component. Therefore, we create an Action performed class and specify what happens when the user interacts with a particular component.

       public void actionPerformed(ActionEvent ae){

Therefore, the trick here is to create a method in which we write the working of the program, return the result, and when required, call the method and display the result. For example, here we read the element entered by the user in a text filed and store it in a variable. Then we call a method, which we are going to create in the following step and display their results or the returned value in other text field. Now in these methods we import the data of the variable, which stores the input. We read a particular text file line by line and compare it with the input and if it matches, we return the matched string to the method, which later displays the string in the text filed. This is particularly done for the atomic number similar process can be done for other atomic properties and their outputs can be displayed in to separate text fields. Below is code of one of the atomic properties, we got the input from the text fields in variable ‘a’ then we store the result of the method atomicnumber() in string ‘atmno’ and set the text of text field ‘t2’ to it. Then method atomicnumber() is created and value of ‘a’ is imported along with it, we use Boolean to check the condition. Then file in which all the atomic numbers are stored is read line by line (readLine) and the starting of the string is compared with the input string (startsWith) stored in variable ‘a’. Its found value of Boolean is ‘true’ and the found string is returned to the method and displayed in the text field.

     String a=t1.getText();
     String atmno="";
       try{
          atmno=atomicnumber(a);
          t2.setText(atmno);}
             catch(Exception x){System.out.println("Error");}
     public static String atomicnumber(String a){
       try{
          boolean found=false;      
          FileReader f=new FileReader("C:/Users/DELL/Periodic/text/AtomicNumber.txt");          String e;  
          BufferedReader new BufferedReader(f);
              while((e=sc.readLine()) != null){
                    if (e.startsWith(a)){            
                          found=true;
                          return e;}         
                               }
                      return("Invalid Input");} 
              (Exception e){e.printStackTrace();}

 

     As you can see I have also used ‘if’ and ‘getsource’, which performs a particular operation, specified within when the specified button is pressed. This gives me the feature to clear the text fields or to display a message box. Displaying a message box can be done by the JOptionPane. There are lots of others features that you can add like colors, borders, fonts, etc. in the swing to make your program work effectively and look better. You can also use different designs of the following is the message dialog box

             if(ae.getSource()==b2){       
                   JOptionPane.showMessageDialog(this,"Your Message");}

 

 If you have problem with any function or step of this program please let me know in the comment box below. Download the source code of this program below.

Download

Note: Please change the file paths to your current destination folders.

CSS Overflow property.

Standard

      A few days ago I was working on the design of a website when I faced a problem. Whenever I used the images, paragraph, heading or any other tag in the HTML, the text-box the box used to break and would again continue when the tag would end. Now obviously this was making the site look ridiculous. For example, whenever we put groceries in a plastic bag more than it can withstand the bag tears up. Now tried everything to keep that text box from breaking in between, until I found this solution.

     In your CSS style sheet when you add the box, you add the following attribute,

overflow: auto;

     Now this property works fine with all the browsers and is supported by CSS 2 and above. Here I have given the overflow property’s value as auto , that is it any accommodate any number of data and if it exceeds the limits then the browser simply adds a scroll bar to it. But depending on your requirement you can use (here overflow means the extra data which cannot be accommodated inside the box):

  • visible: This one is a default and the overflow is not clipped.
  • hidden: The overflow is clipped but the rest of the content is hidden…
  • scroll: The overflow is clipped but the rest of the content can be see with the help of a scroll-bar.
  • auto: The overflow is clipped and the decision of adding a scroll-bar is left up to the browser.
  • initial: Sets this property to tis default value (visible).
  • inherit: Inherits this property from its parent element.

      The overflow property basically, decides what will happen if the box isn’t capable of holding the entire content and what if the content breaks out of the box. Here I have an example of CSS box using this property:

         .box {    
      height: 500px;     
      width: 800px;
      overflow: auto;     
      background-color: #BFCFFF;
      text-align: center;
      padding-top: 25px;
      padding-left: 20px;
      padding-right: 20px;
      padding-bottom: 20px;
      margin-left: 260px;
      margin-top: 100px;}

You can also use ‘div’ instead of box if you want it for other things…Also, you can change the rest of other properties like margin, padding, text-alignment depending on your requirement.

Here is a screenshot of the box working on a html page:

StarkEnterprises

    I also have a website that I made using this and a few other features that you might want to look at. To download it click here.(You need to replace the images and video paths (file-urls) in the html to the paths in your directory).

Download Server project

Java Math Example – Resultant of two Forces.

Standard

      The program below shows how Java can be implemented in math for several applications. In this program we determine the resultant force of two different forces acting upon a body and the angle at which it is acting. At first in order to use the math functions predefined in java we need to import a java package java.lang.Math.*;

      Let us see the working of this program, we first need three variables, two to store the magnitude of each force and the third to store the angle between them. Then we calculate the magnitude of the resultant and later in the second part we calculate the angle between them. So, here are the formulae for both operations:

  • Resultant of two forces = √( p2 + q2 + 2 × p × q × cosθ )
  • Angle made by resultant = tan-1 ( q × sinθ / p + q × cosθ )

So, now we know that we need another two variables to store each of the answers.Well this really depends on you, how precise you want to be answered, if you want your answer in decimal use double or float data-type but if you don’t want a precise one the better go with integer. Another really important thing is that Java uses angles in Radian whereas normally we use angle in Degrees. So, we also need to convert the angles in to radians before using them in the formula (or else the compiler considers 45° as 45 radians ) and convert them back again to degrees to display answer (but if you are comfortable with radians don’t include this feature).

       Very well, let us get on with the program. First we declare our five variables as doubles. Then we ask the user to enter the two forces and the angle between them. Then we read and store the input data with Scanner. Also do not forget to convert the angle to radians if you are planning to enter the angle in degrees, for that we use the function Math.toRadians(a) .

Now we arrange our functions according to the formula to find out the resultant:

     r=Math.sqrt(Math.pow(p, 2)+Math.pow(q, 2)+(2*p*q*Math.cos(a)));

For square root we use the function Math.sqrt similarly for cosine of the angle Math.cos(a) , for power we use Math.pow(p, 2) where, in the bracket we specify the variable and its power (here its square). Then we display our answer or resultant.

Note:- Make a clever and careful use of the brackets in formula, incorrect placements of the brackets may lead to a wrong answer.

        To find the angle of resultant, for time being let us neglect the tan-1 from the formula and arrange the functions accordingly.

    t=(q*Math.sin(a))/(p+q*Math.cos(a));

There is nothing much hard in this formula to deal with. For the sine and cosine angles we use the functions Math.sin(a) and Math.cos(a) respectively. Here now we consider the tan-1 from the formula. To display the tan inverse of a particular value we use the function Math.atan(t) .But keep in mind that Java uses angles in radians so to keep our program more user-friendly we convert the radians back to degrees by using the function Math.toDegrees() and display them. Here I have made this process a bit simpler and less time consuming:

System.out.println("The angle at which resultant is acting on is "+ Math.toDegrees(Math.atan(t)));

Resultant of forces-Math.java

Hope this example helps you to understand how to work with Math in Java.

  • To Download the complete source code of the program click here.

Download Maths.java project

Try coding similar program with some other formula.If you find any difficulties in understanding any part of this program, let me know by commenting below or if you have made a similar program, then send me its link and I’ll put the link in this post, thus we can share it with all!