Saturday, January 30, 2016

Writing Text To An Image

Three components will be displayed on the screen: textfield, label, and button. The textfield holds text that will be added to an image. The label (with image icon) holds the image. When the button is clicked, the text in the textfield will be added to the image.

Notes: This program does not change the image file name, so please make a backup copy of your original image if you try it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.awt.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;

public class TextToImage extends JFrame{
    private BufferedImage bufimage=null;
    private ImageIcon icon=null;
    private JTextField tfield=null;
    private JLabel label=null;
    
    public static void main(String[] args) throws Exception{
        TextToImage obj=new TextToImage();
    }
    
    public TextToImage(){
        super("Text To Image");
        
        setLayout(new BorderLayout());
        
        tfield=new JTextField(20);
        add(tfield,BorderLayout.NORTH);
        
        label=new JLabel();
        label.setIcon(getImage());
        add(label,BorderLayout.CENTER);
        
        JButton button=new JButton("Add Text");
        button.addActionListener(new ButtonHandler());
        add(button,BorderLayout.SOUTH);
        
        setSize(icon.getIconWidth(),icon.getIconHeight()+100);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        show();
    }
    
    class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            Graphics g=bufimage.getGraphics();
            g.setColor(Color.WHITE);
            g.setFont(new Font("Arial Black",Font.BOLD,20));
            g.drawString(tfield.getText(),200,200);
            g.dispose();
            try{
                ImageIO.write(bufimage,"jpg",new File("R2D2.jpg"));
            }
            catch(Exception ex){
            }
            
            label.setIcon(getImage());
        }
    }
    
    public ImageIcon getImage(){
        try{
            bufimage=ImageIO.read(new File("R2D2.jpg"));
        }catch(Exception e){
        }
        icon=new ImageIcon(bufimage);
        return icon;
    }
}


public ImageIcon getImage(){
     try{
          bufimage=ImageIO.read(new File("R2D2.jpg"));
     }catch(Exception e){
     }
     icon=new ImageIcon(bufimage);
     return icon;
}

This function returns an ImageIcon. It is called twice to display the original and the image that has been changed on the screen.

bufimage=ImageIO.read(new File("R2D2.jpg"));

The image is loaded via the ImageIO class. The image will then be manipulated using BufferedImage class.

Graphics g=bufimage.getGraphics();
g.setColor(Color.WHITE);
g.setFont(new Font("Arial Black",Font.BOLD,20));
g.drawString(tfield.getText(),200,200);
g.dispose();
try{
	ImageIO.write(bufimage,"jpg",new File("R2D2.jpg"));
}

This segment of code manipulates the original image. It is the core of the program.

Graphics g=bufimage.getGraphics();

The graphics context is obtained with the getGraphics() method. The next two lines of code set the color and font of the text.

g.drawString(tfield.getText(),200,200);

The value of the text field is retrieved and then added to the image at position x=200, y=200.

g.dispose();

System resources that are used by the graphics context are released.

Tuesday, January 26, 2016

Creating Quiz with JTabbedPane

JTabbedPane is a component that enables us to create a number of pages within a single window. Each tab corresponds to a certain page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JTabbedPaneDemo extends JFrame{
    public static void main(String[] args){
        JTabbedPaneDemo ap=new JTabbedPaneDemo();
    }
    
    public JTabbedPaneDemo(){
        super("Electronics Tutorial");
        setSize(640,120);
        
        JTabbedPane tab=new JTabbedPane();
        
        JPanel panel1=new JPanel();
        JLabel l1=new JLabel("Resistors are designed to oppose the flow of current");
        panel1.add(l1);
        tab.addTab("Resistor", panel1);
 tab.setSelectedIndex(0);
        
        JPanel panel2=new JPanel();
        JLabel l2=new JLabel("Capacitors temporarily store energy as an electric field");
        panel2.add(l2);
        tab.addTab("Capacitor",panel2);
        
        JPanel panel3=new JPanel();
        JLabel l3=new JLabel("Inductors temporarily store energy as a magnetic field");
        panel2.add(l2);
        tab.addTab("Inductor",panel3);
        
        getContentPane().add(tab);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        show();
    }
}

Here is the result:



