Recursion and Formating Text in TextArea. HELP!

N

Newbie

Hi,

I have this assement for college that i have completed in building a "binary
tree" using recursion.

It prints fine through the "System.out.println" command and shows each level
as its built

How can I achieve the same results for my swing textArea as it is displayed
through the above command?

This is not part of the assement but more for my own learning process of
displaying things for the real world.

Thanks in Advance....

PS: both java class's are below.... the first is my gui class and the bottom
is my binary tree class.....

############################################################################
#################

BINT CLASS
############################################################################
#################
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

public class BinT extends JFrame {
JTextField input;
JTextArea display;
JScrollPane displayScroller;
JButton go, clear, transverse;
JLabel lab;
JPanel holder, inPan, txtPan, butPan;
BinaryTree myTree = new BinaryTree();

public BinaryTreeGUI() {
SetupWindow();
}

public void SetupWindow() {
setTitle("Binary Tree");
setResizable(false);
setSize(800, 600);

holder = new JPanel(new BorderLayout());
holder.setBorder(new EmptyBorder(5,5,5,5));

//###################### input Panel ######################
inPan = new JPanel();
inPan.setBorder( new EtchedBorder() );
inPan.setPreferredSize(new Dimension(387, 35));

lab = new JLabel("Input Products in Binary Tree : ");

input = new JTextField("");
input.setPreferredSize(new Dimension(70, 20));

go = new JButton("GO");
go.setPreferredSize(new Dimension(51, 20));
go.setToolTipText("Build Binary Tree");
ActionListener act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//handle errors in input
int treeSize = Integer.parseInt(input.getText()); // get user
input
try {
//check if not equal to ZERO
if (treeSize < 1) {
display.setText("ERROR! Input Must be Greater than ZERO
(Integer)");
}
else {
for (int i = 0; i < treeSize; i++) {
Product prod = new Product();
prod.enterData();
myTree.insert(prod);
//System.out.println("Current Binary Tree :"+myTree);
}
display.setText(""+myTree);
}
}
catch(NumberFormatException er) {
display.setText("ERROR! Input Must be an Integer.");
}
}
};
go.addActionListener(act);
inPan.add(lab);
inPan.add(input);
inPan.add(go);

//###################### button Panel ######################
butPan = new JPanel(new BorderLayout());
butPan.setBorder(new CompoundBorder(new EtchedBorder(),
new EmptyBorder(5,40,5,40)));
butPan.setPreferredSize(new Dimension(387, 35));
clear = new JButton("Clear Tree");
clear.setPreferredSize(new Dimension(130, 20));
clear.setToolTipText("Clear Binary Tree");
act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
myTree.clear();
display.setText("");
}
};
clear.addActionListener(act);
transverse = new JButton("Transverse Tree");
transverse.setPreferredSize(new Dimension(130, 20));
transverse.setToolTipText("Transverse Binary Tree");
act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//myTree.inOrderTrav();
//Need to change the method from void to String
display.setText("");
}
};
transverse.addActionListener(act);
butPan.add( BorderLayout.WEST, transverse);
butPan.add( BorderLayout.EAST, clear);

holder.add( BorderLayout.WEST,inPan);
holder.add( BorderLayout.EAST,butPan);
getContentPane().add( BorderLayout.NORTH, holder);

//###################### text Panel ######################
txtPan = new JPanel(new BorderLayout());
getContentPane().add( BorderLayout.SOUTH, txtPan );
display = new JTextArea();
//display.setEditable(false);
displayScroller = new JScrollPane(display,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(displayScroller);
}

