Using getContentPane() in JFrame class

Hello,
I'm reading Bruce Eckel's book.
In chaapter 14, I read TextArea.java.
My question is:
What is the purpose of getContentPane() in the constructor TextArea() in the code below ?
Isn't JFrame IS a Container ? why bother to get another Container ?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;
public class TextArea extends JFrame {
private JButton
b = new JButton("Add Data"),
c = new JButton("Clear Data");
private JTextArea t = new JTextArea(20, 40);
private Map m = new HashMap();
public TextArea() {
// Use up all the data:
Collections2.fill(m, Collections2.geography,
CountryCapitals.pairs.length);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Iterator it = m.entrySet().iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)(it.next());
t.append(me.getKey() + ": "+ me.getValue()+"\n");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t.setText("");
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JScrollPane(t));
cp.add(b);
cp.add(c);
public static void main(String[] args) {
Consoleb.run(new TextArea(), 475, 425);
}

I appreciate the reply.
There are endless API to read.
I found this:
For conveniance JFrame, JDialog, JWindow, JApplet and
JInternalFrame, by default, forward, by default, all
calls to the add, remove and setLayout methods, to
the contentPane. This means you can call:
rootPaneContainer.add(component);That was introduced in 1.5. May people still use older versions of Java, so use that add method with caution. I myself see no reason to use it, since it is a bit of a hack.
Another question on the side:
How can I remove a topic that I created ?Like karma, no thread ever goes away :-)