Below, JTabbedPane is utilized to create a simple quiz. Just like the program above, there are three tabs on the window. Each contains a different question.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
=====
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class JTabbedPaneDemo2 extends JFrame{
     JTabbedPane tab;
     JPanel panel1,panel2,panel3;
     ButtonGroup g1;
     JRadioButton rb1a,rb1b,rb1c;
     ButtonGroup g2;
     JRadioButton rb2a,rb2b,rb2c;
     ButtonGroup g3;
     JRadioButton rb3a,rb3b,rb3c;
     JButton b1,b2,b3;
    
    public static void main(String[] args){
        JTabbedPaneDemo2 ap=new JTabbedPaneDemo2();
    }
    
    public JTabbedPaneDemo2(){
        super("Electronics Quiz");
        setSize(640,120);
        
        tab=new JTabbedPane();
        
        panel1=new JPanel();
        JLabel l1=new JLabel("The frequency of common household AC in US is:");
        g1=new ButtonGroup();
        rb1a=new JRadioButton("120Hz",false);
        rb1b=new JRadioButton("60Hz",false);
        rb1c=new JRadioButton("100Hz",false);
        g1.add(rb1a); g1.add(rb1b); g1.add(rb1c);
        panel1.add(l1);
        panel1.add(rb1a);
        panel1.add(rb1b);
        panel1.add(rb1c);
        b1=new JButton("Submit");
        panel1.add(b1);
        tab.addTab("Level1", panel1);
        
        panel2=new JPanel();
        JLabel l2=new JLabel("Ohm is the standard unit of:");
        g2=new ButtonGroup();
        rb2a=new JRadioButton("Current",false);
        rb2b=new JRadioButton("Charge",false);
        rb2c=new JRadioButton("Resistance",false);
        g2.add(rb2a); g2.add(rb2b); g2.add(rb2c);
        panel2.add(l2);
        panel2.add(rb2a);
        panel2.add(rb2b);
        panel2.add(rb2c);
        b2=new JButton("Submit");
        panel2.add(b2);
        tab.addTab("Level2", panel2);
        
        panel3=new JPanel();
        JLabel l3=new JLabel("A vector has (Choose the wrong option):");
        g3=new ButtonGroup();
        rb3a=new JRadioButton("Magnitude",false);
        rb3b=new JRadioButton("Direction",false);
        rb3c=new JRadioButton("Inductance",false);
        g3.add(rb3a); g3.add(rb3b); g3.add(rb3c);
        panel3.add(l3);
        panel3.add(rb3a);
        panel3.add(rb3b);
        panel3.add(rb3c);        
        b3=new JButton("Submit");
        panel3.add(b3);
        tab.addTab("Level3", panel3);
        
        tab.setEnabledAt(0,true);
        tab.setEnabledAt(1,false);
        tab.setEnabledAt(2,false);
            
        ButtonHandler handler=new ButtonHandler();
        b1.addActionListener(handler);
        b2.addActionListener(handler);
        b3.addActionListener(handler);
        
        getContentPane().add(tab);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        show();
    }
    
    class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            if(e.getSource()==b1&&rb1a.isSelected()){
                tab.setEnabledAt(1,true);
            }
            if(e.getSource()==b2&&rb2c.isSelected()){
                tab.setEnabledAt(2,true);
            }
            if(e.getSource()==b3&&rb3c.isSelected()){
                CongratDialog cd=new CongratDialog(null);
                cd.show();
            }
        }
    }
    
    class CongratDialog extends JDialog {
        public CongratDialog(JFrame parent) {
            super(parent, "Result", true);
            Container cp = getContentPane();
            cp.setLayout(new FlowLayout());
            cp.add(new JLabel("Congratulation!"));
            JButton ok = new JButton("OK");
            ok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        cp.add(ok);
        setSize(150,100);
        }
    }
}


tab.setEnabledAt(0,true); //Only the first tab is enabled initially
tab.setEnabledAt(1,false);
tab.setEnabledAt(2,false);

Initially, the second and the third tabs are not enabled. They cannot respond to user input.

if(e.getSource()==b1&&rb1a.isSelected()){
     tab.setEnabledAt(1,true);
}

When the user selects the correct answer, the second tab will be enabled.

