Ask Java Expert


Home >> Java

java programing

Goals

  • Be able to create a program using a GUI interface.
  • Understand how to use Swing components and panels.
  • Understand the Computer Science concept of a tree.
  • Answer questions about the Java GUI interface.
  • Practice using Swing JTabbedPane and JTree components.

Description

1) In your lab5 folder, compile the file that is a starting point for this assignment. The listing and image of this Java class is on the bottom of this lab description. You can create the programs by cutting and pasting. Practice using the resulting program until you understand the concept of a displayable tree. Check what happens when you single click on any node and double click on non-leaf nodes of the displayed tree. Study the program until you completely understand what it does.

2) Create three JPanels with a horizontal box layout. The first will contain three buttons (Add, Change, and Remove) that will be used to modify the structure of the tree; the second will contain two buttons (Expand and Collapse) to expand and collapse the entire tree; the third will also contain two buttons (Expand and Collapse) to expand and collapse a single path on the tree. Add horizontal glue to the right of the button panels, so the buttons will be packed to the left.

3) Attach the program's action listener to each of the buttons (ex: addButton.addActionLister(this)). Remember that using the keyword this means that we must provide an actionPerformed method in the class that we are modifying. You can refer to the examples in the text to see how this is done. The phrase, implements ActionListener, must also be on the class signature line.

4) Instantiate a Swing JTabbedPane(). Add the three panels created in the above step to this component (ex: tabs.addTab("Modify", modifyPanel). Add theJTabbedPane to the North portion of JFrame container provided in the original program. Indicate with the statement tabs.setSelectedIndex(0) that the first panel is to be displayed when the program begins to execute.

5) The instantiation of the JTree will need to be slightly changed to complete this lab. We have to work with a class called DefaultTreeModel that controls how the tree is shown on the display as changes are made. Without utilizing this class, modifications to the tree will not show.

Declare treeModel with the statement: DefaultTreeModel treeModel;

The statements to instantiate the initial tree are:

treeModel = new DefaultTreeModel(root);

tree = new JTree(treeModel);

Instead of: tree = new JTree(root);

6) We will now consider each of the options that we need to add to the program. The appropriate logic is to be inserted into the actionPerformed method.

a. Validate the operation.

Make sure that the lastSelectedPathComponent is not null when processing add, change, remove, expand path, and collapse path options. The following statement gets the last selected path component.

DefaultMutableTreeNode selection =

