Help w/ clicking on leaves of tree node
Hello,
I am fairly new to Flex and coding in general, so please bare
with me if my problems seems like a trivial one.
I am trying to create a tree list, where the contents of the
tree are actually links. For example, the top level of the tree
node would be a category (companies), and the leaves of the tree
would be the company names. In addition, I would like the user to
be taken, in a new browser window, to a URL specified in the XML
list when clicking on a company name.
I am having problems resolving the click actions in the app.
I can get the app to open and close the nodes of the tree cleanly,
but when I try to add some code to take the user to a URL when
clicking on a company name (leaf), I get errors.
I am really stuck on how to read the click event in the tree
list, run to the associated XML file to find the URL, then open up
a new browser page to that URL.
Can someone help me please? I've added a snippet of code to
review.
Thank you in advance!
"hokudan" <[email protected]> wrote in
message
news:ghk08n$pdb$[email protected]..
> Hi Amy,
>
> Thank you for your reply. Here are the errors that I'm
getting in Flash:
>
> ReferenceError: Error #1069: Property source not found
on mx.controls.Tree
> and
> there is no default value.
> Two of the nodes in the tree also have a 'source' value
that I've entered-
> do
> I need to make it a separate line instead of including
it with the 'label'
> field?
Two things:
1) I'm thinking the currentTarget of the itemClick event will
be the tree
itself, not the node. So you need to look at the selectedItem
property to
get the node. See the example under Handling Tree control
events:
http://livedocs.adobe.com/flex/3/html/help.html?content=dpcontrols_8.html
2) To answer your question, you just need to reference it
properly for
however you set up the xml:
http://dispatchevent.org/roger/as3-e4x-rundown/
Similar Messages
-
Help with building a JTree using tree node and node renderers
Hi,
I am having a few problems with JTree's. basically I want to build JTree from a web spider. The webspide searches a website checking links and stores the current url that is being processed as a string in the variable msg. I wan to use this variable to build a JTree in a new class and then add it to my GUI. I have created a tree node class and a renderer node class, these classes are built fine. can someone point me in the direction for actually using these to build my tree in a seperate class and then displaying it in a GUI class?
*nodeRenderer.java
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.net.*;
public class nodeRenderer extends DefaultTreeCellRenderer
implements TreeCellRenderer
public static Icon icon= null;
public nodeRenderer() {
icon = new ImageIcon(getClass().getResource("icon.gif"));
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
treeNode node = (treeNode)(((DefaultMutableTreeNode)value).getUserObject());
if(icon != null) // set a custom icon
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
return this;
*treeNode.java
*this is the class to represent a node
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
import java.net.*;
* Class used to hold information about a web site that has
* been searched by the spider class
public class treeNode
*Url from the WebSpiderController Class
*that is currently being processed
public String msg;
treeNode(String urlText)
msg = urlText;
String getUrlText()
return msg;
//gui.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class gui extends JFrame implements Runnable
*declare variable, boolean
*thread, a object and a center
*pane
protected URL urlInput;
protected Thread bgThread;
protected boolean run = false;
protected WebSpider webSpider;
public gui()
*create the gui here
setTitle("Testing Tool");
setSize(600,600);
//add Buttons to the tool bar
start.setText("Start");
start.setActionCommand("Start");
toolBar.add(start);
ButtonListener startListener = new ButtonListener();
start.addActionListener(startListener);
cancel.setText("Cancel");
cancel.setActionCommand("Cancel");
toolBar.add(cancel);
ButtonListener cancelListener = new ButtonListener();
cancel.addActionListener(cancelListener);
close.setText("Close");
close.setActionCommand("Close");
toolBar.add(close);
ButtonListener closeListener = new ButtonListener();
close.addActionListener(closeListener);
//creat a simple form
urlLabel.setText("Enter URL:");
urlLabel.setBounds(100,36,288,24);
formTab.add(urlLabel);
url.setBounds(170,36,288,24);
formTab.add(url);
current.setText("Currently Processing: ");
current.setBounds(100,80,288,24);
formTab.add(current);
//add scroll bars to the error messages screen and website structure
errorPane.setAutoscrolls(true);
errorPane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
errorPane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
errorPane.setOpaque(true);
errorTab.add(errorPane);
errorPane.setBounds(0,0,580,490);
errorText.setEditable(false);
errorPane.getViewport().add(errorText);
errorText.setBounds(0,0,600,550);
treePane.setAutoscrolls(true);
treePane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
treePane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
treePane.setOpaque(true);
treeTab.add(treePane);
treePane.setBounds(0,0,580,490);
treeText.setEditable(false);
treePane.getViewport().add(treeText);
treeText.setBounds(0,0,600,550);
//create the tabbed window
centerPane.setBorder(new javax.swing.border.EtchedBorder());
formTab.setLayout(null);
errorTab.setLayout(null);
treeTab.setLayout(null);
centerPane.addTab("Search Parameters", formTab);
centerPane.addTab("Error Messages", errorTab);
centerPane.addTab("Website Structure", treeTab);
//add the tool bar and tabbed pane
getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);
*create the tool bar pane, a center pane, add the buttons,
*labels, tabs, a text field for user input here
javax.swing.JPanel toolBar = new javax.swing.JPanel();
javax.swing.JButton start = new javax.swing.JButton();
javax.swing.JButton cancel = new javax.swing.JButton();
javax.swing.JButton close = new javax.swing.JButton();
javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
javax.swing.JPanel formTab = new javax.swing.JPanel();
javax.swing.JLabel urlLabel = new javax.swing.JLabel();
javax.swing.JLabel current = new javax.swing.JLabel();
javax.swing.JTextField url = new javax.swing.JTextField();
javax.swing.JPanel errorTab = new javax.swing.JPanel();
javax.swing.JTextArea errorText = new javax.swing.JTextArea();
javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
javax.swing.JPanel treeTab = new javax.swing.JPanel();
javax.swing.JTextArea treeText = new javax.swing.JTextArea();
javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
javax.swing.JTree searchTree = new javax.swing.JTree();
*show the gui
public static void main(String args[])
(new gui()).setVisible(true);
*listen for the button presses and set the
*boolean flag depending on which button is pressed
class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
Object object = event.getSource();
if (object == start)
run = true;
startActionPerformed(event);
if (object == cancel)
run = false;
startActionPerformed(event);
if (object == close)
System.exit(0);
*this method is called when the start or
*cancel button is pressed.
void startActionPerformed (ActionEvent event)
if (run == true && bgThread == null)
bgThread = new Thread(this);
bgThread.start();
if (run == false && bgThread != null)
webSpider.cancel();
*this mehtod will start the background thred.
*the background thread is required so that the
*GUI is still displayed
public void run()
try
webSpider = new WebSpider(this);
webSpider.clear();
urlInput = new URL(url.getText());
webSpider.addURL(urlInput);
webSpider.run();
bgThread=null;
catch (MalformedURLException e)
addressError addErr = new addressError();
addErr.addMsg = "URL ERROR - PLEASE CHECK";
SwingUtilities.invokeLater(addErr);
*this method is called by the web spider
*once a url is found. Validation of navigation
*happens here.
public boolean urlFound(URL urlInput,URL url)
CurrentlyProcessing pro = new CurrentlyProcessing();
pro.msg = url.toString();
SwingUtilities.invokeLater(pro);
if (!testLink(url))
navigationError navErr = new navigationError();
navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
return false;
if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
return false;
else
return true;
*this method is called internally to check
*that a link works
protected boolean testLink(URL url)
try
URLConnection connection = url.openConnection();
connection.connect();
return true;
catch (IOException e)
return false;
*this method is called when an error is
*found.
public void URLError(URL url)
*this method is called when an email
*address is found
public void emailFound(String email)
/*this method will update any errors found inc
*address errors and broken links
class addressError implements Runnable
public String addMsg;
public void run()
errorText.append(addMsg);
current.setText("Currently Processing: "+ addMsg);
class navigationError implements Runnable
public String navMsg;
public void run()
errorText.append(navMsg);
*this method will update the currently
*processing field on the GUI
class CurrentlyProcessing implements Runnable
public String msg;
public void run()
current.setText("Currently Processing: " + msg );
//webspider.java
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.tree.*;
import javax.swing.*;
*this class implements the spider.
public class WebSpider extends HTMLEditorKit
*make a collection of the URL's
protected Collection urlErrors = new ArrayList(3);
protected Collection urlsWaiting = new ArrayList(3);
protected Collection urlsProcessed = new ArrayList(3);
//report URL's to this class
protected gui report;
*this flag will indicate whether the process
*is to be cancelled
protected boolean cancel = false;
*The constructor
*report the urls to the wui class
public WebSpider(gui report)
this.report = report;
*get the urls from the above declared
*collections
public Collection getUrlErrors()
return urlErrors;
public Collection getUrlsWaiting()
return urlsWaiting;
public Collection getUrlsProcessed()
return urlsProcessed;
* Clear all of the collections.
public void clear()
getUrlErrors().clear();
getUrlsWaiting().clear();
getUrlsProcessed().clear();
*Set a flag that will cause the begin
*method to return before it is done.
public void cancel()
cancel = true;
*add the entered url for porcessing
public void addURL(URL url)
if (getUrlsWaiting().contains(url))
return;
if (getUrlErrors().contains(url))
return;
if (getUrlsProcessed().contains(url))
return;
/*WRITE TO LOG FILE*/
log("Adding to workload: " + url );
getUrlsWaiting().add(url);
*process a url
public void processURL(URL url)
try
/*WRITE TO LOGFILE*/
log("Processing: " + url );
// get the URL's contents
URLConnection connection = url.openConnection();
if ((connection.getContentType()!=null) &&
!connection.getContentType().toLowerCase().startsWith("text/"))
getUrlsWaiting().remove(url);
getUrlsProcessed().add(url);
log("Not processing because content type is: " +
connection.getContentType() );
return;
// read the URL
InputStream is = connection.getInputStream();
Reader r = new InputStreamReader(is);
// parse the URL
HTMLEditorKit.Parser parse = new HTMLParse().getParser();
parse.parse(r,new Parser(url),true);
catch (IOException e)
getUrlsWaiting().remove(url);
getUrlErrors().add(url);
log("Error: " + url );
report.URLError(url);
return;
// mark URL as complete
getUrlsWaiting().remove(url);
getUrlsProcessed().add(url);
log("Complete: " + url );
*start the spider
public void run()
cancel = false;
while (!getUrlsWaiting().isEmpty() && !cancel)
Object list[] = getUrlsWaiting().toArray();
for (int i=0;(i<list.length)&&!cancel;i++)
processURL((URL)list);
* A HTML parser callback used by this class to detect links
protected class Parser extends HTMLEditorKit.ParserCallback
protected URL urlInput;
public Parser(URL urlInput)
this.urlInput = urlInput;
public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos)
String href = (String)a.getAttribute(HTML.Attribute.HREF);
if((href==null) && (t==HTML.Tag.FRAME))
href = (String)a.getAttribute(HTML.Attribute.SRC);
if (href==null)
return;
int i = href.indexOf('#');
if (i!=-1)
href = href.substring(0,i);
if (href.toLowerCase().startsWith("mailto:"))
report.emailFound(href);
return;
handleLink(urlInput,href);
public void handleStartTag(HTML.Tag t,MutableAttributeSet a,int pos)
handleSimpleTag(t,a,pos); // handle the same way
protected void handleLink(URL urlInput,String str)
try
URL url = new URL(urlInput,str);
if (report.urlFound(urlInput,url))
addURL(url);
catch (MalformedURLException e)
log("Found malformed URL: " + str);
*log the information of the spider
public void log(String entry)
System.out.println( (new Date()) + ":" + entry );
I have a seperate class for parseing the HTML. Any help would be greatly appreciated
mrvHi Sorry to be a pain again,
I have re worked the gui class so it looks like this now:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class gui extends JFrame implements Runnable
*declare variable, boolean
*thread, a object and a center
*pane
protected URL urlInput;
protected Thread bgThread;
protected boolean run = false;
protected WebSpider webSpider;
public String msgInfo;
public String brokenUrl;
public String goodUrl;
public String deadUrl;
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
public gui()
*create the gui here
setTitle("Testing Tool");
setSize(600,600);
//add Buttons to the tool bar
start.setText("Start");
start.setActionCommand("Start");
toolBar.add(start);
ButtonListener startListener = new ButtonListener();
start.addActionListener(startListener);
cancel.setText("Cancel");
cancel.setActionCommand("Cancel");
toolBar.add(cancel);
ButtonListener cancelListener = new ButtonListener();
cancel.addActionListener(cancelListener);
close.setText("Close");
close.setActionCommand("Close");
toolBar.add(close);
ButtonListener closeListener = new ButtonListener();
close.addActionListener(closeListener);
//creat a simple form
urlLabel.setText("Enter URL:");
urlLabel.setBounds(100,36,288,24);
formTab.add(urlLabel);
url.setBounds(170,36,288,24);
formTab.add(url);
current.setText("Currently Processing: ");
current.setBounds(100,80,288,24);
formTab.add(current);
//add scroll bars to the error messages screen and website structure
errorPane.setAutoscrolls(true);
errorPane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
errorPane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
errorPane.setOpaque(true);
errorTab.add(errorPane);
errorPane.setBounds(0,0,580,490);
errorText.setEditable(false);
errorPane.getViewport().add(errorText);
errorText.setBounds(0,0,600,550);
treePane.setAutoscrolls(true);
treePane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
treePane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
treePane.setOpaque(true);
treeTab.add(treePane);
treePane.setBounds(0,0,580,490);
treeText.setEditable(false);
treePane.getViewport().add(treeText);
treeText.setBounds(0,0,600,550);
//JTree
// NEW CODE
rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
treeText.add(tree);
//create the tabbed window
centerPane.setBorder(new javax.swing.border.EtchedBorder());
formTab.setLayout(null);
errorTab.setLayout(null);
treeTab.setLayout(null);
centerPane.addTab("Search Parameters", formTab);
centerPane.addTab("Error Messages", errorTab);
centerPane.addTab("Website Structure", treeTab);
//add the tool bar and tabbed pane
getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);
*create the tool bar pane, a center pane, add the buttons,
*labels, tabs, a text field for user input here
javax.swing.JPanel toolBar = new javax.swing.JPanel();
javax.swing.JButton start = new javax.swing.JButton();
javax.swing.JButton cancel = new javax.swing.JButton();
javax.swing.JButton close = new javax.swing.JButton();
javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
javax.swing.JPanel formTab = new javax.swing.JPanel();
javax.swing.JLabel urlLabel = new javax.swing.JLabel();
javax.swing.JLabel current = new javax.swing.JLabel();
javax.swing.JTextField url = new javax.swing.JTextField();
javax.swing.JPanel errorTab = new javax.swing.JPanel();
javax.swing.JTextArea errorText = new javax.swing.JTextArea();
javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
javax.swing.JPanel treeTab = new javax.swing.JPanel();
javax.swing.JTextArea treeText = new javax.swing.JTextArea();
javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
javax.swing.JTree tree = new javax.swing.JTree();
*show the gui
public static void main(String args[])
(new gui()).setVisible(true);
*listen for the button presses and set the
*boolean flag depending on which button is pressed
class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
Object object = event.getSource();
if (object == start)
run = true;
startActionPerformed(event);
if (object == cancel)
run = false;
startActionPerformed(event);
if (object == close)
System.exit(0);
*this method is called when the start or
*cancel button is pressed.
void startActionPerformed (ActionEvent event)
if (run == true && bgThread == null)
bgThread = new Thread(this);
bgThread.start();
//new line of code
treeText.addObject(msgInfo);
if (run == false && bgThread != null)
webSpider.cancel();
*this mehtod will start the background thred.
*the background thread is required so that the
*GUI is still displayed
public void run()
try
webSpider = new WebSpider(this);
webSpider.clear();
urlInput = new URL(url.getText());
webSpider.addURL(urlInput);
webSpider.run();
bgThread = null;
catch (MalformedURLException e)
addressError addErr = new addressError();
addErr.addMsg = "URL ERROR - PLEASE CHECK";
SwingUtilities.invokeLater(addErr);
*this method is called by the web spider
*once a url is found. Validation of navigation
*happens here.
public boolean urlFound(URL urlInput,URL url)
CurrentlyProcessing pro = new CurrentlyProcessing();
pro.msg = url.toString();
SwingUtilities.invokeLater(pro);
if (!testLink(url))
navigationError navErr = new navigationError();
navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
brokenUrl = url.toString();
return false;
if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
return false;
else
return true;
*this method is returned if there is no link
*on a web page, e.g. there us a dead end
public void urlNotFound(URL urlInput)
deadEnd dEnd = new deadEnd();
dEnd.dEMsg = "No links on "+urlInput+"\n";
deadUrl = urlInput.toString();
*this method is called internally to check
*that a link works
protected boolean testLink(URL url)
try
URLConnection connection = url.openConnection();
connection.connect();
goodUrl = url.toString();
return true;
catch (IOException e)
return false;
*this method is called when an error is
*found.
public void urlError(URL url)
*this method is called when an email
*address is found
public void emailFound(String email)
/*this method will update any errors found inc
*address errors and broken links
class addressError implements Runnable
public String addMsg;
public void run()
current.setText("Currently Processing: "+ addMsg);
errorText.append(addMsg);
class navigationError implements Runnable
public String navMsg;
public void run()
errorText.append(navMsg);
class deadEnd implements Runnable
public String dEMsg;
public void run()
errorText.append(dEMsg);
*this method will update the currently
*processing field on the GUI
public class CurrentlyProcessing implements Runnable
public String msg;
//new line
public String msgInfo = msg;
public void run()
current.setText("Currently Processing: " + msg );
* NEW CODE
* NEED THIS CODE SOMEWHERE
* treeText.addObject(msgInfo);
public DefaultMutableTreeNode addObject(Object child)
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null)
parentNode = rootNode;
else
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
return addObject(parentNode, child, true);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child)
return addObject(parent, child, false);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,boolean shouldBeVisible)
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
if (parent == null)
parent = rootNode;
treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
if (shouldBeVisible)
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
return childNode;
public class MyTreeModelListener implements TreeModelListener
public void treeNodesChanged (TreeModelEvent e)
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)
(e.getTreePath().getLastPathComponent());
try
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)
(node.getChildAt(index));
catch (NullPointerException exc)
public void treeNodesInserted(TreeModelEvent e)
public void treeStructureChanged(TreeModelEvent e)
public void treeNodesRemoved(TreeModelEvent e)
I beleive that this line of code is required:
treeText.addObject(msgInfo);
I have placed it where the action events start the spider, but i keep getting this error:
cannot resolve symbol
symbol : method addObject (java.lang.String)
location: class javax.swing.JTextArea
treeText.addObject(msgInfo);
Also the jtree is not showing the window that I want it to and I am not too sure why. could you have a look to see why? i think it needs a fresh pair of eyes.
Many thanks
MrV -
How to trigger an ActionListener in different class on click of a tree node
Hi guyz,
There are three panels inside my main Frame
-->TopPanel,MiddlePanel and BottomPanel. I have a tree structure inside a panel. This panel along with couple more panels is in MiddlePanel. My main class is "mainClass.java". Inside that i have an actionListener for a specific button. I need to trigger that actionListener when i click one of the tree nodes in the panel i specified before. The problem is that my MiddlePanel is itself a different ".java" file which is being called in my "mainClass" when a specific button is clicked. There are different buttons in my "mainClass" file and for each one i am creating different MiddlePanels depending on the buttons clicked.
So, if i click the tree node, i need to remove the MiddlePanel and recreate the MiddlePanel(One that will be created when a different button in the mainClass file is clicked). i.e., i need to trigger the actionListener for that corresponding button. Is there a way to do it?use this code to call different panel by selecting tree node.....ok
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.sql.SQLException;
import javax.swing.event.*;
class MainTree extends JFrame
private static final long serialVersionUID = 1L;
CardLayout cl = new CardLayout();
JPanel panel = new JPanel(cl);
public MainTree() throws Exception
JPanel blankPanel = new JPanel();
blankPanel.setBorder(BorderFactory.createTitledBorder("Blank Panel"));
panel.add(blankPanel,"0");
panel.add(blankPanel,BorderLayout.CENTER);
panel.setPreferredSize(new Dimension(800, 100));
setSize(1000, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// getContentPane().setLayout(new GridLayout(1,2));
getContentPane().setLayout(new BorderLayout());
ConfigTree test = new ConfigTree();
DefaultMutableTreeNode mainTree = (DefaultMutableTreeNode)test.buildTree();
JTree tree = new JTree(mainTree);
tree.setCellRenderer(new DefaultTreeCellRenderer(){
private static final long serialVersionUID = 1L;
public Component getTreeCellRendererComponent(JTree tree,Object value,
boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus){
JLabel lbl = (JLabel)super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)value).getUserObject();
if(node.icon != null)lbl.setIcon(node.icon);
return lbl;
getContentPane().add(new JScrollPane(tree));
loadCardPanels((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot());
getContentPane().add(panel,BorderLayout.EAST);
getContentPane().add(blankPanel,BorderLayout.WEST);
// getContentPane().add(panel);
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent tse){
NodeWithID node =(NodeWithID)((DefaultMutableTreeNode)((TreePath)tse.getPath())
.getLastPathComponent()).getUserObject();
if(node.nodePanel != null)
String cardLayoutID = node.ID;
cl.show(panel,cardLayoutID);
cl.show(panel,"0");
public void loadCardPanels(DefaultMutableTreeNode dmtn)
for(int x = 0; x < dmtn.getChildCount(); x++)
if(((DefaultMutableTreeNode)dmtn.getChildAt(x)).isLeaf() == false)
loadCardPanels((DefaultMutableTreeNode)dmtn.getChildAt(x));
NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)dmtn.getChildAt(x)).getUserObject();
if(node.nodePanel != null)
String cardLayoutID = node.ID;
panel.add(cardLayoutID,node.nodePanel);
public static void main(String[] args) throws Exception{new MainTree().setVisible(true);}
class ConfigTree
public Object buildTree() throws Exception
NodeWithID n0 = new NodeWithID("HelpDesk","");
NodeWithID n1 = new NodeWithID("Administrator",n0.nodeName);
NodeWithID n2 = new NodeWithID("Report Form",n1.nodeName,new Tree().getContentPane());
NodeWithID n3 = new NodeWithID("Create User",n2.nodeName,new JPanel());
NodeWithID n4 = new NodeWithID("Unlock User",n2.nodeName,new unlockui().getContentPane());
NodeWithID n5 = new NodeWithID("List User",n2.nodeName,new JPanel());
NodeWithID n6 = new NodeWithID("Assign Role",n2.nodeName,new AssignRole());
NodeWithID n9 = new NodeWithID("Operator",n1.nodeName,new JPanel());
NodeWithID n10 = new NodeWithID("Create Ticket",n9.nodeName,new JPanel());
NodeWithID n11 = new NodeWithID("My Ticket",n9.nodeName,new JPanel());
NodeWithID n12 = new NodeWithID("All Ticket",n9.nodeName,new JPanel());
NodeWithID n13 = new NodeWithID("Event Viewer",n1.nodeName,new JPanel());
DefaultMutableTreeNode top = new DefaultMutableTreeNode(n0);
DefaultMutableTreeNode branch1 = new DefaultMutableTreeNode(n1);
top.add(branch1);
DefaultMutableTreeNode node1_b1 = new DefaultMutableTreeNode(n2);
DefaultMutableTreeNode n1_node1_b1 = new DefaultMutableTreeNode(n3);
DefaultMutableTreeNode n2_node1_b1 = new DefaultMutableTreeNode(n4);
DefaultMutableTreeNode n3_node1_b1 = new DefaultMutableTreeNode(n5);
DefaultMutableTreeNode n4_node1_b1 = new DefaultMutableTreeNode(n6);
branch1.add(node1_b1);
branch1.add(n1_node1_b1);
branch1.add(n2_node1_b1);
branch1.add(n3_node1_b1);
branch1.add(n4_node1_b1);
DefaultMutableTreeNode node4_b1 = new DefaultMutableTreeNode(n9);
DefaultMutableTreeNode n1_node4_b1 = new DefaultMutableTreeNode(n10);
DefaultMutableTreeNode n2_node4_b1 = new DefaultMutableTreeNode(n11);
DefaultMutableTreeNode n3_node4_b1 = new DefaultMutableTreeNode(n12);
node4_b1.add(n1_node4_b1);
node4_b1.add(n2_node4_b1);
node4_b1.add(n3_node4_b1);
DefaultMutableTreeNode node5_b1 = new DefaultMutableTreeNode(n13);
branch1.add(node1_b1);
branch1.add(node4_b1);
branch1.add(node5_b1);
return top;
class NodeWithID
String nodeName;
String ID;
JPanel nodePanel;
ImageIcon icon;
public NodeWithID(String nn,String parentName)
nodeName = nn;
ID = parentName+" - "+nodeName;
public NodeWithID(String nn,String parentName,Container container)
this(nn,parentName);
nodePanel = (JPanel) container;
nodePanel.setBorder(BorderFactory.createTitledBorder(ID + " Panel"));
public NodeWithID(String nn,String parentName,JPanel p, ImageIcon i)
this(nn,parentName,p);
icon = i;
public String toString(){return nodeName;}
} -
How to find the coordinates of a mouse click in a Tree node ?
Hello
I have a JTree that have few nodes. The nodes contain an icon and a label (using custom cell renderer) and I want to receive right clicks on the icon and show a popup menu.
The problem is I can only get the right click on the whole tree node, not only the icon.
I tried two approaches:
1. register the mouse listener directly with the icon in the cell renderer. That doesnt work since the events received by the tree node do not propagate to its sub-components.
2. Register the event with the JTree itself and then try to find which part of the tree node was clicked (see if it was within the coordinates of the icon).
But I cant get the node's coordinates or width.
I tried using SwingUtilities.convertPoint or SwingUtilities.ConvertMouseEvent but it just doesnt work with DefaultMutableTreeNode.
Any ideas how to do it ?user11973359 wrote:
1. register the mouse listener directly with the icon in the cell renderer. That doesnt work since the events received by the tree node do not propagate to its sub-components.No, it doesn't work because a renderer isn't added to any component hierarchy. It isn't in any way a 'sub-component'.
Read about editor and renderer concepts in the Oracle tutorial on How to Use Tables.
user11973359 wrote:
2. Register the event with the JTree itself and then try to find which part of the tree node was clicked (see if it was within the coordinates of the icon).
But I cant get the node's coordinates or width.<tt>getPathForLocation(...) </tt>in conjunction with<tt> getPathBounds(...)</tt>.
db -
Display tree node data in bold characters
Hi,
I have a requirement where I need to display tree nodes data in bold characters. If I click on a particular tree node, next time it should appear in normal font only which means that some task had done using that tree node. Is my question clear??
Plz help me....
thanks,
ravindra.Hi Ravindra,
I think it is possible, i have not done it but let me explain how we can do it.
In <htmlb:treeNode> tag there is an attribute 'text' in
which we specify title of that treeNode.
Now you define a page attribute 'treeNodeTitle' type
edpline and in onCreate assign it value <html><b>MyTreeNode</b></html>
When you click on this node then you do event handling
in onInputProcessing, there assign only 'MyTreeNode' to
treeNodeTitle.
sample code may look like this...
<htmlb:treeNode
id = 'treeNode1'
text = '<%=treeNodeTitle %>' >
</htmlb:treeNode>
Page Attribute
treeNodeTitle type edpline
in onCreate
treeNodeTitle = '<html><b>MyTreeNode</b></html>'
in onInputProcessing
in event-handling code for that treeNode write
treeNodeTitle = 'MyTreeNode'
I hope this will work.
Regards,
Narinder Hartala -
How to run a form using tree node selection??
hi...
i have populated a tree with all the form name.There is a particular id for every form.i want to show a form using tree node selection.What i did...i write a trigger in button's click event when the tree node is selected then i get a id.if id=1 then open_form('test.fmx').when i want to execute this code then it is showing the same form 2 times.Can anyone help me to solve my problem?If so plz tell me what code i have to write to show a form using node selection?.I've done the same thing, and i think it works fine.
Check this code (Sorry for the long post, but i cannot find how to attach files.
PACKAGE menu_pk IS
--Initialization of the menu.
procedure Init;
--Called from WHEN-TREE-NODE-EXPANDED
procedure Expanded;
--Called from WHEN-TREE-NODE-ACTIVATED
procedure ExecuteCommand;
END;
PACKAGE BODY menu_pk IS
MENU_NAME constant varchar2(30) := 'menu.menu';
cursor c_menu(pRoot in varchar2) is
select apm_code, apm_parcode, apm_descr, decode(apm_type, 0, Ftree.EXPANDED_NODE, Ftree.LEAF_NODE) apm_type,
decode(apm_type, 0, 'menu', 1, 'form', 2, 'report') || '.ico' apm_icon
from app_menu
where apm_parcode = pRoot
order by apm_code asc;
procedure Init is
new_node ftree.node;
begin
for i in c_menu('root')
loop
new_node := Ftree.add_tree_node(MENU_NAME, FTree.ROOT_NODE,
Ftree.PARENT_OFFSET, Ftree.LAST_CHILD,
i.apm_type, i.apm_descr, i.apm_icon, i.apm_code);
end loop;
end;
procedure FillNode(pNode in FTree.Node) is
new_node ftree.node;
begin
for i in c_menu(FTree.get_tree_node_property(MENU_NAME, pNode, FTree.NODE_VALUE))
loop
new_node := Ftree.add_tree_node(MENU_NAME, pNode,
Ftree.PARENT_OFFSET, Ftree.LAST_CHILD,
i.apm_type, i.apm_descr, i.apm_icon, i.apm_code);
end loop;
end;
procedure DeleteNodeChilds is
node FTree.NODE;
begin
loop
node := FTree.Find_Tree_Node(MENU_NAME, '',
FTree.FIND_NEXT_CHILD, FTree.NODE_VALUE,
name_in('system.trigger_node'), name_in('system.trigger_node'));
exit when Ftree.ID_NULL(node);
FTree.delete_tree_node(MENU_NAME, node);
end loop;
end;
procedure Expanded is
begin
if (FTree.GET_TREE_NODE_PROPERTY(MENU_NAME, :system.trigger_node, FTree.Node_State) = FTree.EXPANDED_NODE) then
menu_pk.FillNode(name_in('system.trigger_node'));
else
menu_pk.DeleteNodeChilds;
end if;
end;
procedure ExecuteCommand is
cursor c_command(pCode in varchar2) is
select apm_form, apm_type
from app_menu
where apm_code = pCode;
fCommand c_command%rowtype;
fMenuCode varchar2(20);
begin
-- if it is as menu node then exit.
if (not FTree.Get_Tree_Node_Property(MENU_NAME, :system.trigger_node, FTree.NODE_STATE) = FTree.LEAF_NODE) then
return;
end if;
fMenuCode := FTree.Get_Tree_Node_Property(MENU_NAME, :system.trigger_node, FTree.NODE_VALUE);
open c_command(fMenuCode);
fetch c_command into fCommand;
close c_command;
if (fCommand.apm_type = 1) and (fCommand.apm_form is not null) then
globals.Set_MenuChoice(fMenuCode);
OPEN_FORM(fCommand.apm_form);--, ACTIVATE, SESSION);
end if;
end;
END;
The menu table definition follows.
create table APP_MENU
APM_CODE VARCHAR2(10) not null,
APM_PARCODE VARCHAR2(10) not null,
APM_DESCR VARCHAR2(40) not null,
APM_TYPE NUMBER(1) not null,
APM_FORM VARCHAR2(50)
alter table APP_MENU
add constraint APP_MENU_PRI primary key (APM_CODE);
Hope this helps -
Hierarchical tree node problem
Hi all --
Today's problem is (drum roll)............
My application uses a heirarichal tree where each tree node contains the name of a form within this system. The user can navigate from form to form by clicking the appropriatetly name tree node. This seems to work - sometimes. Some users click on a node for one form, but get transferred to another named form(usually the one above or below the one actually activated). I've also found out that this happens ONLY when the user has their screen resolution set to 800 x 600. This application was developed at screen resolution 1024 x 768 and it woks fine. Anybody know why??Here is the code for both the tree node selected and tree node activated triggers
Tree Node Seleceted code:
:CONTROL.Node_Activated := null ;
:CONTROL.Node_Selected := Ftree.Get_Tree_Node_Property('CONTROL_TREE.MENU', :SYSTEM.TRIGGER_NODE, Ftree.NODE_VALUE) ;
===========================================================
Tree Node Activated code:
Declare
LN$I Pls_integer ;
Begin
:CONTROL.Node_Selected := null;
:CONTROL.Node_Activated := Ftree.Get_Tree_Node_Property('CONTROL_TREE.MENU', :SYSTEM.TRIGGER_NODE, Ftree.NODE_VALUE) ;
If :CONTROL.Node_Activated IS NOT NULL Then
if :GLOBAL.curr_proc_id <> :control.node_activated or :control.node_activated
is null then
CALL_FORM(:CONTROL.Node_Activated);
else
Set_Alert_Property( 'AL_FORM_OPENED', ALERT_MESSAGE_TEXT,
:CONTROL.Node_Activated || ' is already opened. Please check your current or previously opened library.' );
LN$I := Show_Alert( 'AL_FORM_OPENED' ) ;
end if;
end if ;
end ; -
Help for Activating Editing Mode on F2 Keyboard Click for a Tree Node
I have a Jtree with several Nodes on the Left Pane. On the Right Pane I have a nodes corresponding Screen with many properties. There is a way to change the Node Name by editing the Name Field property on the Right.
I want to Edit the tree Node name by Clicking F2 on the selected Node, Get it in the Editable Mode, Change the name and press enter. How Do I activate this editable Mode on Click of Keyboard F2 Button.tree.setEditable( true );
-
Perform a query on tree node click
This is probably very easy and I'm just having brain freeze..
I have an application that is using ColdFusion to provide
data for various controls. One control is a tree showing two levels
of data (main level shows the process/job number, then you open
that to see all the event numbers for that job). This all works
fine.
Now what I want to do is when you select an even number, flex
will use a coldfusion page I set up to perform a query on the
database using the event number and job number to get all the rest
of the data about htat particular job (description, run times, etc)
I have the click event from the tree control working fine, I
have the page in coldfusion working fine, it outputs an XML format
file with all the relevant details based on the parameters you send
it. Now the question is, how do I populate the fields on the form
with the data returned from the query?
I am using a HTTPService call to get the data to/from
ColdFusion (I have version 6.1 of Coldfusion).
Thanks for any help.Well, I answered my own question... Here is what I did in
case anyone else wants to know. If there is a better way, please
advise.
I have a click event on the tree control. Since the tree will
only be two levels deep (parent and child) I test for whether the
item clicked has a parent. If it does, I know they clicked on a
child node. I then fire off the HTTPService with the parameters
from the child and parent nodes of the tree item that was clicked.
In the result parameter of the HTTPService, I populate the
various fields using the lastresult.root.fieldname syntax of the
HTTPService.
It works as expected, but perhaps there is a better
way? -
Htmlb:tree differentiate between nodeclick and tree node expander click
Hi,
how can i differentiate between nodeclick and tree node expander (to get to its children) click in my event processing in htmlb:tree element.
<u><b>What i am trying to achieve?</b></u>
Onload just load root node and its immediate children.
On node expand get the children of the current node and modify htmlb:tree table2 with additional node inofs.
on node click call some client function.
But my issue is that i am not able to differentiate between node expander click and node click in my event handling. Any help on this is appreciated.
(I am not using MVC)
Thanks in advance.
Regards
Raja
Message was edited by: Durairaj Athavan RajaAfter reading your weblog I think I understand better. I did some testing with my example. I am using the toggle = "true", so that the page returns to the server each time an expander is selected.
<htmlb:tree id = "myTree1"
height = "75%"
toggle = "true"
title = "<b><otr>EQI Reporting Tree</otr></b>"
width = "90%"
onTreeClick = "myTreeClick"
table = "<%= application->selection_model->itview %>" >
</htmlb:tree>
However I have not added any coding in my event handler to respond to the expander event. I only respond to myTreeClick (which loads some data for the given selection). The BSP tree element itself must be doing the hard work for me.
if event_id cs 'tr_myTree1'.
data: tree_event type ref to cl_htmlb_event_tree.
tree_event ?= htmlb_event.
if tree_event->server_event = 'myTreeClick'.
clear appl->message1.
appl->selection_model->get_chart_data( appl = appl
node = tree_event->node ).
endif.
endif.
I pass my entire tree defintion to the element. It appears that it only sends visible nodes to be rendered. When the expander is selected, I don't have to do anything, the tree re-renders with only the newly visible rows.
I tested and turned off the toggle (toggle = "false") and my page took forever to load because it was sending all the nodes to the frontend on the first load. -
Confirmation Dialog when clicking on Tree Node.
I am working on Oracle Apex 4.2.0.00.27 and I have the following problem:
The code below shows the definition of a tree. The tree displays records from the table ACTIVITIES in hierarchical structure.
When user clicks on a leaf/node of the tree he will be redirected to another page where the details of each Activity/leaf/node are displayed.
The tree is part of a page where I have established a functionality to check for changes on the input fields of the page and inform the user when he tries to redirect without first saving the changes he made.
What I want to do is:
WHEN user clicks on a node of the tree AND he hasn't saved any changes he made
THEN
trigger a confirmation dialog.
IF
he clicks OK he is redirected to the node details page as defined on the tree definition:
f?p=&APP_ID.:10:'||:APP_SESSION||'::::P10_ID:'||"ID"
ELSE if he clicks CANCEL
he stays on the same page.
The condition to trigger the confirmation box is:
if (document.getElementById('P0_CHANGES_DETECTED').value == 1)
where P0_CHANGES_DETECTED is a universal hidden text field that is set to +'1'+ every time a change is made.
and here is the tree definition:
select case when connect_by_isleaf = 1 then 0
when level = 1 then 1
else -1
end as status,
level,
+"NAME" as title,+
null as icon,
+"ID" as value,+
null as tooltip,
decode(PARENT_ID,null,null, 'f?p=&APP_ID.:10:'||:APP_SESSION||'::::P10_ID:'||"ID") as link
from "#OWNER#"."ACTIVITIES"
where GROUP_ID = :P20_GROUP_ID
start with "ID" in (select ID from "#OWNER#"."ACTIVITIES" where GROUP_ID = :P20_GROUP_ID and PARENT_ID is null)
connect by prior "ID" = "PARENT_ID"
order siblings by "ID"
I hope it is clear what I want to achieve. Thanks in advance.So you'll want to bind an event to all tree nodes that checks for the value and then fires the confirmation if there value is 1.
Try something like this:
- first, give your static ID attribute in your tree the value of tree_static_id (or whatever you want. just replace the id selector below with what you choose).
- In your Page Function and Variable Declaration Javascript:
function confirmSave() {
var changeDetected = jQuery('#P0_CHANGES_DETECTED').val();
if(changeDetected == 1) {
//only do this if change is detected
if(confirm('You have unsaved changes. Do you want to leave this page?')) {
window.location('[your url here]');
jQuery(document).ready(function() {
//bind function to the click event
$('#tree_static_id').find('li a').bind('click', function() { confirmSave(); } });
});Hope this helps -
Context Menu on the right click of af:tree node
Hi Experts,
I am using drag and drop functionality in af:tree.In that i used one tree for drag source and another one tree for drop target,and it is working as expected.
Now I want to bring one additional option in the context menu of the target tree node that is ,when i right click on any of the target tree node in addition to the default menu options like "Collapse","Expand" i want to add one more option .For this i added "contextMenu" facet after the "nodeStamp" facet inside the tree.
*<f:facet name="contextMenu">*
*<af:popup id="p1">*
*<af:menu text="Delete" id="m1">*
*<af:commandMenuItem text="Delete" id="cmi1"*
*action="#{myWorkflow.deleteWorkflowNode}"/>*
*</af:menu>*
*</af:popup>*
*</f:facet*>
Now the problem is : before using drag and drop the context menu workes without any problem .But after using drag and drop the context menu is not popped up.
can anybody help me to resolve this?
Thanks,
Priya.Hi Frank,
1. I am using JDeveloper 11.1.1.3 version
2. Drop target tree is having the context menu.
3. Yes . In Drop event am calling a backing bean method with return type DnDAction and i return the value as DnDAction.MOVE to reflect the changes in the database table to the target tree.
Regards,
Priya. -
Displaying data in tableview on click of a tree node
Hi,
I am new to BSP. I created a tree structure having the tablenames as tree nodes, and now if I click on a node I want to display corresponding table data in a tableview. How can I acheive this....??
Thanks in advance,
Ravindra.Hi Ravindra,
You can achieve this by reading the node clicked OnInput Processing and You can assign name of your table in "onNodeClick" attribute .
then onInputprocessing you can read the name of your table from
"event->server_event" .
Check this sample code .
****************OnLayout*******************************
<htmlb:content design="design2003">
<htmlb:page title = " ">
<htmlb:form>
<htmlb:tree id = "myTree1"
title = "Tree"
tooltip = "Tooltip for myTree1">
<htmlb:treeNode id="NODE1" text="TABLE1" isOpen="true" onNodeClick="TABLE1">
</htmlb:treeNode>
<htmlb:treeNode id="NODE2" text="TABLE2" isOpen="true" onNodeClick="TABLE2">
</htmlb:treeNode>
<htmlb:treeNode id="NODE3" text="TABLE3" onNodeClick="TABLE3"/>
<htmlb:treeNode id="NODE4" text="TABLE4"onNodeClick="TABLE4" />
<htmlb:treeNode id="NODE5" text="TABLE5" isOpen="false" onNodeClick="TABLE5">
</htmlb:treeNode>
<htmlb:treeNode id="NODE6" text="TABLE6" onNodeClick="TABLE6"/>
</htmlb:tree>
</htmlb:form>
</htmlb:page>
</htmlb:content>
*****************OnInputProcessing****************
CLASS CL_HTMLB_MANAGER DEFINITION LOAD.
Data: TABLE_NAME type STRING.
Optional: test that this is an event from HTMLB library.
IF event_id = CL_HTMLB_MANAGER=>EVENT_ID.
Scenario 1: Read event from manager.
DATA: event TYPE REF TO CL_HTMLB_EVENT.
event = CL_HTMLB_MANAGER=>get_event( runtime->server->request ).
IF event IS NOT INITIAL AND event->name = 'tree'.
DATA: tree_event TYPE REF TO CL_HTMLB_EVENT_TREE.
tree_event ?= event.
TABLE_NAME = event->server_event.
ENDIF.
ENDIF.
Check examples given in "SBSPEXT_HTMLB" bsp application.
I hope this will help.
Regards,
Monica -
When generate automatically a JTable after a click on a tree node
final int x[] = {0, 1, 2, 22, 0, 2, 0, 1, 0, 2};
final int y[] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3};
final int larg[] = {1, 1, 20, 1, 2, 21, 1, 22, 2, 22};
final int haut[] = {1, 1, 1, 1, 1, 1, 1, 1, 22, 22};
final int px[] = {5, 5, 85, 5, 0, 0, 0, 0, 0, 0};
final int py[] = {2, 0, 0, 0, 2, 0, 2, 0, 94, 0};
//****************** POSITIONNEMENT DES COMPOSANTS
final Container conteneur = getContentPane();
final GridBagLayout gridBg = new GridBagLayout();
conteneur.setLayout(gridBg);
final GridBagConstraints contrainte = new GridBagConstraints();
contrainte.fill = contrainte.BOTH;
//*********** JCOMBO1 **************
borneDate1 = new JComboBox();
Calendrier req = new Calendrier();
String[] valCal = req.lireDansTable();
borneDate1.addItem("");
for (int i = 0; i<= valCal.length - 1; i++){
borneDate1.addItem(valCal);
contrainte.gridx = x[0];
contrainte.gridy = y[0];
contrainte.gridwidth = larg[0];
contrainte.gridheight = haut[0];
contrainte.weightx = px[0];
contrainte.weighty = py[0];
contrainte.insets = new Insets(1, 1, 1, 1);
contrainte.ipadx = 20;
gridBg.setConstraints(borneDate1, contrainte);
conteneur.add(borneDate1);
//*********** JCOMBO2 **************
borneDate2 = new JComboBox();
req = new Calendrier();
valCal = req.lireDansTable();
borneDate2.addItem("");
for (int i = 0; i<= valCal.length - 1; i++){
borneDate2.addItem(valCal[i]);
contrainte.gridx = x[1];
contrainte.gridy = y[1];
contrainte.gridwidth = larg[1];
contrainte.gridheight = haut[1];
contrainte.weightx = px[1];
contrainte.weighty = py[1];
gridBg.setConstraints(borneDate2, contrainte);
conteneur.add(borneDate2);
//*********** JLABEL1 **************
lbl1 = new JLabel(" Dates de S�lection.");
contrainte.gridx = x[2];
contrainte.gridy = y[2];
contrainte.gridwidth = larg[2];
contrainte.gridheight = haut[2];
contrainte.weightx = px[2];
contrainte.weighty = py[2];
gridBg.setConstraints(lbl1, contrainte);
conteneur.add(lbl1);
//*********** BOUTON IMPRIMER **************
btmImprimer = new JButton("IMPRIMER");
contrainte.gridx = x[3];
contrainte.gridy = y[3];
contrainte.gridwidth = larg[3];
contrainte.gridheight = haut[3];
contrainte.weightx = px[3];
contrainte.weighty = py[3];
gridBg.setConstraints(btmImprimer, contrainte);
conteneur.add(btmImprimer);
//*********** BOUTON AUJOURD'HUI **************
btmAujourdhui = new JButton("Ce jour");
contrainte.gridx = x[4];
contrainte.gridy = y[4];
contrainte.gridwidth = larg[4];
contrainte.gridheight = haut[4];
contrainte.weightx = px[4];
contrainte.weighty = py[4];
gridBg.setConstraints(btmAujourdhui, contrainte);
conteneur.add(btmAujourdhui);
//*********** JLABEL 2 **************
lbl2 = new JLabel(" Journal.");
//lbl2.setVisible(false);
contrainte.gridx = x[5];
contrainte.gridy = y[5];
contrainte.gridwidth = larg[5];
contrainte.gridheight = haut[5];
contrainte.weightx = px[5];
contrainte.weighty = py[5];
gridBg.setConstraints(lbl2, contrainte);
conteneur.add(lbl2);
//*********** JLABEL 3 **************
lbl3 = new JLabel(" Adresse ");
contrainte.gridx = x[6];
contrainte.gridy = y[6];
contrainte.gridwidth = larg[6];
contrainte.gridheight = haut[6];
contrainte.weightx = px[6];
contrainte.weighty = py[6];
gridBg.setConstraints(lbl3, contrainte);
conteneur.add(lbl3);
//*********** JTEXTFIELD **************
txtPath = new JTextField();
contrainte.gridx = x[7];
contrainte.gridy = y[7];
contrainte.gridwidth = larg[7];
contrainte.gridheight = haut[7];
contrainte.weightx = px[7];
contrainte.weighty = py[7];
gridBg.setConstraints(txtPath, contrainte);
conteneur.add(txtPath);
//*********** JTREE **************
DefaultMutableTreeNode racine = new DefaultMutableTreeNode("MEDIACAST");
//**********RECUPERER LES LIGNES ANIMATEUR*******
parentNode = new DefaultMutableTreeNode("ANIMATEURS");
racine.add(parentNode);
GenererEnregistrement enregAnimateur = new GenererEnregistrement();
String[] sEnregAnim = enregAnimateur.lireDansTable("SELECT numero_anim FROM animateur ORDER BY numero_anim", "numero_anim");
for(int i = 0; i <= sEnregAnim.length - 1; i++){
fils = new DefaultMutableTreeNode(sEnregAnim[i]);
parentNode.add(fils);
//************RECUPERER LES LIGNES COMPTE******************
parentNode = new DefaultMutableTreeNode("COMPTES");
racine.add(parentNode);
GenererEnregistrement enregCompte = new GenererEnregistrement();
String[] sEnregCompte = enregCompte.lireDansTable("SELECT id_compte FROM compte ORDER BY id_compte", "id_compte");
for(int i = 0; i <= sEnregCompte.length - 1; i++){
fils = new DefaultMutableTreeNode(sEnregCompte[i]);
parentNode.add(fils);
//************RECUPERER LES LIGNES DATE******************
parentNode = new DefaultMutableTreeNode("DATES");
racine.add(parentNode);
GenererEnregistrement enregDate = new GenererEnregistrement();
String[] sEnregDate = enregDate.lireDansTable("SELECT daty FROM calendrier ORDER BY numero_enreg", "daty");
for(int i = 0; i <= sEnregDate.length - 1; i++){
fils = new DefaultMutableTreeNode(sEnregDate[i]);
parentNode.add(fils);
//*************AFFICHAGE******************
TreeNode root = racine;
arbre = new JTree(root);
JScrollPane paneTree = new JScrollPane();
//**********EVENEMENT CLICK DROIT DANS JTREE***************
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = arbre.getRowForLocation(e.getX(), e.getY());
TreePath selPath = arbre.getPathForRow(selRow);
if(selRow != -1) {
if(e.getButton() == 1) {
txtPath.setText(selPath.toString());
//**-> CREER LE VECTEUR POUR JTable**<-
String sPere = txtPath.getText();
int iResComp = sPere.compareTo("[MEDIACAST, ANIMATEURS]" + arbre.getLastSelectedPathComponent().toString() + "]");
//****ANIMATEURS***************
switch(iResComp){
case -49:
String sReq = "SELECT animateur.matricule, animateur.prenom, calendrier.daty, compte.id_compte";
sReq = sReq + " " + "FROM animateur, liaison";
sReq = sReq + " " + "WHERE animateur.numero_anim = ? AND liaison.numero_anim = ? AND calendrier.daty = liaison.daty";
String[] sParamIn = {
arbre.getLastSelectedPathComponent().toString(), arbre.getLastSelectedPathComponent().toString()
String[] sTypeParamIn = {
"entier", "entier"
String[] sParamOut = {
"matricule", "prenom", "daty", "id_compte"
GenererEnregistrement enreg = new GenererEnregistrement();
objEnreg = enreg.retournerToutEnreg(sReq, sParamIn, sTypeParamIn, sParamOut);
iNbEnreg = enreg.donnerNbEnreg(sReq, sParamIn, sTypeParamIn, sParamOut);
Object[] teteTable = {
"Matricule","Prenom","Date", "Numero Compte"
data = clickTreeNode(teteTable.length, iNbEnreg, sParamOut.length, objEnreg);
tableau = new JTable(data);
//*********** JTABLE **************
JScrollPane paneTab = new JScrollPane(tableau);
contrainte.gridx = x[9];
contrainte.gridy = y[9];
contrainte.gridwidth = larg[9];
contrainte.gridheight = haut[9];
contrainte.weightx = px[9];
contrainte.weighty = py[9];
gridBg.setConstraints(paneTab, contrainte);
conteneur.add(paneTab);
break;
else if(e.getButton() == 3) {
arbre.setSelectionPath(selPath);//Donne le focus au noeud click�
txtPath.setText(selPath.toString());
//***********POUR LES NOEUDS PERES*******************************
if(arbre.getLastSelectedPathComponent().toString() == "ANIMATEURS"){
System.out.println(selPath.getParentPath().toString());
//***********POUR LES NOEUDS FILS********************************
String sPere = txtPath.getText();
int iResComp = sPere.compareTo("[MEDIACAST, ANIMATEURS]" + arbre.getLastSelectedPathComponent().toString() + "]");
switch(iResComp){
case -49:
System.out.println("NOEUDS DANS ANIMATEURS:" + iResComp + " " + arbre.getLastSelectedPathComponent().toString());
break;
case 2:
if(arbre.getLastSelectedPathComponent().toString() != "COMPTES")
System.out.println("NOEUDS DANS COMPTES:" iResComp " " + arbre.getLastSelectedPathComponent().toString());
break;
case 3:
if(arbre.getLastSelectedPathComponent().toString() != "DATES")
System.out.println("NOEUDS DANS DATES:" + iResComp + " " + arbre.getLastSelectedPathComponent().toString());
break;
arbre.addMouseListener(ml);
paneTree.setViewportView(arbre);
contrainte.gridx = x[8];
contrainte.gridy = y[8];
contrainte.gridwidth = larg[8];
contrainte.gridheight = haut[8];
contrainte.weightx = px[8];
contrainte.weighty = py[8];
gridBg.setConstraints(paneTree, contrainte);
conteneur.add(paneTree);
//Afficher la fen�tre
ImageIcon ico = new ImageIcon("c:\\works\\mediacast\\gpao\\hlpglobe.gif");
this.setIconImage(ico.getImage());
//this.pack();
this.setVisible(true);
I want to generate automatically a table after a click on a tree node but I don't know when to procedePlease do the following.<br><br>
#In the location bar, type '''about:config''' and hit Enter.<br><br>
#In the filter at the top, type: '''keyword.URL'''<br><br>
#Double click it and remove whatever's in there and replace it with http://www.google.com/search?q= and then click OK.<br><br>
#Close the tab
The URL to add in "keyword.URL" becomes a link in this post, so right click it and choose "Copy Link Location" to copy it to the Windows clipboard. Then hit CTRL+V to paste it. Saves you having to type the whole thing.
'''To reset your home page, do the following'''.<br><br>
* Go to the site you want to set as your homepage.<br><br>
* Click the Firefox button, go to '''Options '''| '''Options '''| '''General'''.<br><br>
* Make sure it says "''Show My Homepage''" in the first dropdown menu.<br><br>
* Click the button called "'''Use Current Pages'''" to set the homepage to the one you have on the screen.<br>
N.B. Some of your plugins are out of date which exposes your system to attack. Please visit the [http://www.mozilla.com/en-US/plugincheck/ Plugins Check] page and update where necessary.
Also, click '''Help '''| '''Check For Updates''' to update Firefox to 3.6.19 -
Hello all,
I need to process right click on the tree node. I can get the node and process the action well. But the problem is that the selected node doesn't have a gray box (selection indicator) like when I left click it.
Please help me with this,
Thanks,
FantabkDear Siva,
You can follow the following steps:-
- Create local class (eg:- lcl_screen_handler) as handler class.
- Define and implement methods handle_node_context_menu_req and handle_node_context_menu_sel for handling right click.
- In Method handle_node_context_menu_req use CALL METHOD menu->add_function for adding entries to context menu.
- In Method handle_node_context_menu_sel based on node_key and fcode handle logic for right click.
- Define event handler (eg:- grc_event_handler TYPE REF TO lcl_screen_handler) to handle events for right click on tree.
- After creating Tree, specify events that are to be handled and assign them to tree instance
eg:- lwa_event-eventid = cl_simple_tree_model=>eventid_node_double_click.
lwa_event-appl_event = ' '. "system event, does not trigger PAI
APPEND lwa_event TO lit_event. (where, lit_event TYPE cntl_simple_events)
- Also, register PAI for context menu as follows:-
Process PAI if context menu select event occurs
CALL METHOD grc_tree->set_ctx_menu_select_event_appl (where grc_tree is Tree instance)
EXPORTING
appl_event = 'X'.
- Register Tree events as follows:-
CALL METHOD grc_tree->set_registered_events
EXPORTING
events = lit_event ....
- Create event handler instance for tree
CREATE OBJECT grc_event_handler. (where, grc_event_handler is already declared on top)
- Set event handler method to handle various events on tree node
eg:- SET HANDLER grc_event_handler->handle_node_double_click FOR grc_tree.
SET HANDLER grc_event_handler->handle_node_context_menu_req FOR grc_tree.
SET HANDLER grc_event_handler->handle_node_context_menu_sel FOR grc_tree.
The events should be handled now. I have followed this approach and it worked for me.
Regards,
Ashish
Maybe you are looking for
-
Aperture slideshow is terrible in terms of entering any text on a photo. It appears that you have to export the photos from Aperture to the desktop to import the photos to iMovie to be able to add quite good text to individual photos. While I am new
-
in bdc we have to save the flat file in desktop or c drive?plz tell Edited by: Alvaro Tejada Galindo on Feb 7, 2008 10:15 AM
-
Sync my iCal in between iPhone and Outlook 2010 on Win7
Hi, I have an iPhone4 running iOS5.1.1 (as of today) and an iCloud account. My iPhone calendar (iCal) is synched with iCloud calendar. My business PC is running Win7 and Outlook 2010. My compagny has selected Google Enterprise to provide all the mail
-
[KDE 4.10] Kontact/Kalender/KMail issue
Hello together! I have recently updated to KDE 4.10, which looks very good. Unfortunately, the above mentioned parts of KDE have stoped to work. I use Kontact for organising my mails, calender and RSS-feeds. The RSS programm (akregator) still works a
-
Hi, I have LabView7.1 and Labview8.0 installed in my pc.Recently i installed Report generation tool kit(version 1.0.1.0) In the functions palette i couldnt able to see the Excel Specific VI sub palette and Word Specific VI sub palette. Can u tell me