Coding for Java Application : 653338

Question:

Design and code a Java Application that :

 

(a)        Implements a Linked-List based Queue and Stack                                        (25 Marks)

(b)        Allows the user to select between working with the Stack or the Queue      (10 Marks)

(c)        Allows values to be loaded from a text file and inserted into the

selected data structure                                                                                    (15 Marks)

(d)       Allows additional values to be inserted and removed through the GUI        (10 Marks)

(e)        Demonstrates how the stack can be used to reverse a list of values               (05 Marks)

(f)        Depicts the selected structure graphically (updated after each change)         (25 Marks)

(g)        Displays appropriate messages in an area of the GUI                                    (10 Marks)

 

You may ‘dismantle and reassemble’ the drawing program constructed during the module practicals as a starting point for your application. More detailed requirements are presented below:

 

(a) The stack and queue should be implemented as a linked data structure in accordance with the ADTs discussed in lectures.

(b) A toggle button of some form should permit the user to work with either the Stack or the Queue.

(c) The program should automatically attempt to load a file ‘stack.txt’ into the stack data structure from the application directory when it is run. The file is a text file containing a string representation of an integer on each line. For marking purposes, a test file with 15 values will be used. It should also be possible to load a file from the GUI (emptying any existing structure first). Failure to find or load the file should be handled within the program with feedback for the user displayed in a message area.

(d) Values entered and removed via the GUI should result in an update of the graphical display (f) when the <ENTER> key is pressed (or a button pressed). The change to the structure should be highlighted in some manner.

(e) A button should trigger the emptying of a selected stack item by item with the values appended to a string and displayed within the message area. The button should be disabled if a queue is selected.

(f) The currently selected data structure should be displayed graphically. This does not need to be elaborate.  The display should be updated on any change to the contents of the structure.

(g) The message area can be employed to indicate error states and other appropriate messages to the user.

 

Note that a Graphics object has a setFont() method to select a font and a drawString() to display text. The getFontMetrics() method returns a FontMetrics instance that can be used to calculate the dimensions of a string to be drawn to the display.

 

Within each marking category, 50% of marks will be available for functionality, 30% for the quality of coding and 20% for coding presentation and comments. Within each of these sub-marking categories marks will be awarded in accordance with the university’s generic undergraduate marking scheme. Submission details will be published to the KLE in the near future.  All of the coding should be your own work save for use of the Java AWT, SWING and IO libraries, and the application shell produced during the practicals.

 

If you fail to implement any of the GUI elements, you should make the functionality of your data structures clear in some other manner.

Answer:

package com.stack_queue;

import java.util.ArrayList;

import java.util.List;

 

/**

*

* @author

* Stack Queue class to implement the working of stack and Queue

*/

public class Stack_QueueClass {

/**

* Flag true : working of stack

* false : working of queue

*/

private boolean flag;

public boolean isFlag() {

return flag;

}

public void setFlag(boolean flag) {

this.flag = flag;

}

/**

* first node of the Stack_Queue

*/

private Node head = null;

/**

* last node of the Stack_Queue

*/

private Node last = null;

/**

* Current Size of the Stack_Queue

*/

private int size=0;

/**

*

* set the working to stack in the beginning

*/

public Stack_QueueClass()

{

this.flag=true;

}

/**

* Change the working

* Stack, if it is queue

* and queue if it is stack

*/

public void toggle()

{

flag=!flag;

}

/**

*

* @return size of current stack_queue

*/

public int getSize() {

return size;

}

/**

*

* @param data insert the data accordingly into the Stack_Queue

*/

public void insert(int data)

{

Node node=new Node(data);

size++;

if(head==null)

{

head=node;

last=node;

return;

}

node.setNext(head);

head=node;

 

}

/**

*

* @return satck queue is empty or not

*/

public boolean isEmpty()

{

return size==0;

}

/**

*

* @return the data

*/

public Integer remove()

{

if(size==0)

throw new ArrayIndexOutOfBoundsException(“Stack_Queue is Empty”);

Integer data=null;

size–;

if(flag || size==0)

{

data=head.getData();

head=head.getNext();

return data;

}

Node temp=head;

while(temp.getNext().getNext()!=null)

temp=temp.getNext();

data=temp.getNext().getData();

temp.setNext(null);

 

 

return data;

 

}

public String[][] getData()

{

String[][] dt=new String[size][1];

List<Integer> data=new ArrayList<>();

Node temp=head;

int in=0;

while(temp!=null)

{

dt[in++][0]=””+temp.getData();

data.add(temp.getData());

temp=temp.getNext();

}

return dt;

}

@Override

public String toString() {

StringBuilder sb=new StringBuilder(“”);

Node temp=head;

while(temp!=null)

{

sb.append(temp.getData()).append(“\n”);

temp=temp.getNext();

}

return sb.toString();

}

 

}

 

