Solved

Container and Frame

Posted on 2004-09-22
16
171 Views
Last Modified: 2013-11-23
How do I appear a container in a frame? What I wanna do is, when the user load a file into the GUI, the GUI will appear the map in the label. I have the following method called in the load button listener:

------------------------------------------------------------------------
 public void drawMap(File aFile)
    {
         // send file over the loader
         MapLoader loader = new MapLoader (aFile.getName());
         
         // graph created
          Graph gf = new GraphImp();
          gf = loader.getGraph();
         
          //Create and set up the container.
        Container in = new Container();

        //Set up the content pane.
        CoordinatesPlane controller = new CoordinatesPlane();
        controller.buildUI(in); // fill up the container

        getContentPane().add(in); // add the container back...
    }

-------------------------------------------------------------------
public class CoordinatesPlane
  {
    public JLabel label;
    public Point clickPoint, cursorPoint;

    public void buildUI(Container container)
    {
        container.setLayout(new BoxLayout(container,BoxLayout.PAGE_AXIS));

        CoordinateArea coordinateArea = new CoordinateArea(this);
        container.add(coordinateArea);

        label = new JLabel();
        resetLabel();
        container.add(label);

        //Align the left edges of the components.
        coordinateArea.setAlignmentX(Component.LEFT_ALIGNMENT);
        label.setAlignmentX(Component.LEFT_ALIGNMENT); //redundant
    }

  ...............

---------------------------------------------------------------------------------

Apparently, it shows nothing on the label even I load the map. Why is that so? Somebody?
0
Comment
Question by:jtcy
  • 8
  • 8
16 Comments
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Where do you declare your JFrame?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
You need to add the component into the JFrame/Frame and then it will show up. You will also need to pack or make the JFrame/Frame visible.
0
 

Author Comment

by:jtcy
Comment Utility
Um......this is where my problem is, i don want to show the container as a JFrame, becuz within my that driver class, there is a frame, and if u look at the code:

> getContentPane().add(in); // add the container back...

I tried to add the container into current frame. I could show it as a pop out frame if I use JFrame instead of Container, but that is not what I want.

Anyhow?
0
 

Author Comment

by:jtcy
Comment Utility
In fact, I would want the container to show in a label of current frame. Within the class of the method drawMap(), the label has been initialised at top:

JLabel map;

So, I would like to show the contented container to show up in that label.
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
You need to have something to add in the container. You cannot add a jbutton or jlabel straight to a container, you need to add it to a frame or a panel first.
0
 

Author Comment

by:jtcy
Comment Utility
Aik, as I said, there have been a JFrame out on top. Okay, let me paste the whole class:

-----------------------------------------------------------------------------------------------------

import Maploader.*;
import Maploader.graphs.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.File;


public class GUI extends JFrame
{
    JLabel map_label;
    JLabel map;
    JTextArea stats;
    JScrollPane sp_stats;
    JScrollBar scrollbar_v_1;
    JButton start;
    JButton stop;
    JLabel control_label;
    JLabel label_1;
    JButton big_stop;
    JLabel mapLabel;
   
    String temp_message = "";
   
    // Items under File                                                            
    JMenuItem Load = new JMenuItem("Load");            
    JMenuItem Quit = new JMenuItem("Quit");
   
    // Items under View                
    JMenuItem Status = new JMenuItem("Source File");          
   
    // Items under Help
    JMenuItem Version = new JMenuItem("About HeavyComponent");                      
    JMenuItem Documents = new JMenuItem("User Manual");
       

    // File chooser for loading files
       JFileChooser fc;


    public GUI()
    {
          // setting up the frame layout
        GUILayout customLayout = new GUILayout();
        getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
        getContentPane().setLayout(customLayout);
       
        fc = new JFileChooser();
       
        // setting up the menu bar
       
        JMenuBar bar = new JMenuBar();                            
          setJMenuBar(bar);

          JMenu FileMenu = new JMenu("File");                      
          FileMenu.add(Load);                          
          Load.setEnabled(true);                              
          FileMenu.add(Quit);
          Quit.setEnabled(true);
            
          JMenu ViewMenu = new JMenu("View");
          ViewMenu.add(Status);
          Status.setEnabled(false);
            
          JMenu HelpMenu = new JMenu("Help");
          HelpMenu.add(Version);
          HelpMenu.add(Documents);
            
          bar.add(FileMenu);
          bar.add(ViewMenu);
          bar.add(HelpMenu);
          
          
            // set up the map

        map_label = new JLabel("Map:");
        getContentPane().add(map_label);

        map = new JLabel("");
        getContentPane().add(map);
       
        // set up the stats

        stats = new JTextArea("");
        sp_stats = new JScrollPane(stats);
        getContentPane().add(sp_stats);
        stats.setFont(new Font("Courier New", Font.PLAIN, 11));
        printStats("Welcome! Please load a map.");

        scrollbar_v_1 = new JScrollBar(Scrollbar.VERTICAL);
        getContentPane().add(scrollbar_v_1);

        // control buttons
        start = new JButton("Start");
        getContentPane().add(start);

        stop = new JButton("Stop/Pause");
        getContentPane().add(stop);

        // copyright stats
        control_label = new JLabel("Control:");
        getContentPane().add(control_label);

        label_1 = new JLabel("Heavy Component Software Development Team");
        getContentPane().add(label_1);

        big_stop = new JButton("Emergency Stop");
        getContentPane().add(big_stop);

        setSize(getPreferredSize());

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
       
        setupEvents();
    }
   
    private void setupEvents()
      {
          
            Load.addActionListener(new ActionListener()
               {
                     public void actionPerformed(ActionEvent e)
                       {
                              //Handle open button action.
                     if (e.getSource() == Load)
                      {
                             // adding file filter to only accept XML file
                             fc.addChoosableFileFilter(new LoadFilter());
                         int returnVal = fc.showOpenDialog(GUI.this);
                         
                         if (returnVal == JFileChooser.APPROVE_OPTION)
                           {
                              File file = fc.getSelectedFile();
                              printStats("Loaded successfully: " + file.getName() + "." + "\n");
                              // draw map
                              drawMap(file);
                           }               
                          }
                     }
               }
             );

          // Quit the frame
            Quit.addActionListener(new ActionListener()
             {
                        public void actionPerformed(ActionEvent e)
                     {
                        // Complete Quit Action
                        setVisible(false);
                        System.exit(0);
                     }
             });
            
            start.addActionListener(new ActionListener()
               {
                     public void actionPerformed(ActionEvent e)
                       {

                     
                       }
               }
             );

              stop.addActionListener(new ActionListener()
               {
                     public void actionPerformed(ActionEvent e)
                       {

                     
                       }
               }
             );
            
            

     }
     
    // Print Stats...
   
    public void printStats(String msg)
    {
         //System.out.println(msg);
         temp_message = stats.getText();
         temp_message = temp_message + "\r\n" + msg;
         this.stats.setText( temp_message );

      
    }
   
    public void drawMap(File aFile)
    {
          // send file over the loader
          MapLoader loader = new MapLoader (aFile.getName());
          
          // graph created
            Graph gf = new GraphImp();
            gf = loader.getGraph();
            
            //Create and set up the window.
        Container in = new Container();

        //Set up the content pane.
        CoordinatesPlane controller = new CoordinatesPlane();
        controller.buildUI(in);

        //Display the window.
        //in.pack();
        //in.setVisible(true);
       
        getContentPane().add(in);
    }

   
    public static void main(String args[])
    {
        GUI window = new GUI();

        window.setTitle("Heavy Component version 1.0");
        window.pack();
        window.show();
    }
}

0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
Ok I think the problem is in the  public void drawMap(File aFile) method. Why do you create a Container in there and not a panel. A contaier shoudl contain a frame or a panel, not the opposite (you cannot add a container to a frame for example, only a frame to a container).
0
 

Author Comment

by:jtcy
Comment Utility
Okay, i tried using JPanel, it still don get shown though..... :(
------------------------------------------
//Create and set up the window.
JPanel in = new JPanel();
//Set up the content pane.
CoordinatesPlane controller = new CoordinatesPlane();
controller.buildUI(in);
getContentPane().add(in);
-------------------------------------------
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 35

Expert Comment

by:girionis
Comment Utility
> CoordinatesPlane controller = new CoordinatesPlane();

What is this doing? Mayeb there is a problem there?
0
 

Author Comment

by:jtcy
Comment Utility
Well, I am trying to create a coordinate plane, that constructs an object of that class and then controller.buildUI would feed the container with that plane created. Here;s the other class:


--------------------------------------------------------------------------
public class CoordinatesPlane
  {
    public JLabel label;
    public Point clickPoint, cursorPoint;

    public void buildUI(Container container)
    {
        container.setLayout(new BoxLayout(container,BoxLayout.PAGE_AXIS));

        CoordinateArea coordinateArea = new CoordinateArea(this);
        container.add(coordinateArea);

        label = new JLabel();
        resetLabel();
        container.add(label);

        //Align the left edges of the components.
        coordinateArea.setAlignmentX(Component.LEFT_ALIGNMENT);
        label.setAlignmentX(Component.LEFT_ALIGNMENT); //redundant
    }

    public void updateCursorLocation(int x, int y) {
        if (x < 0 || y < 0) {
            cursorPoint = null;
            updateLabel();
            return;
        }
           
        if (cursorPoint == null) {
            cursorPoint = new Point();
        }
       
        cursorPoint.x = x;
        cursorPoint.y = y;
        updateLabel();
    }

    public void updateClickPoint(Point p) {
        clickPoint = p;
        updateLabel();
    }

    public void resetLabel() {
        cursorPoint = null;
        updateLabel();        
    }
   
    protected void updateLabel() {
        String text = "";

        if ((clickPoint == null) && (cursorPoint == null)) {
            text = "Click or move the cursor within the framed area.";
        } else {
           
            if (clickPoint != null) {
                text += "The last click was at ("
                        + clickPoint.x + ", " + clickPoint.y + "). ";
            }
           
            if (cursorPoint != null) {
                text += "The cursor is at ("
                        + cursorPoint.x + ", " + cursorPoint.y + "). ";
            }
        }
       
        label.setText(text);
    }


    public static class CoordinateArea extends JComponent
                                       implements MouseInputListener {
        Point point = null;
        CoordinatesPlane controller;
        Dimension preferredSize = new Dimension(450,228);
        Color gridColor;
   
        public CoordinateArea(CoordinatesPlane controller) {
            this.controller = controller;
           
            //Add a border of 5 pixels at the left and bottom,
            //and 1 pixel at the top and right.
            setBorder(BorderFactory.createMatteBorder(1,5,5,1,
                                                      Color.RED));
                                                     
            addMouseListener(this);
            addMouseMotionListener(this);
            setBackground(Color.WHITE);
            setOpaque(true);
        }
   
        public Dimension getPreferredSize() {
            return preferredSize;
        }
   
        protected void paintComponent(Graphics g) {
            //Paint background if we're opaque.
            if (isOpaque()) {
                g.setColor(getBackground());
                g.fillRect(0, 0, getWidth(), getHeight());
            }

            //Paint 20x20 grid.
            g.setColor(Color.GRAY);
            drawGrid(g, 20);
           
            //If user has chosen a point, paint a small dot on top.
            if (point != null) {
                g.setColor(getForeground());
                g.fillRect(point.x - 3, point.y - 3, 7, 7);
            }
        }
       
        //Draws a 20x20 grid using the current color.
        private void drawGrid(Graphics g, int gridSpace) {
            Insets insets = getInsets();
            int firstX = insets.left;
            int firstY = insets.top;
            int lastX = getWidth() - insets.right;
            int lastY = getHeight() - insets.bottom;
           
            //Draw vertical lines.
            int x = firstX;
            while (x < lastX) {
                g.drawLine(x, firstY, x, lastY);
                x += gridSpace;
            }
           
            //Draw horizontal lines.
            int y = firstY;
            while (y < lastY) {
                g.drawLine(firstX, y, lastX, y);
                y += gridSpace;
            }
        }
   
        //Methods required by the MouseInputListener interface.
        public void mouseClicked(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            if (point == null) {
                point = new Point(x, y);
            } else {
                point.x = x;
                point.y = y;
            }
            controller.updateClickPoint(point);
            repaint();
        }

        public void mouseMoved(MouseEvent e) {
            controller.updateCursorLocation(e.getX(), e.getY());
        }

        public void mouseExited(MouseEvent e) {
            controller.resetLabel();
        }

        public void mouseReleased(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mousePressed(MouseEvent e) { }
        public void mouseDragged(MouseEvent e) { }
    }
}
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
It's difficult to say what's going on. Can you post a small compilable example that demonstartes the problem?
0
 

Author Comment

by:jtcy
Comment Utility
There;s no any compilation error, just that the thing i wan it to show on the interface, dont show up. hm~~~ u see, I have this Container instance and I send it to a method and it gets returned with filled components in itself. Then I wanna show this Container at my current frame, so I do: getContentPane().add(in); But it just doesnt show out. :(
0
 

Author Comment

by:jtcy
Comment Utility
So what would you recommend me to use to show the map on the interface? I cannot have it as a seperate window, so definitely a Frame cant be used, what about JLabel?..or JPanel?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
What exactly is the map? Is it a picture?
0
 

Author Comment

by:jtcy
Comment Utility
Don't worry, I have eventually let it show up on the interface. I decided to use JPanel as the map, and it worked. The reason it didnt work was becuz add to the interface after the interface frame was created. So, I added to it in the constructor and it appears out now.

But the next problem is....how am i going to edit the panel in real time. hm......ie. when the user clicks on a button, the panel would show smth....
0
 
LVL 35

Accepted Solution

by:
girionis earned 20 total points
Comment Utility
Put in on the panel from the beginning, have it hidden and when the button is pressed show it.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now