public static void main(String[] args) {
BinT frame = new BinT();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
############################################################################
#########

BINARY TREE CLASS
############################################################################
#########

public class BinaryTree {
protected TreeNode root;

public BinaryTree() {
root = null;
}

public boolean isEmpty() {
return root == null;
}

public boolean isFull() {
return false;
}

public void clear() {
root = null;
}

public void insert (Product obj) {
root = insert( obj, root );
}
private TreeNode insert(Product obj, TreeNode root) {
if (root == null) { // empty root/tree
root = new TreeNode(obj);
}
else if (obj.code.compareTo(root.prod.code) < 0) {
root.left = insert( obj, root.left );
}
else if (obj.code.compareTo(root.prod.code) > 0) {
root.right = insert( obj, root.right );
}
return(root);
}

public String toString() {
if (isEmpty())
return "";// new String("EMPTY TREE");
else
return (root.toString());
}

public void inOrderTrav(){
System.out.print("\nIn Order Traversal : ");
inOrderTrav(root);
}
protected void inOrderTrav(TreeNode tn){
if(tn == null)
return;
inOrderTrav(tn.left);
System.out.print(tn.prod.code+" ");
inOrderTrav(tn.right);
}

private class TreeNode {
protected Product prod;
protected TreeNode left, right;

private TreeNode(Product obj) {
prod = obj;
left = null;
right = null;
}

public String toString() {
String str = new String();
str += prod.code;
if (left == null)
str += "";
else str +=
" L:"+left.toString();
if (right == null)
str += "";
else str +=
" R:"+right.toString();
return(str);
}
} // end inner TreeNode class

} // end BinaryTree class
 
N

Newbie

The binary tree uses an external class. product.java.

Maybe thatswhy it wouldn't compile?

it runs perfectly here...

below is the product class...
############################################################
PRODUCT.CLASS
############################################################

import java.util.Random; // import random class
public class Product {
protected String name, code;
char[] letters =
{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s'
,'t','u','v','w','x','y','z'};
static Random rnd = new Random();

public Product()
{
// initialize instance variable of product
name = "x";
code = "x";
}

public int compareTo(Product P)
{
String str1,str2;
str1 = this.code;
str2 = P.code;
int result = 0; // start as if keys are equal
String out = "";
if ( this.code.length() == 9 && P.code.length() == 9 ) { // check
length of each string
if ( !str2.substring(0,1).equals("0") ) { // check to
make sure leading char is not zero
str1 = this.code.toUpperCase(); // insure that
alpha characters are capitalized
str2 = P.code.toUpperCase();

if (str1.equals(str2)) {
result = 0;
}
else if (str1.compareTo(str2)<0) {
result = -1;
}
else if (str1.compareTo(str2)>0) {
result = 1;
}
}
else {
result = -200;
}
}
else {
result = -100;
}
return result;
}
public void enterData() {
name = getRandomName(); // get a random name
code = getRandomCode(); // get a random product code
}
public String getRandomName() {
StringBuffer sb = new StringBuffer();
int nameLengh = rnd.nextInt(17)+4; // randomly generate length from
4 to 20
for (int i=0; i<nameLengh; i++) {
sb.append(letters[rnd.nextInt(26)]);
}
return sb.toString();
}
public String getRandomCode() {
StringBuffer sb = new StringBuffer();
int codeNum = rnd.nextInt(899999)+100000; // Generate number
(100000 - 999999)
sb.append(codeNum);
sb.append(letters[rnd.nextInt(26)]); // Generate three characters
sb.append(letters[rnd.nextInt(26)]);
sb.append(letters[rnd.nextInt(26)]);
return sb.toString();
}
}

############################################################################
#################
 
A

Andrew Thompson

The binary tree uses an external class. product.java.

Maybe thatswhy it wouldn't compile?

No. Line wrap was a problem, as it is in the latest code you posted.

But maybe you should find that out for yourself by
taking the advice I outlined in the link I gave you.

Also, maybe you should cut the code from the approximate
300 lines you currently have, and reduce the public classes
to default so it can make an SSCCE.
it runs perfectly here...

....I'm not there.

--
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
 
N

Newbie

I have dramically reduced all code to the minimum and reformatted it to be
80chars or less.

Alot of the white spacing has been taken out to reduce the number of lines
as has the GUI.

ALL new code is below... seperate out the classes into seperate files before
compilling..

I have done all the above and tested it and it works ok...with exception to
my original request for assistance.

Thankyou for your help!

###################################################################

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class GUI extends JFrame {
JTextField input;
JTextArea display;
JScrollPane displayScroller;
JButton go, clear, transverse;
JLabel lab;
JPanel holder, inPan, txtPan, butPan;
BinaryTree myTree = new BinaryTree();
public GUI() { SetupWindow(); }
public void SetupWindow() {
setSize(800, 600);
holder = new JPanel(new BorderLayout());
inPan = new JPanel();
inPan.setPreferredSize(new Dimension(387, 35));
lab = new JLabel("Input Products in Binary Tree : ");
input = new JTextField("");
input.setPreferredSize(new Dimension(70, 20));
go = new JButton("GO");
go.setPreferredSize(new Dimension(51, 20));
ActionListener act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int treeSize = Integer.parseInt(input.getText());
try { //check if not equal to ZERO
if (treeSize < 1) { display.setText("ERROR!"); }
else {
for (int i = 0; i < treeSize; i++) {
product prod = new product();
prod.enterData();
myTree.insert(prod);
System.out.println(""+myTree);
}
display.append(""+myTree);
}
} //end try
catch(NumberFormatException er) {
display.setText("ERROR! Input Must be an Integer.");
} //end catch
}
}; // end actionPerformed
go.addActionListener(act);
inPan.add(lab);
inPan.add(input);
inPan.add(go);
butPan = new JPanel(new BorderLayout());
butPan.setPreferredSize(new Dimension(387, 35));
clear = new JButton("Clear Tree");
clear.setPreferredSize(new Dimension(130, 20));
act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
myTree.clear();
input.setText("");
display.setText("");
}
};
clear.addActionListener(act);
transverse = new JButton("Transverse Tree");
transverse.setPreferredSize(new Dimension(130, 20));
act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//this needs to be call a toString not a void
display.append("\n"+myTree.inOrderTrav());
}
};
transverse.addActionListener(act);
butPan.add( BorderLayout.WEST, transverse);
butPan.add( BorderLayout.EAST, clear);
holder.add( BorderLayout.WEST,inPan);
holder.add( BorderLayout.EAST,butPan);
getContentPane().add( BorderLayout.NORTH, holder);
txtPan = new JPanel(new BorderLayout());
getContentPane().add( BorderLayout.SOUTH, txtPan );
display = new JTextArea();
displayScroller = new JScrollPane(display,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(displayScroller);
}
public static void main(String[] args) {
GUI frame = new GUI();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
###################################################################

public class BinaryTree {
protected TreeNode root;
public BinaryTree() { root = null; }
public boolean isEmpty() { return root == null; }
public boolean isFull() { return false; }
public void clear() { root = null; }
public void insert (product obj) { root=insert(obj,root); }
private TreeNode insert(product obj,TreeNode root) {
if (root==null) { root = new TreeNode(obj); }
else if (obj.code.compareTo(root.prod.code) < 0) {
root.left = insert( obj, root.left ); }
else if (obj.code.compareTo(root.prod.code) > 0) {
root.right = insert( obj, root.right ); }
return(root);
}
public String toString() {
if (isEmpty()) return "";
else return (root.toString());
}
public String inOrderTrav() {
System.out.print("\nTraversal : ");
return inOrderTrav(root);
}
protected String inOrderTrav(TreeNode tn) {
String str = new String();
if(tn == null) return "";
inOrderTrav(tn.left);
System.out.print(tn.prod.code+" ");
inOrderTrav(tn.right);
return str;
}

private class TreeNode {
protected product prod;
protected TreeNode left, right;
private TreeNode(product obj) {
prod = obj;
left = null;
right = null;
}
public String toString() {
String str = new String();
str += prod.code;
if (left == null) str += "";
else str += " "+left.toString();
if (right == null) str += "";
else str += " "+right.toString();
return(str);
}
}
}
#######################################################################

import java.util.Random;
public class product {
protected String name, code;
char[] letters ={'a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z'};
static Random rnd = new Random();

public product() {
name = "x";
code = "x";
}

public int compareTo(product P) {
String str1,str2;
str1 = this.code;
str2 = P.code;
int result = 0; // start as if keys are equal
str1 = this.code.toUpperCase();
str2 = P.code.toUpperCase();
if (str1.equals(str2)) { result = 0; }
else if (str1.compareTo(str2)<0) { result = -1; }
else if (str1.compareTo(str2)>0) { result = 1; }
return result;
}
public void enterData() {
name = getRandomName();
code = getRandomCode();
}
public String getRandomName() {
StringBuffer sb = new StringBuffer();
int nameLengh = rnd.nextInt(17)+4;
for (int i=0; i<nameLengh; i++) {
sb.append(letters[rnd.nextInt(26)]);
}
return sb.toString();
}
public String getRandomCode() {
StringBuffer sb = new StringBuffer();
int codeNum = rnd.nextInt(899999)+100000;
sb.append(codeNum);
sb.append(letters[rnd.nextInt(26)]);
sb.append(letters[rnd.nextInt(26)]);
sb.append(letters[rnd.nextInt(26)]);
return sb.toString();
}
}
 
A

andreas

It prints fine through the "System.out.println" command and shows each
level
as its built
How can I achieve the same results for my swing textArea as it is displayed
through the above command?

if you want it to look like in the console, you have to use the system font
of
the console (or just some font with fixed character width like "courier
new")
and then basically call:

display.append(myTree+"\r\n");

instead of

System.out.println(""+myTree);

you have to do the carriage return line feed yourself.
I have dramically reduced all code to the minimum and reformatted it to be
80chars or less.

Alot of the white spacing has been taken out to reduce the number of lines
as has the GUI.

ALL new code is below... seperate out the classes into seperate files
before
compilling..

I have done all the above and tested it and it works ok...with exception
to
my original request for assistance.

i noticed that you also changed some code from display.setText to
display.append

your method inOrderTrav(TreeNode tn) still contains a System.out. instead of
the display.append
====================================
protected String inOrderTrav(TreeNode tn) {
String str = new String();
if(tn == null) return "";
inOrderTrav(tn.left);
System.out.print(tn.prod.code+" ");
inOrderTrav(tn.right);
return str;
}

====================================

i hope i am addressing your problem,
i didn't run the code...

andreas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top