package com.stack_queue;

/**

*

* @author

* Node class for Stack/Queue

*/

public class Node {

/**

* data at the Node

*/

private int data;

/**

* Next pointer of the node

*/

private Node next;

/**

*

* @return data contained at the node

*/

public int getData() {

return data;

}

/**

*

* @param data data to be inserted at the node

*/

public void setData(int data) {

this.data = data;

}

/**

*

* @param data data to be inserted when node is constructed

* set next pointer to NULL

*/

public Node(int data) {

this.data = data;

this.setNext(null);

}

/**

* display the current node data and a space

*/

public void displayNode() {

System.out.print(data);

System.out.print(”  “);

 

}

/**

*

* @return next pointer of the node

*/

public Node getNext() {

return next;

}

/**

*

* @param next set next pointer of the node

*/

public void setNext(Node next) {

this.next = next;

}

}

 

package com.MainGUI;

 

import javax.swing.*;

import javax.swing.table.DefaultTableModel;

 

import com.stack_queue.Stack_QueueClass;

 

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

 

public class GUIView extends JFrame{

private static Stack_QueueClass sq=new Stack_QueueClass();

private static final long serialVersionUID = 1L;

 

 

JTable table;

private JTextField valueToAdd;

private JLabel valueRemoved;

 

 

public GUIView(){

 

 

 

setExtendedState(JFrame.MAXIMIZED_BOTH);

setUndecorated(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setTitle(“GUI Stack_Queue Application”);

 

setLayout(new BorderLayout());

 

JPanel p = new JPanel();

p.setLayout(new GridLayout(7,4));

 

p.add(new JLabel(“Enter value to Add: “));

 

valueToAdd =  new JTextField(“”);

valueToAdd.setBackground(Color.WHITE);

valueToAdd.setColumns(20);

p.add(valueToAdd);

 

p.add(new JLabel(“Removed Value: “));

 

valueRemoved = new JLabel(“”);

valueRemoved.setBackground(Color.WHITE);

 

p.add(valueRemoved);

 

p.add(new JLabel(“”));

p.add(new JLabel(“”));

p.add(new JLabel(“”));

p.add(new JLabel(“”));

 

 

 

JButton displayButton = new JButton(“Toggle to Queue”);

p.add(displayButton);

 

JButton pushButton = new JButton(“Insert”);

p.add(pushButton);

 

JButton popButton = new JButton(“Remove”);

p.add(popButton);

 

JButton exitButton = new JButton(“Exit”);

p.add(exitButton);

exitButton.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

System.exit(0);

 

}

});

 

p.add(new JLabel(“”));

p.add(new JLabel(“”));

p.add(new JLabel(“”));

p.add(new JLabel(“”));

JButton loadFile=new JButton(“Load Integer Data File”);

 

p.add(loadFile);

JButton trigger=new JButton(“Trigger Stack Empty”);

p.add(trigger);

JButton reverse=new JButton(“Reverse By Stack”);

p.add(reverse);

 

 

 

p.add(new JLabel(“”));

p.add(new JLabel(“”));

p.add(new JLabel(“”));

 

add(p,BorderLayout.NORTH);

 

JTextArea messages=new JTextArea();

JScrollPane bar=new JScrollPane(messages);

bar.add(messages);

bar.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

messages.setRows(10);

messages.setColumns(20);

add(bar);

 

 

 

JPanel t = new JPanel();

 

 

 

String [] title = {“Data in Stack Queue”};

String d[][]=new String[50][1];

for(int i=0;i<50;i++)

d[i][0]=”a”;

JTable table = new JTable(d,title);

table.setModel(new DefaultTableModel());

JScrollPane scrollPane = new JScrollPane(table);

scrollPane.setPreferredSize(new Dimension(800, 500));

t.add(scrollPane);

t.add(messages);

add(t);

popButton.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

try

{

 

int i=sq.remove();

valueRemoved.setText(i+” “);

messages.setForeground(Color.BLACK);

messages.setText(valueToAdd.getText()+”removed from Stack_Queue”);

DefaultTableModel model = (DefaultTableModel)table.getModel();

model.setRowCount(0);

String[][] d=sq.getData();

model.setDataVector(d, new String[]{“Stack_Queue Data”});

 

}

catch(Exception ee)

