Can we add JFrame to JPanel?

hi
I m trying to add JFrame which has JPanel with BufferedImage to another JPanel.
Is it possible? if yes kindly tell me how to achieve this.
thanx

Just another cross poster.
[http://www.java-forums.org/java-2d/16085-how-add-jframe-inside-jpanel.html]
db

Similar Messages

  • How can we add components to JPanel so that they can be resizeable

    Is it possible to add components to JPanel so that we can resize them or drag them.

    You could try searching the forums, but I'll save you the trouble. tjacobs has oft posted code which does what you want, both dragging and resizing.
    You can find an example here or here.

  • Can not add a picture to the JFrame from an ActionListener class

    As topic says, I can not add a picture to the JFrame from an ActionListener class which is a class inside the JFrame class.
    I have a Map.java class where I load an image with ImageIcon chosen with JFileChooser.
    I my window class (main class), I have following:
    class OpenImage_Listener implements ActionListener
         public void actionPerformed(ActionEvent e)
              int ans = open.showOpenDialog(MainProgram.this);     // "open" is the JFileChooser reference
              if(ans == open.APPROVE_OPTION)
                   File file = open.getSelectedFile();                    
                   MainProgram.this.add(new Map(file.getName()), BorderLayout.CENTER);     // this line does not work - it does not add the choosen picture on the window,
                            //but if I add the picture outside this listener class and inside the MainProgram constructor, the picture apperas, but then I cannot use the JFileChooser.
                            showMessageDialog(MainProgram.this, fil.getName() ,"It works", INFORMATION_MESSAGE);  // this popup works, and thereby the ActionListener also works.
    }So why can�t I add a picture to the window from the above listener class?

    The SSCCE:
    Ok, I think I solved it with the picture, but now I cannot add new components after adding the picture.
    Look at the comment in the actionlistener class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Test extends JFrame{
         JButton b = new JButton("Open");
         JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
         Picture pane;
         Test(){
              super("Main Program");
              setLayout(new BorderLayout());
              JPanel north = new JPanel();
              add(north, BorderLayout.NORTH);
              north.add(b);
              b.addActionListener(new Listener());
              setVisible(true);
              setSize(500,500);
              pane = new Picture("");
              add(pane, BorderLayout.CENTER);
         class Listener implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   int ans = jfc.showOpenDialog(Test.this);
                   if(ans == jfc.APPROVE_OPTION)
                        File file = jfc.getSelectedFile();
                        Test.this.add(new Picture(file.getName()), BorderLayout.CENTER);
                        pane.add(new JButton("NEW BUTTON")); // Why does this button not appear on the window???
                        pane.repaint();
                        pane.revalidate();
         public static void main(String[] args)
              Test t = new Test();
    class Picture extends JPanel
         Image pic;
         String filename;
         Picture(String filename)
              setLayout(null);
              this.filename = filename;
              pic = Toolkit.getDefaultToolkit().getImage(filename);
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawImage(pic,0,0,getWidth(),getHeight(),this);
                revalidate();
    }

  • Can i add JPanel to Jasper Report

    I have a panel on which I have drawn some graphics and now I want this panel to be added on report, is this possible?
    Can we add Jpanel to Jasper report, if anybody has any thoughts and ideas please share with me?
    Thanks & regards,
    - Prashant

    Don't know exactly what you mean but this is how I add a JPanel to a JScrollPane.
    public class Scroll extends JFrame{
    JScrollPane jsp;
    JPanel panel;
    public Scroll(){
    jsp = new JScrollPane();
    panel = new JPanel();
    jsp.getViewPort().add(panel);
    getContentPane().add(jsp, BorderLayout.CENTER)
    }

  • How can I add the key listener to JFrame

    Hi,
    How can I add the Key Listener to the JFrame? I want to show the Windows default popup which comes after right clicking on the frame's header. I want to add the key board support for the same

    1. Make sure that key events are enabled on your component. (AWTMulticaster.enableEvents(...)
    2. add the keylistener

  • Can I add a JPanel in JScrollPane?

    Can I add a JPanel in JScrollPane?
    If I added,components in the JPanel can effect the JScrollPane?
    thanks!

    Can I add a JPanel in JScrollPane?yes you can - it is meant for this.
    If I added,components in the JPanel can effect the
    JScrollPane?if you mean affect like focusing and scrolling to a certain place - the answer is yes, you have to look the right functions in each component you insert to the panel.

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

  • How can i add the check box beside the directory?

    how can i add the check box beside the directory? anybody can help?
    tis r the panel of my program :
    // FileTreePanel.java
    // JPanel for displaying file system contents in a JTree
    // using a custom TreeModel.
    package com.deitel.advjhtp1.mvc.tree.filesystem;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import com.deitel.advjhtp1.mvc.tree.filesystem.FileSystemModel;
    public class FileTreePanel extends JPanel {
    private JTree fileTree;
    private FileSystemModel fileSystemModel;
    private JTextArea fileDetailsTextArea;
    public FileTreePanel( String directory )
    fileDetailsTextArea = new JTextArea();
    fileDetailsTextArea.setEditable( false );
    fileSystemModel = new FileSystemModel(
    new File( directory ) );
    fileTree = new JTree( fileSystemModel );
    fileTree.setEditable( true );
    fileTree.addTreeSelectionListener(
    new TreeSelectionListener() {
    public void valueChanged(
    TreeSelectionEvent event )
    File file = ( File )
    fileTree.getLastSelectedPathComponent();
    fileDetailsTextArea.setText(
    getFileDetails( file ) );
    JSplitPane splitPane = new JSplitPane(
    JSplitPane.HORIZONTAL_SPLIT, true,
    new JScrollPane( fileTree ),
    new JScrollPane( fileDetailsTextArea ) );
    setLayout( new BorderLayout() );
    add( splitPane, BorderLayout.NORTH );
    JCheckBox check = new JCheckBox("Check me");
    add( check, BorderLayout.SOUTH );
    public Dimension getPreferredSize()
    return new Dimension( 400, 200 );
    private String getFileDetails( File file )
    if ( file == null )
    return "";
    StringBuffer buffer = new StringBuffer();
    buffer.append( "Name: " + file.getName() + "\n" );
    buffer.append( "Path: " + file.getPath() + "\n" );
    buffer.append( "Size: " + file.length() + "\n" );
    return buffer.toString();
    public static void main( String args[] )
    if ( args.length != 1 )
    System.err.println(
    "Usage: java FileTreeFrame <path>" );
    else {
    JFrame frame = new JFrame( "JTree FileSystem Viewer" );
    FileTreePanel treePanel = new FileTreePanel( args[ 0 ] );
    frame.getContentPane().add( treePanel );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible( true );
    }

    You can maybe explore button and forms feature in InDesign. It was added in CS6.

  • Best recommendataion to work with one JFrame & Multiple Jpanels(or Windows)

    Hi all,
    I am a bit new(bie) to Java and Gui but not new to programming.
    I need to write an application in using Java. The Current editor I use is Netbeans.
    I have a rough idea on how to write this apps, but I would like to confirm if my idea is applicable to such application (from a performance and feasibility standpoint).
    The main idea for this application is to have multiple forms that users would populate, and the values entered will be stored in a Database.
    I had plan to use only one main Window (JFrame), and no MDI, no multiple Java windows.
    My plan was:
    -     Create the main form (JFrame) with menus, once the application is loaded, I will check if a database connection is available otherwise open a Jpanel to input database settings (which can be started from the menu).
    -     All menus and application/company settings would be set in the main form
    -     All features available in the Jpanel would be in a separate class for clarity/lisibility of my code. For instance : user settings would be a separate jpanel class; database settings is a new jpanel class
    -     Each Jpanel class would be stored in a separate java/class file.
    Here is my test example for now (file MainForm.java) :
    import javax.swing.*;
    public class MainForm extends JFrame {
        /* Initializing a few variables */
        String databaseServer = null;
        String databaseUserName = null;
        String databasePassword = null;
        /** Creates new form MainForm */
        public MainForm() {
            /* Initializing menus */
            initComponents();
           /* starting a new instance of database configuration */
            DbPanel test = new DbPanel();
        /* Initialization menu and graphical components */
        private void initComponents () {
            JMenuBar BarMenu;
            JMenu MenuConfiguration;
    /* �.*/
         BarMenu.add(MenuConfiguration);
         setJMenuBar(BarMenu);
         pack();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainForm().setVisible(true);
    } Here is my DBpanel class (file MainForm.java) :
    public class DbPanel extends javax.swing.JPanel {
        /** Creates new form DbPanel */
        public DbPanel() {
            initComponents();
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            java.awt.Button buttonClose;
            java.awt.Button buttonSave;
            java.awt.TextField dbName;
    /* � */
           gridBagConstraints.ipadx = 100;
            gridBagConstraints.insets = new java.awt.Insets(0, 21, 0, 21);
            add(dbPassword, gridBagConstraints);
    // </editor-fold>   
    }Here are then my questions:
    -     Would you think that is a practical plan to write such application?
    -     Once I display a Jpanel form and I close it (for instance myJpanel.setVisible=false), will the memory be freed?
    -     Is there any other way to remove entire a JPanel from RAM?
    -     How can I call my �external� Jpanel ? I have designed one Jpanel class for testing but I was not able to display it when I created the new instance of that class.
    -     Is there any other alternative to Jpanel for this application? I was thinking about opening a new window within my Jframe. But, ideally it would be best that multiple windows are not opened simultaneously.
    Thanks for your input

    I was thinking about this but requirements are the
    application development cost should be reduced to the
    minimum.
    thus one desktop application and one database
    server.Application development cost? If you are being paid to do this, the bulk of the cost will be your hourly rate times the number of hours it takes you to do it. Thus you want to minimize the number of hours it takes you to do it. Assuming that the cost of your learning Java is going to be charged to this project, it might well be a good idea for you to do it in a language you already know. Or one where it's easy to develop this sort of application.

  • Change jFrame to JPanel

    I have a gui that uses Jframe how easy would it be to change it to use jPanel instead? would it just be a few tweeks or would i be basically writting my code again?
    Also kind of off topic but if any one could give there view i'd be very happy
    The class file that uses the GUI is for entering names and DOB's, the same class can also be used for reading it back in again (data gets saved to a file) in your opinion which would look best
    if i split the gui in half so the left side was for entering and the right hand side was for reading in or
    if i just had it so there was one lot of text fields which could be used to enter data and if you read in the file would show the data from the file?

    I have a gui that uses Jframe how easy would it be to change it to use jPanel instead?You already are already using panels most likely.
    All GUI's need a top level container (JFrame, JDialog or JWindow). To the top level container you add Swing components (JPanel, JButton, JTextField, JTable etc...).
    So your question doesn't make any sense.
    Take a look at the Swing tutorial which has a [url http://java.sun.com/docs/books/tutorial/uiswing/components/components.html]Visual Index of Swing Componentsurl. Click on each component and you will find example programs that use the component and you can see how the program is structured and use that approach in your design.

  • Can I Add a memo in the E61i calendar that repeats...

    Can I Add a memo in the E61i calendar that repeats weekly?

    Try this it worked, I not sure if this is what you want. a few ke things worth noticing, setPreferred size on the JPanel. That might be the reason it was not showing up, anyway here it is.
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    public class temp extends JFrame{
         public temp(){
              super("Scroll Test");
              Vector myVector = new Vector();
              JPanel contentPane = new JPanel(new BorderLayout());
              for(int j = 0; j < 40; j++)
                   myVector.add(new String(j + ""));
              JList theList = new JList(myVector);
              JScrollPane sp = new JScrollPane(theList);
              JPanel p = new JPanel(new BorderLayout());
              p.setPreferredSize(new Dimension(100, 100));
              JMenuBar menuBar = new JMenuBar();
              JMenu menu = new JMenu("Scroll");
              p.add(sp, BorderLayout.CENTER);
              menu.add(p);
              menuBar.add(menu);
              this.setJMenuBar(menuBar);
              this.setContentPane(contentPane);
              this.setSize(300, 300);
         public static void main(String [] args){
              JFrame j = new temp();
              j.show();
    Good luct write back and tell me if this is what you were looking for!
    Late jason

  • Inserting a Gui program using JFrames and JPanel

    I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?

    whatever is in the frame's contentPane now, you add to a separate JPanel.
    you also add your chat stuff to the separate panel
    the separate panel is added to the frame as the content pane

  • JFram or Jpanel maximum size

    How should I set maximum and minimum size of JFrame (or JPanel using BorderLayout) ? Please note setPreferredSize() and setMaximumSize() are not effective.
    Thanks

    You can't set the min/max size of a JPanel in a BorderLayout.
    You can't directly set the min/max size of a JFrame, but you can add a ComponentListener the the JFrame and resize the JFrame when it exceeds you specified sizes.
    Search the forum using "+maximum +addcomponentlistener".
    Of course since this is a Swing question, you should be searching the Swing forum.

  • How can i refresh JFrame at regular intervals to display in intervals

    I have a query which is :
    String query = "select FIRSTNAME, MIDDLEINITIAL, LASTNAME from user" ;
    now i have executed the above query
    ResultSet rs = stmt.executeQuery(query) ;
    Suppose i get 2000 rows in my resultset after execution.
    If i want to display all the contents of my query inside a JFrame, then i can say
    JFrame myFrame = new JFrame() ;
    myFrame.setSize(500, 500) ;
    while(rs.next()){
    add the results to myFrame
    myFrame.pack() ;
    myFrame.setVisible() ;
    but this may take a long time to show my frame, because first it has to either add components to my JFrame if use JLabels or if i use graphics then it has to wait till complete all of my drawString's to display the JFrame.
    and this may take time.
    I would like to know, how can make my JFrame intelligent enough so that if first display an empty frame, refresh at regular intervals and see how many i have fetched from the result set and add those to my JFrame, and do this opration untill i am done fetching all the results.
    Thanks
    Arun

    Any reason why you aren't displaying the results in a table? Both labels and drawString do not seem like a good alternative.
    Now to your question, you could use a thread and force painting after so many from the resultset. You could display a fixed number and implement your own scrolling scheme. Say paint first 50 and scrolling forward and back.

  • Can I add multiple swing elements on a single line.

    Im adding a number of labels to the JPanel -- is there a way to add them all on one line as opposed to:
    c.add(top1);
    c.add(top2); etc. etc.?

    Im adding a number of labels to the JPanel -- is
    there a way to add them all on one line as opposed
    to:
    c.add(top1);
    c.add(top2); etc. etc.?well you can do
    c.add(top1); c.add(top2);
    but basically no, you can't add them all together at the same time

Maybe you are looking for

  • Belkin's Nostromo N52 does not recognize/work with games

    I am using Belkin's Nostromo N52 gamepad with my iMac G5 Recently I installed "James Bond 007 Nightfire" and "Tron 2.0". Nostromo is not recognizing Nightfire at all. When I select the application Nightfire.app, Nostromo does not work as usually when

  • VBS Script to validate RDP Connection

    I am working on a VBS script to confirm if RDP Connection is working on remote servers. I know some server administrators check it via Telnet on default RDP port 3389. But, it is not completely reliable. I need to open an RDP Connection to a server,

  • Why do I keep getting a message that says "Isufficient Flash Player Resources"?

    I've tried all of the solutions outlined on the help blogs but nothing seems to work. I've removed and reloaded Flash Player, upgraded to IE10, tried 32 bit and 64 bit versions but I still get the above message when I try to watch an ESPN video. Can

  • Etherchannel Failover issue

    I have cisco 2960s switch stacked at my DC site and one 2960s cisco switch at DR site There are two fiber links from DC to DR site I have configured etherchannel LACP on both sides. The fiber links are terimiated to the switches from media converter

  • Client "discoverying" SCCM Server?

    Hi, I got a strange problem, we are in the process of implementing the SCCM 2012 R2 into our company, and for testing purposes i designated only one OU to be discoverable by our new SCCM 2012 R2 server, but every now and then another computer is disc