• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

Container and Frame

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
jtcy
Asked:
jtcy
  • 8
  • 8
1 Solution
 
girionisCommented:
Where do you declare your JFrame?
0
 
girionisCommented:
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
 
jtcyAuthor Commented:
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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
jtcyAuthor Commented:
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
 
girionisCommented:
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
 
jtcyAuthor Commented:
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
 
girionisCommented:
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
 
jtcyAuthor Commented:
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
 
girionisCommented:
> CoordinatesPlane controller = new CoordinatesPlane();

What is this doing? Mayeb there is a problem there?
0
 
jtcyAuthor Commented:
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
 
girionisCommented:
It's difficult to say what's going on. Can you post a small compilable example that demonstartes the problem?
0
 
jtcyAuthor Commented:
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
 
jtcyAuthor Commented:
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
 
girionisCommented:
What exactly is the map? Is it a picture?
0
 
jtcyAuthor Commented:
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
 
girionisCommented:
Put in on the panel from the beginning, have it hidden and when the button is pressed show it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 8
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now