if(e.getSource()==b2&&rb2c.isSelected()){
     tab.setEnabledAt(2,true);
}

When the user chooses the correct answer, the thids tab will be enabled.

if(e.getSource()==b3&&rb3c.isSelected()){
     CongratDialog cd=new CongratDialog(null);
     cd.show();
}

When the right option on the third tab is selected, a dialog box will be displayed.

Sunday, January 24, 2016

Writing To Text File

There are a number of Java classes that can be used to write characters to text files. Two of them are FileWriter and RandomAccessFile.

FileWriter

FileWriter's job here is to create a character-based file. The output is wrapped (buffered) in BufferedWriter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.*;

public class WritingTextFile1 {
    public static void main(String[] args){
        String st1="Java is a general-purpose computer programming language.";
        String st2="Java was originally developed by James Gosling.";
        
        FileWriter fw=null;
        try{
            fw=new FileWriter("textfile.txt");
        }catch(IOException e){
            
        }
        
        BufferedWriter bw=new BufferedWriter(fw);
        try{
            bw.write(st1,0,st1.length());
     bw.newLine();
            bw.write(st2,0,st2.length());
        }catch(IOException e){
            
        }
        
        try{
            bw.close();
        }catch(IOException e){
            
        }
    }
}


bw.write(st1,0,st1.length());     

String st1 is written to the text file. The second argument is the starting point and the third or the last argument is the numbers of character written. In other words, this code write all the characters of the string.

bw.newLine();   

This inserts a newline to the text.

bw.write(st2,0,st2.length());

The second string st2 is written to the text file.

Adding new content to an existing file

To prevent the existing content from being replaced by new content, the text file is opened in append mode. This is accomplished by passing true to the second argument.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.*;

public class WritingTextFile1b {
    public static void main(String[] args){
        String st="Sun relicensed most of its Java technologies under the GNU General Public License.";
        
        FileWriter fw=null;
        try{
            fw=new FileWriter("textfile.txt",true);
        }catch(IOException e){
            
        }
        
        BufferedWriter bw=new BufferedWriter(fw);
        try{
            bw.newLine();
            bw.write(st,0,st.length());
        }catch(IOException e){
            
        }
        
        try{
            bw.close();
        }catch(IOException e){
            
        }
    }
}


RandomAccessFile

This example shows how to write text to a file using RandomAccessFile, a class which can perform read and write operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.*;

public class WritingTextFile2 {
    public static void main(String[] args){
        String st1="Java is concurrent, class-based, and object-oriented.";
        String st2="The language derives much of its syntax from C and C++.";
        String st3="The code can run on all platforms without recompilation.";
        
        RandomAccessFile raf=null;
        try{
            raf=new RandomAccessFile("textfile.txt","rw");
        }catch(IOException e){
            
        }
        
        try{
            raf.seek(0);
            raf.writeBytes(st1); //writeBytes(String s)
            raf.writeBytes("\r\n"); //newline
            raf.writeBytes(st2);
            raf.writeBytes("\r\n"); //newline
            raf.writeBytes(st3);
        }catch(IOException e){
            
        }
        
        try{
            raf.close();
        }catch(IOException e){
            
        }
    }
}


raf=new RandomAccessFile("textfile.txt","rw");

The text file is opened in "rw" (read write) mode.

raf.seek(0);

Set the file pointer in the beginning of the text file.

raf.writeBytes(st1);

String st1 is written to the the text file.

raf.writeBytes("\r\n");

Insert newline. And so on...

Adding new content to an existing file

To add new data, move the pointer to the end of the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.*;

public class WritingTextFile2b {
    public static void main(String[] args){
        String st="The latest version is Java 8, which is supported for free by Oracle.";
        
        RandomAccessFile raf=null;
        try{
            raf=new RandomAccessFile("textfile.txt","rw");
        }catch(IOException e){
            
        }
        
        try{
            raf.seek(raf.length());
            raf.writeBytes("\r\n"); //newline
            raf.writeBytes(st); //writeBytes(String s)
        }catch(IOException e){
            
        }
        
        try{
            raf.close();
        }catch(IOException e){
            
        }
    }
}


raf.seek(raf.length());     

Move the file pointer to the end of the file.

Reading Text File

