Hi, im trying to create a GUI which will house a BST. When the user enters a number and clicks add, it should display that number as a leaf in a BST. It then adds each consecutive leaf onto the last to create the BST.
My problem is actually getting the little icon to appear. I want an icon to represent the leaf but which will also contain the user's number that they entered too. So far I can't get the icon to appear on the second panel. Please help if you can!
This is my code so far:
public void startGUI()
{
JFrame frame = new JFrame("Building a Binary Search Tree"); // Create Frame
JMenuBar menubar;
JMenuItem add, delete;
menubar = new JMenuBar();
frame.setJMenuBar(menubar);
// Create a menu and add it to the menubar
// Create some items, give them a handler and add then to the menu
add = new JMenuItem();
add.setText("Add Node");
add.setActionCommand("addition");
add.addActionListener(this);
menubar.add(add);
/*
JButton add = new JButton("Add Node");
add.setActionCommand("addition");
add.addActionListener(this);
menubar.add(add);
*/
delete = new JMenuItem();
delete.setText("Delete Node");
delete.setActionCommand("delete");
delete.addActionListener(this);
menubar.add(delete);
canvas.setLayout(new FlowLayout() ); // Use flow-layout, if we used Border layout then the buttons would expand to fit
canvas.setPreferredSize(new Dimension(500, 500) ); // the screen and would also over-write each other.
canvas.setBackground(Color.white);
canvasB.setLayout(new GridLayout() );
canvasB.setPreferredSize(new Dimension(500, 500) );
canvasB.setBackground(Color.yellow);
frame.add(canvas); // Add JPanel and other components to the frame
canvas.add(field);
canvas.add(add);
canvas.add(delete);
canvas.add(canvasB);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Closes the window
frame.pack(); // Frame set to the size of the components within the frame, naturally no components means nothing in the frame
frame.setVisible(true); // Make the frame visible
}
public void actionPerformed(ActionEvent e) {
String input = field.getText();
BinarySearchTree bst = new BinarySearchTree();
if("addition".equals(e.getActionCommand() ) ){
ImageIcon icon = new ImageIcon("/Users/myname/Pictures/plus.gif", "Plus Symbol");
JLabel label1 = new JLabel();
label1.setIcon(icon);
// label1 = new JLabel("Plus icon", icon, JLabel.CENTER);
System.out.println("Plus icon: " +icon);
canvasB.add(label1);
// label1.setVerticalTextPosition(JLabel.BOTTOM);
// label1.setHorizontalTextPosition(JLabel.CENTER);
} else if("delete".equals(e.getActionCommand() ) ){
}
}
protected static ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = practiceCW.class.getResource("/Users/myname/Pictures/plus.gif");
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
Cheers