{

ee.printStackTrace();

messages.setForeground(Color.RED);

messages.setText(ee.getMessage());

valueRemoved.setText(“”);

valueToAdd.setText(“”);

}

 

}

});

pushButton.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

try

{

 

sq.insert(Integer.parseInt(valueToAdd.getText()));

messages.setForeground(Color.BLACK);

messages.setText(valueToAdd.getText()+”inserted into Stack_Queue”);

DefaultTableModel model = (DefaultTableModel)table.getModel();

model.setRowCount(0);

String[][] d=sq.getData();

model.setDataVector(d, new String[]{“Stack_Queue Data”});

valueToAdd.setText(“”);

valueRemoved.setText(“”);

valueToAdd.requestFocus();

 

}

catch(Exception ee)

{

ee.printStackTrace();

messages.setForeground(Color.RED);

messages.setText(“Please enter a valid Integer”);

}

}

});

loadFile.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

JFileChooser fileChooser = new JFileChooser();

int returnValue = fileChooser.showOpenDialog(null);

if (returnValue == JFileChooser.APPROVE_OPTION) {

File selectedFile = fileChooser.getSelectedFile();

try{

BufferedReader br = new BufferedReader(new FileReader(selectedFile.getAbsolutePath()));

 

String sCurrentLine;

 

while ((sCurrentLine = br.readLine()) != null) {

sq.insert(Integer.parseInt(sCurrentLine));

}

DefaultTableModel model = (DefaultTableModel)table.getModel();

model.setRowCount(0);

String[][] d=sq.getData();

model.setDataVector(d, new String[]{“Stack_Queue Data”});

messages.setForeground(Color.BLACK);

messages.setText(“Data successfully loaded “);

valueToAdd.setText(“”);

valueRemoved.setText(“”);

valueToAdd.requestFocus();

}

 

catch(Exception ee)

{

messages.setForeground(Color.RED);

messages.setText(“Please select a file with valid Integer Data”);

}

 

}

 

}

});

displayButton.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

sq.toggle();

String str=null;

if(sq.isFlag())

trigger.setEnabled(true);

else

trigger.setEnabled(false);

if(sq.isFlag())

str=”Queue”;

else

str=”Stack”;

displayButton.setText(“Toggle to “+str);

repaint();

}

});

 

 

trigger.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

StringBuilder msg=new StringBuilder(“Stack Empty Process Triggered”).append(“\n”);

messages.setForeground(Color.BLACK);

messages.setText(msg.toString());

while(!sq.isEmpty())

{

int i=sq.remove();

 

msg.append(“Item Removed :”+i).append(“\n”);

messages.setText(msg.toString());

}

DefaultTableModel model = (DefaultTableModel)table.getModel();

model.setRowCount(0);

String[][] dd=sq.getData();

model.setDataVector(dd, new String[]{“Stack_Queue Data”});

 

}

});

 

reverse.addActionListener(new ActionListener() {

 

@Override

public void actionPerformed(ActionEvent e) {

StringBuilder msg=new StringBuilder(“Reversing List By Stack “).append(“\n”);

messages.setForeground(Color.BLACK);

ArrayList<Integer> tempList=new ArrayList<>();

messages.setText(msg.toString());

while(!sq.isEmpty())

{

int i=sq.remove();

tempList.add(i);

msg.append(“Item Removed :”+i).append(“\n”);

messages.setText(msg.toString());

}

while(!tempList.isEmpty())

{

int i=tempList.remove(0);

sq.insert(i);

msg.append(“Item Added :”+i).append(“\n”);

messages.setText(msg.toString());

}

DefaultTableModel model = (DefaultTableModel)table.getModel();

model.setRowCount(0);

String[][] dd=sq.getData();

model.setDataVector(dd, new String[]{“Stack_Queue Data”});

 

}

});

 

 

BufferedReader br = null;

try {

br = new BufferedReader(new FileReader(“stack.txt”));

 

 

String sCurrentLine;

 

try {

while ((sCurrentLine = br.readLine()) != null) {

sq.insert(Integer.parseInt(sCurrentLine));

}

} catch (NumberFormatException | IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

DefaultTableModel model = (DefaultTableModel)table.getModel();

model.setRowCount(0);

String[][] dd=sq.getData();

model.setDataVector(dd, new String[]{“Stack_Queue Data”});

messages.setForeground(Color.BLACK);

messages.setText(“Data successfully loaded “);

valueToAdd.setText(“”);

valueRemoved.setText(“”);

valueToAdd.requestFocus();

} catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

 

}

}

 

 

 

 

}