(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();

If no node has been selected, place an appropriate message in the label field. The remove option requires additional validation. Users should not be able to remove non-root leaf nodes. The statement selection.isLeaf() returns true if selection specifies a leaf node (assuming 'selection' is the name you give to the variable holding the last selected component.

b. Add a node to the tree.

You can instantiate DefaultMutableTreeNode objects in the same way as done in the original program. The variable, childName, sequentially numbers the nodes. You can number nodes that users add to add to the tree in the same way.

The add method used in the original program won't work correctly for dynamically changing the tree; The treeModel object won't correctly display them. Instead, use the insertNodeInto method of the TreeModel class to add a node. The following is an example of using this method, assuming that newN is the identifier you use for naming the new node and selection is the identifier for the last selected path component.

treeModel.insertNodeInto(newN,selection,selection.getChildCount());

After adding the new node, you need to make the new node visible. Assuming the newly instantiated node is newNode, the statement follows.

tree.scrollPathToVisible(new TreePath(newNode.getPath));

Finally, make sure to call the setSelectionPath() method so the new node is now selected, and update the text shown in the label.

c. Remove a node from the tree.

Remember that we only allow users to remove non-root leaf nodes. After removing a node, we want to have the parent node to become the last selected node and update the label with an appropriate error message. Use the statement to get the parent:

parent = (DefaultMutableTreeNode)selection.getParent();

To cause the parent node to highlight, use the statement:

tree.setSelectionPath(new TreePath(parent.getPath()));

The statement to remove a node from the tree is:

treeModel.removeNodeFromParent(selection);

d. Change the label that identifies a node on the tree.

The statement to change the label of a node is:

selected.setUserObject("new identifier");

You'll also need the statement treeModel.nodeChanged(selected); to force the modified node to display correctly. Make sure that each time you change a node, you give it a unique new identifier name.

e. Expand the entire tree.

You can use the loop in the original program to implement this option.

f. Collapse the entire tree.

The logic is very similar to that of expand tree except you need to count down instead of up. Use the method tree.collapseRow(row) instead of tree.expandRow(row)

g. Expand the path after a selected node of the tree.

The statement that will expand the path after selected is: tree.expandPath(new TreePath(selected.getPath());

h. Collapse the path after a selected node of the tree.

The statement that will collapse the path after selected is

tree.collapsePath(new TreePath(selected.getPath());

12) Answer the synthesis questions in an rtf or doc file (answers.rtf or answers.doc). Type your name and the lab number on this file and include the questions with the answers.

13) Zip your Eclipse project along with the synthesis answers and email to [email protected].

// Trees.java
// Program to demonstrate implementation of trees.

// Provides the framework for cs258 lab number 5.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.tree.*;

import javax.swing.event.*;

public class Trees

{ public static void main(String[] args)

{ SelectableTree tree = new SelectableTree();

}

}

// The tree class to be used as the framework for cs258 lab3.

class SelectableTree extends JFrame implements TreeSelectionListener

{ private JTree tree; // Reference tree that will be created.

private JLabel selectField; // Reference label for messages.

private JScrollPane scrollArea; // Reference scroll area to display tree.

private int childName = 1;// Node name.

// The constructor method.

public SelectableTree()

{ super("JTree Selections"); // Set the title line.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Enable the exit button.

// Create the tree nodes.

DefaultMutableTreeNode grandChild, child; // References to tree nodes.

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

// In a loop create children and grandchildren.

// Link the children to the root and the grandchildren to the children.

for (int childX=1; childX<=4; childX++)

{ child = new DefaultMutableTreeNode("Node " + childName++);

root.add(child);

for (int grandX=1; grandX<=4; grandX++)

{ grandChild = new DefaultMutableTreeNode("Node " + childName++);

child.add(grandChild);

}

}

// Instantiate the tree and add the selection listener.

tree = new JTree(root);

tree.addTreeSelectionListener(this);

for (int row = 0; row < tree.getRowCount(); row++) { tree.expandRow(row); }

// Construct the frame that will be displayed.

Container content = getContentPane(); // JFrame default root panel.

scrollArea = new JScrollPane(tree); // Instantiate scroll area.

selectField = new JLabel("Current Selection: NONE"); // Output Label.

// Add the scroll pane and the text field to the JFrame container.

content.add(scrollArea, BorderLayout.CENTER);

content.add(selectField, BorderLayout.SOUTH);

setSize(250, 275); // Set the JFrame window size.

setVisible(true); // Make everything visible.

}

// Method to respond to tree selection changes.

public void valueChanged(TreeSelectionEvent event)

{ selectField.setText( "Current Selection: " +

tree.getLastSelectedPathComponent().toString());

}

}

Java, Programming

  • Category:- Java
  • Reference No.:- M91335310
  • Price:- $70

Guranteed 36 Hours Delivery, In Price:- $70

Have any Question?


Related Questions in Java

Chatbotscreate a small networked chat application that is

Chatbots Create a small, networked chat application that is populated by bots. Introduction On an old server park, filled with applications from the early days of the internet, a few servers still run one of the earliest ...

Assignment taskwrite a java console application that allows

Assignment task Write a java console application that allows the user to read, validate, store, display, sort and search data such as flight departure city (String), flight number (integer), flight distance (integer), fl ...

Assignment game prototypeoverviewfor this assessment task

Assignment: Game Prototype Overview For this assessment task you are expected to construct a prototype level/area as a "proof of concept" for the game that you have designed in Assignment 1. The prototype should function ...

Assignment taskwrite a java console application that allows

Assignment task Write a java console application that allows the user to read, validate, store, display, sort and search data such as flight departure city (String), flight number (integer), flight distance (integer), fl ...

In relation to javaa what is constructor the purpose of

(In relation to Java) A. What is constructor? the purpose of default constructor? B. How do you get a copy of the object but not the reference of the object? C. What are static variables and instance variables? D. Compar ...

Project descriptionwrite a java program to traverse a

Project Description: Write a java program to traverse a directory structure (DirWalker.java) of csv files that contain csv files with customer info. A simple sample in provided in with the sample code but you MUST will r ...

Fundamentals of operating systems and java

Fundamentals of Operating Systems and Java Programming Purpose of the assessment (with ULO Mapping) This assignment assesses the following Unit Learning Outcomes; students should be able to demonstrate their achievements ...

Assessment -java program using array of Assessment -JAVA Program using array of objects

Assessment -JAVA Program using array of objects Objectives This assessment item relates to the course learning outcomes as stated in the Unit Profile. Details For this assignment, you are required to develop a Windowed G ...

Applied software engineering assignment 1 -learning

Applied Software Engineering Assignment 1 - Learning outcomes - 1. Understand the notion of software engineering and why it is important. 2. Analyse the risk factors associated with phases of the software development lif ...

Retail price calculatorwrite a java program that asks the

Retail Price Calculator Write a JAVA program that asks the user to enter an item's wholesale cost and its markup percentage. It should then display the item's retail price. For example: (If an item's wholesale cost is 5. ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As