Similar Messages

  • Beginner question - How to use JFrame class?

    How can we use a JFrame class created? Shld you run it like JApplet on browser or appletviewer?

    First, if I understand what you want to do exactly, you need to write two classes. The main one will be your class that extends javax.swing.JFrame. Wherehas the second will be your "container class" and will extends java.applet.Applet. This second class will do nothing more than instantiate your JFrame subclass. This is this last class that will be called in your HTML file.
    I made up some code quickly to give you an idea:
    import javax.swing.JFrame;
    public class TestJFrame extends JFrame {
    //Constructor
    public TestJFrame() {
    super("My test JFrame"); //calls the superclass constructor
    this.setSize(200,200);
    this.setVisible(true);
    // Main (optionnal here: just in case you need to
    // instantiate the class within an application)
    public static void main(String[] args) {
    new TestJFrame();
    =======================
    import java.applet.Applet;
    public class TestJFrameApplet extends Applet {
    public void init() {
    new TestJFrame();
    Hope this help

  • Problem with setContentPane() in JFrame class

    I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
    I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.

    I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
    Here is the method I use to switch screens in my app:
    public static void changeScreen (JPanel panel){
              try{
                   appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
                   appFrame.setContentPane(panel);
                   appFrame.setSize(appFrame.getContentPane().getPreferredSize());     
                   appFrame.getContentPane().setBackground(backColour);
                   for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
                        appFrame.getContentPane().getComponents().setForeground(textColour);
                   //System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
                   appFrame.validate();
              catch (Exception e){
                   //System.out.println("change");
                   e.printStackTrace();
    And it is called like this:
    changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it.

  • JSplitPane in JFrame class

    Hi all,
    Sorry about the newbie question. I'm trying to place a split pane into a JFrame, but I'm not entirely clear how to implement it. The code is below. Ideally, I'd have one ImageJPanel on the left-hand side, to be populated with a BufferedImage, and one on the right, to be populated with a graphical representation of some data from that image (specifically RGB and HSV histograms). However, I'm just having trouble displaying the JSplitPane, although, admittedly, I don't know much about it. Any advice is appreciated. Thanks!
    Joe
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.awt.image.*;
    public class ImFrame extends JFrame implements ActionListener {
        ImageJPanel imgPanel = new ImageJPanel();
        ImageJPanel leftPanel = new ImageJPanel();
        ImageJPanel rightPanel = new ImageJPanel();
        JScrollPane imageScrollPane = new JScrollPane();
        JScrollPane leftPane = new JScrollPane();
        JScrollPane rightPane = new JScrollPane();
        private JSplitPane split;
        public ImFrame(){
            super("Image Display Frame");
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
            JMenu fileMenu = new JMenu("File");
            fileMenu.add(makeMenuItem("Open"));
            fileMenu.add(makeMenuItem("Save Analysis Data"));
            fileMenu.add(makeMenuItem("Quit"));
            JMenu analyzeMenu = new JMenu("Analyze");
            analyzeMenu.add(makeMenuItem("Smooth"));
            analyzeMenu.add(makeMenuItem("Display RGB and HSV"));
            analyzeMenu.add(makeMenuItem("Display Second Image for Comparison"));
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(fileMenu);
            menuBar.add(analyzeMenu);
            setJMenuBar(menuBar);
            split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                    leftPanel, rightPanel);
            split.setDividerLocation(150);
            split.setSize(300, 300);
            split.setRightComponent(rightPane);
            split.setLeftComponent(leftPane);
            setContentPane(split);
            setSize(300, 300);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                .addComponent(imageScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(imageScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
            imageScrollPane.setViewportView(imgPanel);
            pack();
            //setVisible(true);
        public void actionPerformed(ActionEvent e){
            String command = e.getActionCommand();
            if(command.equals("Quit")) System.exit(0);
            else if (command.equals("Open")) loadFile();
        private void loadFile(){
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(this);
            if (result == JFileChooser.CANCEL_OPTION) return;
            try{
                File file = chooser.getSelectedFile();
                System.out.println("Loading..." + file.getAbsolutePath());
                BufferedImage buffImage = ImageIO.read(file);
                if (buffImage != null) {
                leftPanel.setImage(buffImage);
                imageScrollPane.setViewportView(leftPanel);
                } else {
                    System.out.println("Problem loading image file.");
            } catch(Exception e){
                System.out.println("File error:" + e);
        private JMenuItem makeMenuItem(String name){
            JMenuItem m = new JMenuItem(name);
            m.addActionListener(this);
            return m;
        public static void main(String[] s){
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ImFrame().setVisible(true);
    }

    split.setDividerLocation(150); // only works once the GUI is visible
    split.setSize(300, 300);Don't use setSize() it has no effect when using a layout manager
    split.setRightComponent(rightPane);
    split.setLeftComponent(leftPane);You are adding an ImagePanel. Presumably ImagePanel extends JPanel. I don't know what you code is like but I'm guessing that you are doing custom painting. When you do custom painting the panel does not have a preferred size (unless you specifically set it). So when you do a pack(), the preferred size of each panel is (0, 0) and therefore the preferred size of the split pane is (0, 0) plus the divideer size, so you frame is really small.
    setContentPane(split);Just use getContentPane().add(split);
    setSize(300, 300);Has no effect since the pack method will recalculate the preferred size as described above.
    Here is a simple example:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SplitPaneBasic extends JFrame
         JSplitPane splitPane;
         public SplitPaneBasic()
              JPanel red = new JPanel();
              red.setBackground( Color.RED );
              red.setPreferredSize( new Dimension(100, 100) );
    //          red.setMinimumSize( new Dimension(0, 0) );
              JPanel blue = new JPanel();
              blue.setBackground( Color.BLUE );
              blue.setPreferredSize( new Dimension(100, 100) );
              splitPane = new JSplitPane();
              splitPane.setOneTouchExpandable(true);
              splitPane.setLeftComponent( red );
              splitPane.setRightComponent( blue );
    //          splitPane.setDividerLocation(1.0);
    //          splitPane.setResizeWeight(0.5);
              getContentPane().add(splitPane, BorderLayout.CENTER);
              splitPane.setDividerLocation(1.0);
         public static void main(String[] args)
              SplitPaneBasic frame = new SplitPaneBasic();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.splitPane.setDividerLocation(0.75);
              frame.setVisible(true);
    //          frame.splitPane.setDividerLocation(1.0);
    }

  • Problem with JFrame class.

    To risolve my problem i need for few diferent frame
    ( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
    If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
    I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
    Help me.....

    Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.

  • Doubt in processing of  statements after calling JFrame class

    I have two java classes.
    The first one is Normal class and the second one is a JFrame class.
    In the first Class, i created an object for second JFrame class followed by a set of statements.
    Based on the input from the second class, i must process the statements, the problem i am facing is after creating the object for second frame class , the first class continues execution of the remaining statements. I must stop the execution of the statements until i get an input from the second class.
    How can i make the first class wait for an input from the second class.
    if possible provide me some source code.
    Thanks for your help!.

    Use a modal JDialog instead of a JFrame.
    db

  • Creating a java thread in a jframe class?

    hello is this possible to create a thread for a jframe class? so that everytime a connection is established, a new thread along with the gui is opened automaticly? if so, would i just need to insert extends Thread on my declaration of my class?
    i already have this code at the top of my jframe class..
    public class ChatDialog extends javax.swing.JFrame implements WindowListenerwhere and how would i implement the run() method in thsi class?
    full code:
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog extends javax.swing.JFrame implements WindowListener {
        protected String messege;
        private Socket client_user = null;
        /** Creates new form ChatDialog */
        public ChatDialog()
            initComponents();
            addWindowListener( this );
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            convo_txt = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            txt_messege = new javax.swing.JTextArea();
            send_button = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            Option = new javax.swing.JMenu();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            jScrollPane1.setViewportView(convo_txt);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 270));
            jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            txt_messege.setLineWrap(true);
            jScrollPane2.setViewportView(txt_messege);
            getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 310, 220, 70));
            send_button.setText("Send");
            send_button.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    send_buttonActionPerformed(evt);
            getContentPane().add(send_button, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 390, -1, -1));
            jMenu1.setText("File");
            jMenuBar1.add(jMenu1);
            Option.setText("Option");
            jMenuBar1.add(Option);
            setJMenuBar(jMenuBar1);
            pack();
        // </editor-fold>
        private void send_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            //get txt from textbox   
            String text = txt_messege.getText();
        public void windowClosing(WindowEvent e)
            public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
          public void windowOpened(WindowEvent e)
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ChatDialog().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JMenu Option;
        private javax.swing.JTextArea convo_txt;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JButton send_button;
        private javax.swing.JTextArea txt_messege;
        // End of variables declaration
    }

    Instead of attempting to have the frame extend thread (or implement Runnable which is actually possible since you cannot have multiple inferitance). You might want to just create the frame and have that frame lauch an associated thread to take care of the processing required.

  • Limiting the parameter used in constructing a class

    I would like to create a Class, where the name parameter used when constructing the Class can only be 1 of 5 different names. I was thinking about saving these "usable" names as final Strings in some interface that all my classes implement. I was wondering if there was an easy way of doing this, since I know there are Java Classes that have this feature...or do they just use brute force, testing the inputted String against what is legitimate with a for loop or something?

    I would like to add one more thing, and perhaps somebody knows the answer.
    In the Java Swing classes, the setDefaultCloseOperation(int) method of a JFrame asks for an (int) parameter. If you enter 10, the program will compile, but when you execute it it will throw an exception. So obviously if I wanted to mimic this way of writing a program I would make ChessPiece(String) and not ChessPiece(AllowableName), so that the program compiles. But then what do I do to make it throw an exception for not being an AllowableName and just any old String. My curiosity is killing me. It just seems that for my program I have to write
    class ChessPiece(AllowableName)
    {}for me to use the
    ChessPiece Rook = new ChessPiece(AllowableName.Rook);format.
    but if I did that
    ChessPiece Rook = new ChessPiece("Rook");wouldn't even compile, and if it was truly like the Swing API, it should.

  • Why we extends JFrame class in java

    Hello Java Developers,
    I am new to Java & Currently I am trying my hands on Java Swings.
    I wrote a very simple program in Java to display a JFrame on screen. My code is as follows:
    import javax.swing.*;
    public class JavaFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    I saw some examples on internet & they are extending "JFrame" in their every example. I want to know what is the benefit of this ??? here is code:
    import javax.swing.*;
    public class JavaFrame extends JFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    My second question is what is the meaning of line "frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);"
    frame - This object of class created by me.
    setDefaultCloseOperation() - This is predefined method in JFrame class.
    JFrame.EXIT_ON_CLOSE - what is the meaning of this ??

    I saw in JFrame API as you suggested & I found that
    EXIT_ON_CLOSE is an "public static final" method.Look again. It's not a method.
    final: this mehod must be executed
    am I right ???No. final means that the value cannot be reassigned.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • Using Timer and TimerTask classes in EJB's(J2EE)

    Does J2EE allow us to use Timer and TimerTask classes from java.util package in SessionBean EJB's ( Statless or Statefull )?.
    If J2EE does allow, I am not sure how things work in practical, Lets take simple example where a stateless SessionBean creates a Timer class
    and schedules a task to be executed after 5 hours and returns. Assuming
    GC kicks in many times in 5 hours, I wonder if the Timer object created by survives the GC run's so that it can execute the scheduled tasks.
    My gut feeling says that the Timer Object will not survive.. Just
    want to confirm that.
    I will be interested to know If there are any techiniques that can make
    the usage of Timer and TimeTask classes in EJB's possible as well as reliable with minmum impact on over all performance.

    Have a look at J2EE 1.4. I think they add a timer service for EJBs there...
    Kai

  • Error in using TCPIP/Inst​r class to open a VISA session

    I use the TCPIP/Instr class session to open a VISA session to Agilent 86140B Optical spectrum Analyser and I get an Error - VISA open in Appln.vi.Help me to fix this problem.
    I am able to access the instrument on LAN through a Telnet session.
    Vijayalakshmi.
    Attachments:
    OSA_Close.vi ‏28 KB
    OSA_Reset.vi ‏27 KB
    OSA_Initialize.vi ‏63 KB

    Thanx for the reply.The instrument is VXI-11 compliant.The error I am getting is Instrument timeout -1073807339 (BFFF0015) and I am using LabVIEW on Linux.
    I have another problem.I am able to see the instrument using a Telnet session but not using http//192.168.10.2 on a web browser.It is giving an error that the host may be down and try some time later.

  • Facing problem to Use a custom Java class in UCCX

    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-priority:99;
    mso-style-qformat:yes;
    mso-style-parent:"";
    mso-padding-alt:0in 5.4pt 0in 5.4pt;
    mso-para-margin-top:0in;
    mso-para-margin-right:0in;
    mso-para-margin-bottom:10.0pt;
    mso-para-margin-left:0in;
    line-height:115%;
    mso-pagination:widow-orphan;
    font-size:11.0pt;
    font-family:"Calibri","sans-serif";
    mso-ascii-font-family:Calibri;
    mso-ascii-theme-font:minor-latin;
    mso-hansi-font-family:Calibri;
    mso-hansi-theme-font:minor-latin;}
    Hi,
    We are using Communication manager 7.0.1 and UCCX version 7.0.1(Cisco Unified CCX Premium).  We are trying to call a Custom Java class file from UCCX scripting. We have followed the steps mentioned in the guide (How-To: Using a custom Java class in UCCX 5.x (SOAP Example)). See below link.
    http://www.avholloway.com/vtools/ipcc/custom-java/soap/
    After completed all the steps we have got the variable type SimpleSOAP at script but we did not found it to object constructors or object attributes (plz find the attached screenshots). We will appreciate if you plz guide us to solve the issue.
    Thanks
    Fakhrul
    LEADS Corporation Ltd.

    Hello, Fakhrul.
    I'm sorry to see you were not able to find the information or help you were looking for here in the Contact Center community forum.
    You may be able to find more help through the Cisco Developer Network.
    Also, you might want to consider engaging Cisco Advanced Services via your account team to assist with UCCX custom scripting.
    Thank you, and good luck.
    -Paulo

  • What are the uses of declaring a class "final"?

    Can any one please tell me the uses of declaring a class "final"?
    I know that final classes cannot be extended. Other than this,
    Is there any thing that will improve the compiler time for the final classes?

    compiler performance is utterly unimportant anyway...
    If the compiler takes too long, just get a faster build system :)

  • Code Sample: Easy RFC Lookup From XSLT Mappings Using a Java Helper Class

    Hi everyone,
    This is just a shameless plug for my article: <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/05a3d62e-0a01-0010-14bc-adc8efd4ee14">Easy RFC Lookup From XSLT Mappings Using a Java Helper Class</a>. I hope you're interested in reading it, and I welcome your comments in this thread.
    Kind regards,
    Thorsten

    Hi Stefan. Thanks for your post. I have already done that. It still does not work. As a base for my java helper class I have usesd Thorstens code.
    The problem is quite confusing. I will try to ouline both issues here.
    First of all, when try to test from within the Operation Mapping, I always get a java error saying it cannot find the communication channel (it is there and working because I have tested it with the RFCLookup in graphical mapping). I have found a way to work around this, and that is to uncheck the "Use SAP XMLToolkit" checkbox --> switch to test tab, enter my ReceiverService in the parameter tab (header parameter) --> switch back to Definition tab, check the "Use SAP XMLToolkit" checkbox --> switch to Test tab and run the test. Then the XSLT and call to java helper class will work. Of course this is not really something you want to do all the time. Maybe there is a bug.
    Secondly, it never works when I try to do it "live". I am using a file adapter to pick up one file, convert it and a file adapter to drop the converted file. I get the following error code in SXMB_MONI.
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    <!--  Request Message Mapping   -->
    <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">
      <SAP:Category>Application</SAP:Category>
      <SAP:Code area="MAPPING">TRANSFORMER_CONF_EX</SAP:Code>
      <SAP:P1>ATJ_Accounting2XML_Accounting.xsl</SAP:P1>
      <SAP:P2>http://rd.accounting.logica.com</SAP:P2>
      <SAP:P3>fd552c30-bad9-11dd-9761-c21dac1b818c</SAP:P3>
      <SAP:P4>-1</SAP:P4>
      <SAP:AdditionalText />
      <SAP:Stack>TransformerConfigurationException triggered while loading XSLT mapping ATJ_Accounting2XML_Accounting.xsl; http://rd.accounting.logica.comfd552c30-bad9-11dd-9761-c21dac1b818c-1</SAP:Stack>
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Using an XSLT without a call to a java helper class, works just fine.
    I am totally at a loss here. Any more input would be much appreciated.
    /Patrik

  • Building Tree hierarchy Using nested loops and class cl_gui_column_tree

    Hello gurus,
    I want to create a tree report using custom container and class cl_gui_column_tree. I have read and understood the standard demo report which SAP has provided i.e. SAPCOLUMN_TREE_CONTROL_DEMO. But in this report all the levels nodes are created as constants and hardcoded. I want to create hierarchy using nested loops. For this i took one example of a hierarchy of VBAK-VBELN->VBAP-POSNR Like One sales order has many line items and each line item can have number of line items in billing plan.
    I have done some coding for it.
    FORM build_tree USING node_table TYPE treev_ntab
                                           item_table TYPE zitem_table.              " i created the zitem_table table type of mtreeitm in SE11.
      DATA: node TYPE treev_node,
                 item TYPE mtreeitm.
      node-node_key = root.
      CLEAR node-relatkey.
      CLEAR node-relatship.
      node-hidden = ' '.
      node-disabled = ' '.
      CLEAR node-n_image.
      CLEAR node-exp_image.
      node-isfolder = 'X'.
      node-expander = 'X'.
      APPEND node TO node_table.
      item-node_key = root.
      item-item_name = colm1.
      item-class = cl_gui_column_tree=>item_class_text.
      item-text = 'Root'.
      APPEND item TO item_table.
      item-node_key = root.
      item-item_name = colm2.
      item-class = cl_gui_column_tree=>item_class_text.
      item-text = 'Amount'.
      APPEND item TO item_table.
      LOOP AT it_vbeln INTO wa_vbeln.
        node-node_key = wa_vbeln-vbeln.
        node-relatkey = root.
        node-relatship = cl_gui_column_tree=>relat_last_child.
        node-hidden = ' '.
        node-disabled = ' '.
        CLEAR node-n_image.
        CLEAR node-exp_image.
        node-isfolder = 'X'.
        node-expander = 'X'.
        APPEND node TO node_table.
        item-node_key = wa_vbeln-vbeln.
        item-item_name = colm1.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_vbeln-vbeln.
        APPEND item TO item_table.
        item-node_key = wa_vbeln-vbeln.
        item-item_name = colm2.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_vbeln-netwr.
        APPEND item TO item_table.
        LOOP AT it_posnr INTO wa_posnr.
        node-node_key = wa_posnr-posnr.
        node-relatkey = wa_vbeln-vbeln.
        node-relatship = cl_gui_column_tree=>relat_last_child.
        node-hidden = ' '.
        node-disabled = ' '.
        CLEAR node-n_image.
        CLEAR node-exp_image.
        node-isfolder = ' '.
        node-expander = ' '.
        APPEND node TO node_table.
        item-node_key = wa_posnr-posnr.
        item-item_name = colm1.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_posnr-posnr.
        APPEND item TO item_table.
        item-node_key = wa_posnr-posnr.
        item-item_name = colm2.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_posnr-netpr.
        APPEND item TO item_table.
        ENDLOOP.
      ENDLOOP.
    ENDFORM.
    Now this program compiles fine and runs till there is only one level. That is root->vbeln. But when i add one more loop of it_posnr it gives me runtime error of message type 'X'. The problem i found was uniqueness of item-item_name as all the sales order have posnr = 0010. What could be done? I tried giving item_name unique hierarchy level using counters just like stufe field in prps eg. 10.10.10, 10.10.20,10.20.10,10.20.20,20.10.10 etc.. etc.. but still i am getting runtime error when i add one more hierarchy using nested loop. Plz guide.
    Edited by: Yayati6260 on Jul 14, 2011 7:25 AM

    Hello all,
    Thanks the issue is solved. The node key was not getting a unique identification as nodekey. I resolved the issue by generating unique identification for each level. Thanks all,
    Regards
    Yayati Ekbote

Maybe you are looking for