Learn how to create a Java Swing application that reads words from a text file and categorizes them based on starting vowels (A, E, I, O, U) into a 2x3 grid using JTable. Includes complete source code for WordGUI.java and Project1.java with file handling and GUI implementation.
Write a main application called Project1.java, and a GUI (that extends
JFrame) called WordGUI.java. The main program should open a file called
“input.txt” which will contain words, one per line. As the words are read from
the file, they should be displayed in the GUI as follows:
The GUI should have a grid layout of two
rows (row 0 and row 1) and three columns (column 0, 1 and 2). All words that
start with an ‘A’ or ‘a’ should be displayed in row 0, column 0. All words that
start with an ‘E’ or ‘e’ should be displayed in row 0, column 1. Likewise for
words starting with ‘I’ or ‘I’ in row 0 column 2, with ‘O’ or’o’ in row 1
column 0, with ‘U’ or ‘u’ in row 1 column 1, and the rest of the words in row
1, column 2.
Answer
WordGUI.java
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class WordGUI extends
javax.swing.JFrame {
/**
* Creates new form
WordGUI
*/
public WordGUI() {
initComponents();
}
/**
* This method is
called from within the constructor to initialize the form.
* WARNING: Do NOT
modify this code. The content of this method is always
* regenerated by the
Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold
defaultstate="collapsed" desc="Generated Code">
private void
initComponents() {
jScrollPane1
= new javax.swing.JScrollPane();
jTable1
= new javax.swing.JTable();
jButton1
= new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new
javax.swing.table.DefaultTableModel(
new
Object [][] {
{null,
null, null},
{null,
null, null}
},
new
String [] {
"",
"", ""
}
) {
boolean[]
canEdit = new boolean [] {
false,
false, false
};
public
boolean isCellEditable(int rowIndex, int columnIndex) {
return
canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
if
(jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
}
jButton1.setFont(new
java.awt.Font("Tahoma", 1, 24)); // NOI18N
jButton1.setText("Run");
jButton1.addActionListener(new
java.awt.event.ActionListener() {
public
void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout
layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(44,
44, 44)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE, 643,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(31,
Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jButton1,
javax.swing.GroupLayout.PREFERRED_SIZE, 199,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(253,
253, 253))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(71,
71, 71)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE, 275,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33,
33, 33)
.addComponent(jButton1,
javax.swing.GroupLayout.PREFERRED_SIZE, 46,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(46,
Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String
filepath ="";
JFileChooser
j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
//
invoke the showsOpenDialog function to show the save dialog
int
r = j.showOpenDialog(null);
//
if the user selects a file
if
(r == JFileChooser.APPROVE_OPTION)
{
//
set the label to the path of the selected file
filepath
= (j.getSelectedFile().getAbsolutePath());
Project1
test = new Project1(filepath);
String
words[] = test.getData() ;
Object
sortedword [][] = new Object [][] {
{"",
"", ""},
{"",
"", ""}
}
;
for(int i = 0 ; i <words.length ;
i++ ){
if(words[i].startsWith("A")
|| words[i].startsWith("a") ){
sortedword
[0][0] += words[i]+" ";
}
else
if(words[i].startsWith("E") || words[i].startsWith("e") ){
sortedword
[0][1] += words[i]+" ";
}
else
if(words[i].startsWith("I") ||
words[i].startsWith("i") ){
sortedword
[0][2] += words[i]+" ";
}
else
if(words[i].startsWith("O") ||
words[i].startsWith("o") ){
sortedword
[1][0] += words[i]+" ";
}
else
if(words[i].startsWith("U") || words[i].startsWith("u") ){
sortedword [1][1] +=
words[i]+" ";
}
else{
sortedword [1][2] +=
words[i]+" ";
}
}
/////
jTable1.setModel(new
javax.swing.table.DefaultTableModel(
sortedword,
new
String [] {
"",
"", ""
}
) {
boolean[]
canEdit = new boolean [] {
false,
false, false
};
public
boolean isCellEditable(int rowIndex, int columnIndex) {
return
canEdit [columnIndex];
}
});
//////
}else{
JOptionPane.showMessageDialog(null,"Select
a file .");
}
}
/**
* @param args the
command line arguments
*/
public static void
main(String args[]) {
/*
Set the Nimbus look and feel */
//<editor-fold
defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/*
If Nimbus (introduced in Java SE 6) is not available, stay with the default
look and feel.
*
For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for
(javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if
("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(WordGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(WordGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(WordGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(WordGUI.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
//</editor-fold>
/*
Create and display the form */
java.awt.EventQueue.invokeLater(new
Runnable() {
public
void run() {
new
WordGUI().setVisible(true);
}
});
}
// Variables declaration -
do not modify
private javax.swing.JButton
jButton1;
private
javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable
jTable1;
// End of variables
declaration
}
Project1.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1 {
private String data ="" ;
public Project1(String Filename) {
try {
File myObj = new
File(Filename);
Scanner myReader
= new Scanner(myObj);
while
(myReader.hasNextLine()) {
this.data
+= myReader.nextLine()+"\n";
//
System.out.println(data);
}
myReader.close();
} catch
(FileNotFoundException e) {
System.out.println("An
error occurred or file not found ");
e.printStackTrace();
}
}
public String[] getData(){
String names[] =
data.split("\n");
return names;
}
}// end class
input.txt
This
is
an
input
file
to
be
used
for
project
1
in
Computer
Science
The
words
are
to
be
divided
into
six