There are a number of Java classes that can be used to fetch or to manipulate the content of text files.

Scanner

The first program uses Scanner class to read the content of a text file and display the output on the screen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import java.util.*;
import java.io.*;


public class ReadingTextFile { public static void main(String[] args){ try{ Scanner sc=new Scanner(new FileInputStream("article.txt")); while(sc.hasNext()){ System.out.println(sc.nextLine()); } }catch(Exception e) { } } }

Scanner sc=new Scanner(new FileInputStream("article.txt"));

The constructor takes a FileReader object as a parameter.

sc.hasNext()

Returns true if there is another token (\n) in the input. In this case it will check if there is another paragraph in the text.

sc.nextLine()

This method reads a line of input and advances the cursor in the next line (paragprah).

FileReader

The following code utilizes the combination of FileReader and BufferedReader classes to perform the same task. FileReader is a class which is desiged for reading character files. BufferedReader class makes the reading process easier as it provides a method to read a line of text (readLine).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.io.*;

public class ReadingTextFile2 { public static void main(String[] args){ int numbyte=0; String filename=new String("article.txt"); FileReader fr=null; try{ fr=new FileReader(filename); }catch(IOException i){ System.out.println("Cannot open file"); System.exit(1); } BufferedReader br=new BufferedReader(fr); try{ while(true){ String datarow=br.readLine(); if(datarow==null) break; System.out.println(datarow); } }catch(IOException i){ System.out.println("Cannot read data"); System.exit(1); } try{ fr.close(); }catch(IOException i){ } } }

while(true){
 String datarow=br.readLine();
 if(datarow==null)
  break;
 System.out.println(datarow);
}

BufferedReader.readLine() does the job inside a while loop. When no more data is available, readLine returns null and break is executed.

RandomAccessFile

The following program utilizes RandomAccessFile to read a text file. The advantage of using this class is it uses pointer that allows user to easily move to a new point in the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.*;

public class ReadingTextFile3 { public static void main(String[] args){ String filename="article.txt"; RandomAccessFile raf=null; try{ raf=new RandomAccessFile(filename,"r"); }catch(IOException e){ } char c=' '; try{ raf.seek(0); //pointer to the beginning of the text while(raf.getFilePointer()<raf.length()){ c=(char)raf.readByte(); System.out.print(c); } }catch(IOException e){ } try{ raf.close(); }catch(IOException e){ } } }

raf=new RandomAccessFile(filename,"r");

RandomAccessFile has a number of file access modes. "r" means read only and "rw" means read/write mode.

raf.seek(0);

The pointer is positioned to the beginning of the text file.

while(raf.getFilePointer()<raf.length()){
 c=(char)raf.readByte();
        System.out.print(c);
}

The position of the pointer is compared with the length of the text file (end of file). The reading process will continue as long as the pointer has not reached the end of the file. The content of the text file is fetched character by character.

Friday, January 22, 2016

Split A Sentence Into Words

This program converts a sentence to an array of words. Date class is used to form the sentence so the array of words will contain day, month, date, and time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;

public class DateDemo {
    public static void main(String[] args){
        Date d=new Date();
        String st=d.toString();
        
        int counter=0;
        for(int i=0;i<st.length();i++){
            if(st.charAt(i)==' '){
                counter++;
            }
        }
        
        StringTokenizer stoken=new StringTokenizer(st);        
        ArrayList<String> al=new ArrayList<String>();
        
        for(int i=0;i<counter;i++){
            al.add(i,stoken.nextToken(" "));
            System.out.println(al.get(i));
        }
    }
}


for(int i=0;i<st.length();i++){
     if(st.charAt(i)==' '){
          counter++;
     }
}

Basically, what the 'for' loop does is to count the number of words in the sentence. The value wil be used in the second 'for' loop. Everytime a space is detected, 1 is added to the variable counter.

StringTokenizer stoken=new StringTokenizer(st);

The StringTokenizer class is used to split the string by 'space' delimiter.

for(int i=0;i<counter;i++){
 al.add(i,stoken.nextToken(" "));
        System.out.println(al.get(i));
}

The nextToken() method is used to extract the words in the sentence. Words that have been separated are stored in an ArrayList named "al". Each word is then displayed on the screen.