Overpainted JInternalFrame

Hi there!
I have been experimenting with the JInternalFrame class. It seemed very handy, because I am playing a lot with Java2D API and try different things on multiple JPanels. I put each Panel on a separate JInternalFrame. This works fine, as long as I only draw some lines und rectangles. Now here's my problem:
I fill a JPanel in green using "g2.fillRectangle()" ... and in my MDI Interface, the green filled area is always on top. The Internal frame itself is covered by two others, but the green rectangle is painted over everything else. Only this green fill is there, eerything else is fine.
Does someone have an idea, why that is?
Greetings, Sascha

Do you follow the standard ?
That means:
1) use a JPanel to put into the frame's content pane.
1) overwrite the panel's paintComponent(Graphics g) method.
3) in this method, first call super.paintComponent(g)
4) call the g2.fillRectangle()
5) draw your graphic stuff or call your drawing methods passing the graphics as a parameter

Similar Messages

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • Alarm status drawing iow: recolour JInternalFrame components

    Greetings,
    Please have a look at this picture. It's a low res snapshot of
    a few quite complicated components. Most of the functionality isn't
    visible nor relevant in the example. What you're looking at is a real time
    process of some sort. Things can go wrong in that process. In a previous
    version of my views I'd turn the background colour of some components
    red/yellow/green according to the 'alarm status' of the process. One of
    my customers suggested the idea of turning everything red/yellow/green
    inside those JInternalFrames (that's what you're looking at in the example).
    Of course one fool can ask more than a dozen of wise men can answer
    and I am not that wise, so my question is: how would one change the
    colour of all components that are part of a JInternalFrame (or any
    other container) such that the colour wouldn't be 100% opague but
    still visible by itself and still showing the information originally present
    in each individual component. iow, as if a transparent monochrome
    filter were positioned in front of that entire JContainer.
    In a naive way I like the idea; if the idea turns out to be too complicated
    to realize I'd be happy with visual alternatives also. (such as big arrows
    pointing to the JContainer where the alarm happened).
    Note that these appliations run in a 'factory' environment where people
    either hardly watch the screens or they watch them at quite a great
    distance. The changing colours should just attract their attention so they
    will walk/run/drive/ride to the screens for a second inspection.
    Any ideas are appreciated.
    kind regards,
    Jos

    Not sure I understand the question, but I keyed in on:
    as if a transparent monochrome filter were positioned in front of that entire JContainer.So maybe you could use a GlassPane:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GlassPaneTest extends JFrame
        public GlassPaneTest()
            final JComponent glassPane = new JComponent()
                public void paintComponent(Graphics g)
                    g.setColor( getBackground() );
                    g.fillRect(0, 0, getSize().width, getSize().height);
            glassPane.setOpaque( false );
            glassPane.setBackground( new Color(240, 20, 20, 100) );
            setGlassPane( glassPane );
            glassPane.addKeyListener( new KeyAdapter()
                public void keyPressed(KeyEvent e)
                    e.consume();
            glassPane.addMouseListener( new MouseAdapter()
                public void mousePressed(MouseEvent e)
                    e.consume();
            final JButton button = new JButton( "Click Me" );
            button.setMnemonic('c');
            button.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent e)
                       glassPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                       glassPane.setVisible( true );
                       glassPane.requestFocus();
                       Thread thread = new Thread()
                            public void run()
                                try { this.sleep(5000); }
                                catch (InterruptedException ie) {}
                                 glassPane.setVisible( false );
                                 glassPane.setCursor(null);
                    thread.start();
            getContentPane().add(new JLabel("NORTH"), BorderLayout.NORTH );
            getContentPane().add( button );
            getContentPane().add(new JTextField(), BorderLayout.SOUTH);
        public static void main(String[] args)
            GlassPaneTest frame = new GlassPaneTest();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.setSize(300, 300);
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html]How to Use Glass Panes shows how you can also do a simple drawing (your arrow?) on the glass pane.

  • What is equivalent of JInternalFrame in JavaFX 2.0?

    what is equivalent of JInternalFrame in JavaFX 2.0?
    Actually I want to use pure javaFX 2.0 to view report created in iReport 5.0.0.
    I have used java.swing code, and now I want to use pure javaFX 2.0.
    My code in swing is as follows
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package reports;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.HashMap;
    import net.sf.jasperreports.engine.JRException;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.view.JRViewer;
    * @author TANVIR AHMED
    public class ReportsViewer extends javax.swing.JInternalFrame {
    * Creates new form MyiReportViewer
    private ReportsViewer()
    super("Report Viewer",true,true,true,true);
    initComponents();
    setBounds(10,10,600,500);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    public ReportsViewer(String fileName)
    this(fileName,null);
    public ReportsViewer(String fileName,HashMap parameter)
    this();
    try
    /* load the required JDBC driver and create the connection
    here JDBC Type Four Driver for MySQL is used*/
    //Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "invoice", "item");
    //Connection con=DriverManager.getConnection("jdbc:mysql://localhost/inventory","root","karim");
    /*(Here the parameter file should be in .jasper extension
    i.e., the compiled report)*/
    JasperPrint print = JasperFillManager.fillReport(
    fileName, parameter, con);
    JRViewer viewer=new JRViewer(print);
    Container c=getContentPane();
    c.setLayout(new BorderLayout());
    c.add(viewer);
    catch(SQLException sqle)
    sqle.printStackTrace();
    catch(JRException jre)
    jre.printStackTrace();
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 394, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 290, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    // Variables declaration - do not modify
    // End of variables declaration
    and
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package reports;
    import java.beans.PropertyVetoException;
    * @author TANVIR AHMED
    public class MainUI extends javax.swing.JFrame {
    * Creates new form MainUI
    public MainUI() {
    super("REPORTS");
    initComponents();
    setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jMenuItem1 = new javax.swing.JMenuItem();
    desktopPane = new javax.swing.JDesktopPane();
    salesTaxInv = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    supplyRegister = new javax.swing.JButton();
    PartyLedger = new javax.swing.JButton();
    menuBar = new javax.swing.JMenuBar();
    jMenuItem1.setText("jMenuItem1");
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    desktopPane.setBackground(new java.awt.Color(255, 204, 0));
    desktopPane.setBorder(new javax.swing.border.MatteBorder(null));
    desktopPane.setForeground(new java.awt.Color(255, 0, 102));
    desktopPane.setAutoscrolls(true);
    desktopPane.setFont(new java.awt.Font("Bookman Old Style", 0, 14)); // NOI18N
    desktopPane.setPreferredSize(new java.awt.Dimension(1024, 768));
    salesTaxInv.setBackground(new java.awt.Color(255, 255, 255));
    salesTaxInv.setFont(new java.awt.Font("Bookman Old Style", 1, 18)); // NOI18N
    salesTaxInv.setForeground(new java.awt.Color(204, 0, 0));
    salesTaxInv.setText("Sales Tax Invoice");
    salesTaxInv.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    salesTaxInvActionPerformed(evt);
    salesTaxInv.setBounds(20, 53, 200, 31);
    desktopPane.add(salesTaxInv, javax.swing.JLayeredPane.DEFAULT_LAYER);
    jLabel1.setFont(new java.awt.Font("Bookman Old Style", 0, 24)); // NOI18N
    jLabel1.setForeground(new java.awt.Color(50, 72, 255));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("Invoice System Reports");
    jLabel1.setBounds(0, -1, 1024, 50);
    desktopPane.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);
    supplyRegister.setFont(new java.awt.Font("Bookman Old Style", 1, 18)); // NOI18N
    supplyRegister.setForeground(new java.awt.Color(204, 0, 0));
    supplyRegister.setText("Supply Register");
    supplyRegister.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    supplyRegisterActionPerformed(evt);
    supplyRegister.setBounds(20, 100, 200, 30);
    desktopPane.add(supplyRegister, javax.swing.JLayeredPane.DEFAULT_LAYER);
    PartyLedger.setFont(new java.awt.Font("Bookman Old Style", 1, 18)); // NOI18N
    PartyLedger.setForeground(new java.awt.Color(204, 0, 0));
    PartyLedger.setText("Party Ledger");
    PartyLedger.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    PartyLedgerActionPerformed(evt);
    PartyLedger.setBounds(20, 140, 200, 30);
    desktopPane.add(PartyLedger, javax.swing.JLayeredPane.DEFAULT_LAYER);
    setJMenuBar(menuBar);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(desktopPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    private void salesTaxInvActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try
    ReportsViewer myiReportViewer = new ReportsViewer("reports/INV.jasper");
    myiReportViewer.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
    myiReportViewer.setVisible(true);
    desktopPane.add(myiReportViewer);
    myiReportViewer.setSelected(true);
    catch (PropertyVetoException pve)
    pve.printStackTrace();
    private void supplyRegisterActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try
    ReportsViewer myiReportViewer = new ReportsViewer("reports/supplyRegister.jasper");
    myiReportViewer.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
    myiReportViewer.setVisible(true);
    desktopPane.add(myiReportViewer);
    myiReportViewer.setSelected(true);
    catch (PropertyVetoException pve)
    pve.printStackTrace();
    private void PartyLedgerActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try
    ReportsViewer myiReportViewer = new ReportsViewer("reports/CustomerLedger.jasper");
    myiReportViewer.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
    myiReportViewer.setVisible(true);
    desktopPane.add(myiReportViewer);
    myiReportViewer.setSelected(true);
    catch (PropertyVetoException pve)
    pve.printStackTrace();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new MainUI().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton PartyLedger;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton salesTaxInv;
    private javax.swing.JButton supplyRegister;
    // End of variables declaration
    Best Regards

    Dear Sir,
    I am using the swing code and running the jasper report with the above code.
    Realy!
    I start the thread with this code
    @FXML
    private void mainUiButtonAction(ActionEvent event) {
    try{
    new MainUI().setVisible(true);
    catch(Exception ex){                 
    }

  • JInternalFrame drawing problem.

    Hi gurus
    Please could you help with a java problem that I cant find an answer to over the net:
    I have a JDesktop which contains multiple JInternalFrames. On one JInternalFrame i have attached a JPanel on which to draw on. I have multiple threads (simple ball shapes) that need to be drawn onto the JPanel and have left it up to the indivual threads to draw themselves (as opposed to using paintComponent in the JPanel class). The drawing on the JInternalFrame works perfectly fine.
    The problem arises when the other JInternalFrames are placed on top of each other - the balls are drawn over the top most JInternalFrame. What am i doing wrong? I have attached snippets of the code:
    public class Desktop extends JFrame implements ActionListener
              public Desktop()
                        setTitle("Agent's world");
                        setSize(w,h);
                        setDefaultCloseOperation(EXIT_ON_CLOSE);
                        JDesktopPane desktop = new JDesktopPane();
                        setContentPane(desktop);
                        /************* Agent *************/
                        JInternalFrame agents = new JInternalFrame("Agents War", true, false, true, false);                    
                        agents.reshape(0,0,(int)((w/3)*2),h);
                        Container contentPane = agents.getContentPane();
                        canvas = new AgentPanel(agents);
                        contentPane.add(canvas);
                        /************* Button *************/
                        JPanel buttonPanel = new JPanel();
                        ButtonGroup buttonGroup = new ButtonGroup();
                        JButton start = new JButton("START");
                        start.addActionListener(this);
                        buttonPanel.add(start);
                        contentPane.add(buttonPanel, "North");
                        agents.setVisible(true);
                        desktop.add(agents);
                        //sets focus to other frames within the desktop
                        try
                                  agents.setSelected(true);
                        catch(PropertyVetoException e)
                                  //attempt to refocus was vetoed by a frame
              /** Method to listen for event actions, i.e. button clicks **/
         public void actionPerformed(ActionEvent event)
                   //passes through 'this' to allow access to the getList method
                   Agents agent = new Agents(canvas, this);
                   agent.start();
    public class Agents extends Thread
              public Agents(AgentPanel panel, Desktop desktop)
                        panel =_panel;
                        desktop = _desktop;
                        setDaemon(true);
    /** Moves the agent from a spefic position to a new position **/
              public void move()
                        Graphics g = panel.getGraphics();
                        Graphics2D g2 = (Graphics2D)g;
                        try
                                  //set XOR mode
                                  g.setXORMode(panel.getBackground());
                                  //draw over old
                                  Ellipse2D.Double ballOld = new Ellipse2D.Double(i , j, length, length);
                                  g2.fill(ballOld);     
                                  i++;
                                  j++;
                                  if(flag == true)
                                            //draw new
                                            Ellipse2D.Double ballNew = new Ellipse2D.Double(i , j, length, length);
                                            g2.fill(ballNew);
                                            g2.setPaintMode();
                        finally
                                  g.dispose();
              /** Activates the Thread **/
              public void run()
                   int i = 0;
                   while(!interrupted() && i<100)
                        try
                                       for(i = 0 ; i <100 ; i++)
                                                 //draw ball in old position                                             move();          
                                                 sleep(100);                              
                             catch(InterruptedException e)
    public class AgentPanel extends JPanel
              /** local copy of internal frame */
              private JInternalFrame frame;
              public AgentPanel(JInternalFrame _frame)
                        frame = _frame;
                        setSize(frame.getWidth(), frame.getHeight());
                        setBackground(Color.white);          
              public void paintComponent(Graphics g)
                        super.paintComponent(g);
    Thank you in advance.
    Ravs

    I have the same problem. Seems to be a bug. See:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=231037
    Bummer.

  • Need to convert a JFrame to an jinternalframe

    Hello,
    I have an application that is comprised of 7 classes. I'm attempting to rewrite it so that the one class that I have which is for the JFrame is converted to an internal frame so that I can add the complete application to the desktop pane of a gui which I've created, to be a part of a bigger application. I've tried the code that converts JFrames to JInternalFrames but that doesn't seem to work, maybe I'm missing something here. I'm relatively new to the Java Programming world but I'm moving along. Any help is more than welcomed.

    Hello,
    I don't think you can directly convert a JFrame to JInternalFrame
    But panels are compatible
    (for example you can do this : yourJInternalFrame.setContent(yourJFrame.getContent);
    When i program in java, my main classes extends JPanel and not JFrame or JInternalFrame, then you can use this application into every frames or applets :)
    If you do that, set in your main:
    JFrame myJFrame = new JFrame(...);
    MyClass myClassWhichExtendsJPanel = new MYClass(...);
    yourJFrame.setContent(myClassWhichExtendsJPanel);

  • Repaint Problem in JInternalFrame!!!! help plz.

    hi,
    I have a question I have an application that has internal frames, Basically it is a MDI Application. I am using JDK 1.2.2 and windows 2000. The following example shows that when I drag my JInternalFrames only the border is shown and the contents are not shown as being dragged that's fine, but the application I am running have lot of components in my JInternalFrames. And when I drag the JInternalFrame my contents are not being dragged and that's what I want but when I let go the internalFrame it takes time to repaint all the components in the internalFrame. Is there any way I can make the repaint goes faster after I am done dragging the internalFrame. It takes lot of time to bring up the internalframe and it's components at a new location after dragging. Is there a way to speed up the repainting. The following example just shows how the outline border is shown when you drag the internalFrame. As there are not enough components in the internal frame so shows up quickly. But when there are lots of components specially gif images inside the internalframe it takes time.
    /*************** MDITest ************/
    import javax.swing.*;
    * An application that displays a frame that
    * contains internal frames in an MDI type
    * interface.
    * @author Mike Foley
    public class MDITest extends Object {
    * Application entry point.
    * Create the frame, and display it.
    * @param args Command line parameter. Not used.
    public static void main( String args[] ) {
    try {
    UIManager.setLookAndFeel(
    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
    } catch( Exception ex ) {
    System.err.println( "Exception: " +
    ex.getLocalizedMessage() );
    JFrame frame = new MDIFrame( "MDI Test" );
    frame.pack();
    frame.setVisible( true );
    } // main
    } // MDITest
    /*********** MDIFrame.java ************/
    import java.awt.*;
    import java.awt.event.*;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    * A top-level frame. The frame configures itself
    * with a JDesktopPane in its content pane.
    * @author Mike Foley
    public class MDIFrame extends JFrame implements Serializable {
    * The desktop pane in our content pane.
    private JDesktopPane desktopPane;
    * MDIFrame, null constructor.
    public MDIFrame() {
    this( null );
    * MDIFrame, constructor.
    * @param title The title for the frame.
    public MDIFrame( String title ) {
    super( title );
    * Customize the frame for our application.
    protected void frameInit() {
    // Let the super create the panes.
    super.frameInit();
    JMenuBar menuBar = createMenu();
    setJMenuBar( menuBar );
    JToolBar toolBar = createToolBar();
    Container content = getContentPane();
    content.add( toolBar, BorderLayout.NORTH );
    desktopPane = new JDesktopPane();
    desktopPane.putClientProperty("JDesktopPane.dragMode", "outline");
    desktopPane.setPreferredSize( new Dimension( 400, 300 ) );
    content.add( desktopPane, BorderLayout.CENTER );
    } // frameInit
    * Create the menu for the frame.
    * <p>
    * @return The menu for the frame.
    protected JMenuBar createMenu() {
    JMenuBar menuBar = new JMenuBar();
    JMenu file = new JMenu( "File" );
    file.setMnemonic( KeyEvent.VK_F );
    JMenuItem item;
    file.add( new NewInternalFrameAction() );
    // file.add( new ExitAction() );
    menuBar.add( file );
    return( menuBar );
    } // createMenuBar
    * Create the toolbar for this frame.
    * <p>
    * @return The newly created toolbar.
    protected JToolBar createToolBar() {
    final JToolBar toolBar = new JToolBar();
    toolBar.setFloatable( false );
    toolBar.add( new NewInternalFrameAction() );
    // toolBar.add( new ExitAction() );
    return( toolBar );
    * Create an internal frame.
    * A JLabel is added to its content pane for an example
    * of content in the internal frame. However, any
    * JComponent may be used for content.
    * <p>
    * @return The newly created internal frame.
    public JInternalFrame createInternalFrame() {
    JInternalFrame internalFrame =
    new JInternalFrame( "Internal JLabel" );
    internalFrame.getContentPane().add(
    new JLabel( "Internal Frame Content" ) );
    internalFrame.setResizable( true );
    internalFrame.setClosable( true );
    internalFrame.setIconifiable( true );
    internalFrame.setMaximizable( true );
    internalFrame.pack();
    return( internalFrame );
    * An Action that creates a new internal frame and
    * adds it to this frame's desktop pane.
    public class NewInternalFrameAction extends AbstractAction {
    * NewInternalFrameAction, constructor.
    * Set the name and icon for this action.
    public NewInternalFrameAction() {
    super( "New", new ImageIcon( "new.gif" ) );
    * Perform the action, create an internal frame and
    * add it to the desktop pane.
    * <p>
    * @param e The event causing us to be called.
    public void actionPerformed( ActionEvent e ) {
    JInternalFrame internalFrame = createInternalFrame();
    desktopPane.add( internalFrame,
    JLayeredPane.DEFAULT_LAYER );
    } // NewInternalFrameAction
    } // MDIFrame
    I'll really appreciate for any help.
    Thank you

    Hi
    if you fill the ranges
    r_rundate-sign = 'I'.
    r_rundate-option = 'EQ'.
    r_rundate-low = '20080613'.
    r_rundate-high = '20080613'.
    APPEND r_rundate.
    EQ = 'equal', the select check the record with data EQ r_rundate-low.
    change EQ with BT  
    BT = between
    r_rundate-sign = 'I'.
    r_rundate-option = 'BT'.
    r_rundate-low = '20080613'.
    r_rundate-high = '20080613'.
    APPEND r_rundate.
    reward if useful, bye

  • Problems getting data from JMenuBar to JInternalFrame

    I have modified an example to show my problem. I am trying to take text input from the menu bar and print it into a JTextArea. I don't know how to reference the data in my ActionListener.
    The ActionListener is incomplete, but this is basically what I am trying to do:
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * InternalFrameDemo.java is a 1.4 application that requires:
    *   MyInternalFrame.java
    public class InternalFrameDemo extends JFrame
                                   implements ActionListener {
        JDesktopPane desktop;
        JTextField memAddrBox;
        JTextArea menuText;
        JTextArea frame;
        String textFieldString = " Input Text: ";
        ActionListener al;
        public InternalFrameDemo() {
            super("InternalFrameDemo");
            //Make the big window be indented 50 pixels from each edge
            //of the screen.
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            //Set up the GUI.
            desktop = new JDesktopPane(); //a specialized layered pane
            frame = createFrame(); //create first "window"
            setContentPane(desktop);
            setJMenuBar(createMenuBar());
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        protected JMenuBar createMenuBar() {
            JMenuBar menuBar = new JMenuBar();
            JLabel memAddrLabel = new JLabel(textFieldString);
            memAddrLabel.setLabelFor(memAddrBox);
            menuBar.add(memAddrLabel);
            JTextField memAddrBox = new JTextField();
            memAddrBox.addActionListener(this);
            memAddrBox.setActionCommand("chMemAddr");
            menuBar.add(memAddrBox);
            return menuBar;
        //React to menu selections.
        public void actionPerformed(ActionEvent e) {
            if ("chMemAddr".equals(e.getActionCommand())) 
                JMenuBar bar = getJMenuBar();
    //            JTextField memAddrBox = bar.getParent();
                String memStartString = memAddrBox.getText();
                update(memStartString);
        public void update(String temp)
            frame.setText(temp);
        //Create a new internal frame.
        protected JTextArea createFrame() {
            JInternalFrame frame = new JInternalFrame("Memory",true,true,true,true);      
            frame.setSize(650, 500);
            frame.setVisible(true);
            frame.setLocation(200, 0);
            desktop.add(frame);  
            JTextArea textArea = new JTextArea();
            frame.getContentPane().add("Center", textArea);
            textArea.setFont(new Font("SansSerif", Font.PLAIN, 12));
            textArea.setVisible(true);
            textArea.setText("Initial Text");
            return textArea;
        //Quit the application.
        protected void quit() {
            System.exit(0);
        public static void main(String[] args) {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            InternalFrameDemo frame = new InternalFrameDemo();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
    class MyInternalFrame extends JInternalFrame {
        static int openFrameCount = 0;
        static final int xOffset = 30, yOffset = 30;
        public MyInternalFrame() {
            super("Document #" + (++openFrameCount),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            setSize(300,300);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }I want to take the input from the "memAddrBox" and put it into the "frame" using the update() method. Probably a simple solution, but I have not found a similar problem in the Forums.

    I knew it had to be something simple, here is the fix I found:
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * InternalFrameDemo.java is a 1.4 application that requires:
    *   MyInternalFrame.java
    public class InternalFrameDemo extends JFrame
                                   implements ActionListener {
        JDesktopPane desktop;
        JTextField memAddrBox;
        JTextArea menuText;
        JTextArea frame;
        String textFieldString = " Input Text: ";
        ActionListener al;
        public InternalFrameDemo() {
            super("InternalFrameDemo");
            //Make the big window be indented 50 pixels from each edge
            //of the screen.
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            //Set up the GUI.
            desktop = new JDesktopPane(); //a specialized layered pane
            frame = createFrame(); //create first "window"
            setContentPane(desktop);
            setJMenuBar(createMenuBar());
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        protected JMenuBar createMenuBar() {
            JMenuBar menuBar = new JMenuBar();
            JLabel memAddrLabel = new JLabel(textFieldString);
            memAddrLabel.setLabelFor(memAddrBox);
            menuBar.add(memAddrLabel);
            JTextField memAddrBox = new JTextField();
            memAddrBox.addActionListener(this);
            memAddrBox.setActionCommand("chMemAddr");
            menuBar.add(memAddrBox);
            return menuBar;
        //React to menu selections.
        public void actionPerformed(ActionEvent e) {
            if ("chMemAddr".equals(e.getActionCommand())) 
               JTextField textField =
                 (JTextField)e.getSource();
                String memStartString = textField.getText();
                update(memStartString);
        public void update(String temp)
            frame.setText(temp);
        //Create a new internal frame.
        protected JTextArea createFrame() {
            JInternalFrame frame = new JInternalFrame("Memory",true,true,true,true);      
            frame.setSize(650, 500);
            frame.setVisible(true);
            frame.setLocation(200, 0);
            desktop.add(frame);  
            JTextArea textArea = new JTextArea();
            frame.getContentPane().add("Center", textArea);
            textArea.setFont(new Font("SansSerif", Font.PLAIN, 12));
            textArea.setVisible(true);
            textArea.setText("Initial Text");
            return textArea;
        //Quit the application.
        protected void quit() {
            System.exit(0);
        public static void main(String[] args) {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            InternalFrameDemo frame = new InternalFrameDemo();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
    class MyInternalFrame extends JInternalFrame {
        static int openFrameCount = 0;
        static final int xOffset = 30, yOffset = 30;
        public MyInternalFrame() {
            super("Document #" + (++openFrameCount),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            setSize(300,300);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }Note the e.getSource() change in the ActionListener.

  • Opening a Second JInternalFrame

    Below I have two classes InternalFrameDemo instantiates MyInternalFrame (extends javax.swing.JInternalFrame ) in doing this the application creates a JDesktopPane and creates a MyInternalFrame to put in it.
    What I want to happen is when the jButton1 on the MyInternalFrame is clicked is for a second MyInternalFrame to open and the first MyInternalFrame to close is this possible?
    I think that I would need to have the action Method in MyInternalFrame trigger a method call in the InternalFrameDemo and do the closing and opening of new MyInternalFrame from there?
    Thanks
    package components;
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import java.awt.event.*;
    import java.awt.*;
    public class InternalFrameDemo extends JFrame
    implements ActionListener {
    JDesktopPane desktop;
    public InternalFrameDemo() {
    super("InternalFrameDemo");
    int inset = 50;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setBounds(inset, inset,
    screenSize.width - inset*2,
    screenSize.height - inset*2);
    desktop = new JDesktopPane();
    createFrame();
    setContentPane(desktop);
    setJMenuBar(createMenuBar());
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    protected JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Document");
    menu.setMnemonic(KeyEvent.VK_D);
    menuBar.add(menu);
    JMenuItem menuItem = new JMenuItem("New");
    menuItem.setMnemonic(KeyEvent.VK_N);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_N, ActionEvent.ALT_MASK));
    menuItem.setActionCommand("new");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    return menuBar;
    public void actionPerformed(ActionEvent e) {
    if ("new".equals(e.getActionCommand())) {
    createFrame();
    } else {
    quit();
    protected void createFrame() {
    MyInternalFrame frame = new MyInternalFrame();
    frame.setVisible(true);
    desktop.add(frame);
    try {
    frame.setSelected(true);
    } catch (java.beans.PropertyVetoException e) {}
    MyInternalFrame frame2 = new MyInternalFrame();
    frame.setVisible(true);
    desktop.add(frame2);
    try {
    frame2.setSelected(true);
    } catch (java.beans.PropertyVetoException e) {}
    public void closeWin(){
    protected void quit() {
    System.exit(0);
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    InternalFrameDemo frame = new InternalFrameDemo();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public static void main(String[] args) {     
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    /*MyInternalFrame */
    package components;
    public class MyInternalFrame extends javax.swing.JInternalFrame {
    @SuppressWarnings("unchecked")
    private void initComponents() {
    jButton1 = new javax.swing.JButton();
    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(152, 152, 152)
    .addComponent(jButton1)
    .addContainerGap(169, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(108, 108, 108)
    .addComponent(jButton1)
    .addContainerGap(147, Short.MAX_VALUE))
    pack();
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    this.dispose();
    private javax.swing.JButton jButton1;
    }

    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
    I think that I would need to have the action Method in MyInternalFrame trigger a method call in the InternalFrameDemo and do the closing and opening of new MyInternalFrame from there?Correct. So give it a try and see what happens.

  • JInternalFrame problem

    Hello,
    I've got a JFrame class like this :
    public class FrameTest extends JFrame
    public JFrameTest()
    JDesktopPane desktop = new JDesktopPane();
    this.setContentPane(desktop);
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    Test panelTest = new Test();
    Container contentPane = getContentPane();
    contentPane.setLayout(new GridBagLayout());
    contentPane.add(panelTest , panelTest .gridBagConstraints);
    At this point, I've got no problem. My frame is visible and my panel is inside.
    On the listener of a button of my panel, I want to open an JInternalFrame.
    My JInternal class is like this :
    public class JInternalFrameTest extends JInternalFrame
    public JInternalFrameTest(String title)
    super(title, true, true, true);
    this.pack();
    this.setVisible(true);
    The code of the listener is like this :
    JInternalFrameTest internalFrameTest = new JInternalFrameTest("TITLE");
    frameTest.getContentPane().add(internalFrameTest ); //frameTest is a reference on the main frame (instance of JFrameTest)
    At the execution of my application, when the listener starts, the JInternalFrameTest is created but near the panel not on the top. Moreover, I can't specify the position and the size of my JInternalFrameTest object because when I specify them in the JInternalFrameTest class, nothing happen.
    If you have a solution for me because I don't understand what I have forgotten.
    Thanks.

    michal1101 wrote:
    As I understand, in mvc - if the view is not updated , so it's a bug.What are you trying to say here? There are two options: there is a bug in Java that millions of people have missed, and you've somehow found OR you're misunderstanding something. Which do you think is more likely?
    Does anyone had that kind of mvc problem?No. Either something in your code is wrong, or you're misunderstanding something pretty basic.
    Ps. It's difficult to send an example, since i can't send the code from work.Then you understand that it's difficult to help you, right? Without seeing code, we can't tell you what's wrong with your code. You were asked for an SSCCE, which shouldn't contain any extra "company-sensitive" code. It's your call, but claiming that your problems must be a "bug" and refusing to post any code won't get you very far.

  • Problem with JInternalFrame

    Hii there,
    I'm having a problem with JInternalFrame, that is, when I'm trying to open multiple frames, it is overlapping one another and sometimes one of them disappears, I did something like this,
    dpane=new JDesktopPane();                                                 
                            dpane.setDesktopManager(new DefaultDesktopManager());
                            dpane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                            iframe=new JInternalFrame("Title" ,true,true,true,true);  
                            //iframe.setPreferredSize(new Dimension(1010,800));
                            iframe.setResizable(false);
                            vScrollPane = new JScrollPane(viewPanel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                       
                            iframe.setPreferredSize(new Dimension(1010,800));
                            iframe.setLocation(0,1);
                            iframe.setVisible(true);
                            iframe.show();
                            iframe.getContentPane().add(vScrollPane,BorderLayout.EAST);                      
                            iframe.getContentPane().add(hScrollBar,BorderLayout.SOUTH);
                            iframe.moveToFront();
                            iframe.setFocusable(true);
                            iframe.pack();
                            dpane.add(iframe);                                      
                            getContentPane().add(dpane);could u someone plz help me !
    Dev

    [How to Use Internal Frames|http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html]

  • Undecorated JInternalFrame becomes decorated by itself.

    Hi,
    I’m facing a problem with JInternalFrame implementation. I have made the JInternalFrame undecorated, so that the title bar and border of the JInternalFrame gets removed. The problem occurs in the following scenario.
    *1)     Execute the program in a Windows 7 machine.*
    *•     At this point the JInternalFrame remains undecorated.*
    *2)     Access the Windows 7 machine using remote desktop sharing from another machine.*
    *•     Now the title bar and border of the internal frame becomes visible.*
    This issue occurs only in Windows 7 machine, and not in Windows XP. You can access the Windows 7 machine using remote desktop sharing from another Windows 7 machine or Windows XP machine.
    Also if you access the machine using remote desktop sharing first, and then execute the program, the JInternalFrame remains undecorated.
    Steps to reproduce
    Step 1: Execute the application in a Windows 7 machine.
    Step 2: Access the Windows 7 machine using remote desktop sharing from another Windows 7 or Windows XP machine.
    Step 3: Check the GUI of the application
    Result :- The title bar and border of the undecorated JInternalFrame becomes visible.
    If anyone has faced this issue or if anyone has a solution for this issue, kindly share your thoughts.
    A sample code using which you can reproduce this issue is given below.
    * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * - Redistributions of source code must retain the above copyright
    * notice, this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and/or other materials provided with the distribution.
    * - Neither the name of Oracle or the names of its
    * contributors may be used to endorse or promote products derived
    * from this software without specific prior written permission.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
    import javax.swing.plaf.basic.BasicInternalFrameUI;
    import java.awt.event.*;
    import java.awt.*;
    * InternalFrameDemo.java requires:
    * MyInternalFrame.java
    public class InternalFrameDemo extends JFrame
    implements ActionListener {
    JDesktopPane desktop;
    public InternalFrameDemo() {
    super("InternalFrameDemo");
    //Make the big window be indented 50 pixels from each edge
    //of the screen.
    int inset = 50;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setBounds(inset, inset,
    screenSize.width - inset*2,
    screenSize.height - inset*2);
    //Set up the GUI.
    desktop = new JDesktopPane(); //a specialized layered pane
    createFrame(); //create first "window"
    setContentPane(desktop);
    setJMenuBar(createMenuBar());
    //Make dragging a little faster but perhaps uglier.
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    protected JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    //Set up the lone menu.
    JMenu menu = new JMenu("Document");
    menu.setMnemonic(KeyEvent.VK_D);
    menuBar.add(menu);
    //Set up the first menu item.
    JMenuItem menuItem = new JMenuItem("New");
    menuItem.setMnemonic(KeyEvent.VK_N);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_N, ActionEvent.ALT_MASK));
    menuItem.setActionCommand("new");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    //Set up the second menu item.
    menuItem = new JMenuItem("Quit");
    menuItem.setMnemonic(KeyEvent.VK_Q);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_Q, ActionEvent.ALT_MASK));
    menuItem.setActionCommand("quit");
    menuItem.addActionListener(this);
    menu.add(menuItem);
    return menuBar;
    //React to menu selections.
    public void actionPerformed(ActionEvent e) {
    if ("new".equals(e.getActionCommand())) { //new
    createFrame();
    } else { //quit
    quit();
    //Create a new internal frame.
    protected void createFrame() {
    MyInternalFrame frame = new MyInternalFrame();
    frame.setVisible(true); //necessary as of 1.3
    desktop.add(frame);
    try {
    frame.setSelected(true);
    } catch (java.beans.PropertyVetoException e) {}
    //Quit the application.
    protected void quit() {
    System.exit(0);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    InternalFrameDemo frame = new InternalFrameDemo();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Display the window.
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    /* Used by InternalFrameDemo.java. */
    @SuppressWarnings("serial")
    class MyInternalFrame extends JInternalFrame {
    static int openFrameCount = 0;
    static final int xOffset = 30, yOffset = 30;
    public MyInternalFrame() {
    super("Document #" + (++openFrameCount),
    true, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    //...Create the GUI and put it in the window...
    //...Then set the window size or call pack...
    setSize(300,300);
    // Undecorating the internal frame
    BasicInternalFrameTitlePane titlePane =
    (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) this.getUI()).
    getNorthPane();
    this.remove(titlePane);
    this.setBorder(null);
    //Set the window's location.
    setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }

    Thanks a lot for that lead Walter.
    Actually when I tried to override updateUI(), I got a NullPoinerException. Instead of that, I tried overriding the paintComponent() method, did the undecoration part in that method and, and called super.paintComponent(g) inside the method. Then the issue was resolved.
    Once again, thanks for the quick reply.

  • JInternalFrame size issue

    I'm trying to make an IDE, and have started trying to create a nopepad type editor. My problem occurs when clicking new to create a new internal frame, the frame is created to be the same size as a maximised internal frame would be. I've tryed adding setBounds, setSize, setPreferredSize, setMaximumSize, setMinimumSize functions to the frame, but to no avail. This is the full listing of my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.text.*;
       Java IDE (Integrated Development Environment)
       IDE.java
       Sets up constants and main viewing frame.
       Advanced 2nd Year HND Project
       @author Mark A. Standen
       @Version 0.2 18/04/2002
    //=========================================================
    //   Main (public class)
    //=========================================================
    public class IDE extends JFrame
          Application Wide Constants
       /**   The Name of the Application   */
       private static final String APPLICATION_NAME = "Java IDE";
       /**   The Application Version   */
       private static final String APPLICATION_VERSION = "0.2";
       /**   The Inset from the edges of the screen of the main viewing frame   */
       private static final int INSET = 50;
       /**   The main frame   */
       private static IDE frame;
          MAIN
       public static void main (String[] Arguments)
          //Adds Cross-Platform functionality by adapting GUI
          try
             UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
             //Adapts to current system look and feel - e.g. windows
          catch (Exception e) {System.err.println("Can't set look and feel: " + e);}
          frame = new IDE();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
          This Constructor creates an instance of Main, the main view frame.
          @param sizeX Width of the main view Frame in pixels
          @param sizeY Height of the main view Frame in pixels
       public IDE()
          super (APPLICATION_NAME + " (Version " + APPLICATION_VERSION + ")");
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          this.setBounds( INSET, INSET, screenSize.width - (INSET * 2), screenSize.height - (INSET * 3) );
          JDesktopPane mainPane = new JDesktopPane();
          mainPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
          this.setContentPane(mainPane);
          this.getContentPane().setLayout( new BorderLayout() );
          this.getContentPane().add("North", new ToolBar() );
    //===================================================================
    //   ToolBar (private class)
    //===================================================================
       private class ToolBar extends JToolBar implements ActionListener
          /*   Create toolbar buttons   */
          private JButton newBox;
          private JButton load;
          private JButton save;
             Creates an un-named toolbar,
             with New, Load, and Save options.
          public ToolBar () {
                Use to make toolbar look nice later on
                ImageIcon imageNew = new ImageIcon("imgNew.gif");
                JButton toolbarNew = new JButton(imageNew);  
                ImageIcon imageLoad = new ImageIcon("imgLoad.gif");
                JButton toolbarLoad = new JButton(imageLoad);  
                ImageIcon imageSave = new ImageIcon("imgSave.gif");
                JButton toolbarSave = new JButton(imageSave);
                temp toolbar buttons for now
             newBox = new JButton("New");
             load = new JButton("Load");
             save = new JButton("Save");
             this.setFloatable(false);
             this.setOrientation(JToolBar.HORIZONTAL);
             this.add(newBox);
             this.add(load);
             this.add(save);
             newBox.addActionListener(this);
             load.addActionListener(this);
             save.addActionListener(this);
             Checks for button presses, and calls the relevant functions
          public void actionPerformed (ActionEvent event)
             Object source = event.getSource();
             /*   If new has been clicked   */
             if (source == newBox)
                TextDisplayFrame textBox = new TextDisplayFrame();
                Rectangle rect = this.getParent().getBounds();
                textBox.setBounds( rect.x - INSET, rect.y - INSET, rect.width - (INSET * 2), rect.height - (INSET * 2) );
                this.getParent().add(textBox);
                textBox.setVisible(true);
             /*   If load has been clicked   */
             else if (source == load)
                TextDisplayFrame textBox = new TextDisplayFrame();
                frame.getContentPane().add(textBox);
                System.out.println(textBox + "");
                textBox.loadDoc();
             /*   If save has been clicked   */
             else if (source == save)
    //====================================================================
    //   Menu (private class)
    //====================================================================
       private class Menu extends JMenu
          public Menu()
             JMenuBar menuBar = new JMenuBar();
             JMenu menu = new JMenu("Document");
             menu.setMnemonic(KeyEvent.VK_D);
             JMenuItem menuItem = new JMenuItem("New");
             menuItem.setMnemonic(KeyEvent.VK_N);
             menuItem.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      TextDisplayFrame textBox = new TextDisplayFrame();
                      //this.getContentPane().add(textBox);
             menu.add(menuItem);
             menuBar.add(menu);
             menuBar.setVisible(true);
    //====================================================================
    //   TextDisplayFrame (private class)
    //====================================================================
       private class TextDisplayFrame extends JInternalFrame
          /**   The Default Title of an internal pane   */
          private static final String DEFAULT_TITLE = "untitled";
          /**   Path to the current File   */
          private File filePath = new File ("C:" + File.separatorChar + "test.txt");
          /*   Swing Components   */
          private JTextArea mainTextArea;
          private JScrollPane scrollPane;
             Creates a TextDisplayFrame with the given arguments
             @param title Title of the TextDisplayFrame
          public TextDisplayFrame(String title)
             super(title, true, true, true, true); //creates resizable, closable, maximisable, and iconafiable internal frame
             this.setContentPane( textBox() );
             this.setPreferredSize( new Dimension (150, 100) );
             this.setMaximumSize( new Dimension (300, 300) );
             this.setVisible(true);
             Creates a resizable frame with the default title
          public TextDisplayFrame()
             this(DEFAULT_TITLE);
             Creates a blank, resizable central text area, for the entering of text
             @return Returns a JPanel object
          private JPanel textBox()
             mainTextArea = new JTextArea( new PlainDocument() );
             mainTextArea.setLineWrap(false);
             mainTextArea.setFont( new Font("monospaced", Font.PLAIN, 14) );
             scrollPane = new JScrollPane( mainTextArea );
             JPanel pane = new JPanel();
             BorderLayout bord = new BorderLayout();
             pane.setLayout(bord);
             pane.add("Center", scrollPane);
             return pane;
             @return Returns a JTextComponent to be used as document object
          public JTextComponent getDoc()
             return mainTextArea;
          public void loadDoc()
             /* Create blank Document */
             Document textDoc = new PlainDocument();
             /* Attempt to load the document in the filePath into the blank Document object*/
             try
                Reader fileInput = new FileReader(filePath);
                char[] charBuffer = new char[1000];
                int numChars;
                while (( numChars = fileInput.read( charBuffer, 0, charBuffer.length )) != -1 )
                   textDoc.insertString(textDoc.getLength(), new String( charBuffer, 0, numChars ), null);
             catch (IOException error) {System.out.println(error); }
             catch (BadLocationException error) {System.out.println(error); }
             /* Set the loaded document to be the text of the JTextArea */
             this.getDoc().setDocument( textDoc );
    }I would appreciate all/any help that can be offered.

    i have tried out your source and have made some modifications and now it works fine.
    move the desktoppane to be a private variable of the class, so that you can add the InternalFrame to it directly. also the setBounds() needs to be given lil' corrections to c that the InternalFrame appear on the visible area.
    i'm posting entire source just to make sure you don't confuse abt the changes. This is a working version. Hope it serves.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.text.*;
    Java IDE (Integrated Development Environment)
    IDE.java
    Sets up constants and main viewing frame.
    Advanced 2nd Year HND Project
    @author Mark A. Standen
    @Version 0.2 18/04/2002
    //=========================================================
    // Main (public class)
    //=========================================================
    public class IDE extends JFrame
    Application Wide Constants
    /** The Name of the Application */
    private static final String APPLICATION_NAME = "Java IDE";
    /** The Application Version */
    private static final String APPLICATION_VERSION = "0.2";
    /** The Inset from the edges of the screen of the main viewing frame */
    private static final int INSET = 50;
    /** The main frame */
    private static IDE frame;
    /*********** CHANGED HERE ****************/
    private JDesktopPane mainPane;
    /*********** END CHANGE ****************/
    MAIN
    public static void main (String[] Arguments)
    //Adds Cross-Platform functionality by adapting GUI
    try
    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
    //Adapts to current system look and feel - e.g. windows
    catch (Exception e) {System.err.println("Can't set look and feel: " + e);}
    frame = new IDE();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    This Constructor creates an instance of Main, the main view frame.
    @param sizeX Width of the main view Frame in pixels
    @param sizeY Height of the main view Frame in pixels
    public IDE()
    super (APPLICATION_NAME + " (Version " + APPLICATION_VERSION + ")");
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setBounds( INSET, INSET, screenSize.width - (INSET * 2), screenSize.height - (INSET * 3) );
              /*********** CHANGED HERE ****************/
    mainPane = new JDesktopPane();
    mainPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    //this.setContentPane(mainPane);
    this.getContentPane().setLayout( new BorderLayout() );
    this.getContentPane().add(new ToolBar(), java.awt.BorderLayout.NORTH);
         this.getContentPane().add(mainPane, java.awt.BorderLayout.CENTER);
         /*********** END CHANGE ****************/
    //===================================================================
    // ToolBar (private class)
    //===================================================================
    private class ToolBar extends JToolBar implements ActionListener
    /* Create toolbar buttons */
    private JButton newBox;
    private JButton load;
    private JButton save;
    Creates an un-named toolbar,
    with New, Load, and Save options.
    public ToolBar () {
    Use to make toolbar look nice later on
    ImageIcon imageNew = new ImageIcon("imgNew.gif");
    JButton toolbarNew = new JButton(imageNew);
    ImageIcon imageLoad = new ImageIcon("imgLoad.gif");
    JButton toolbarLoad = new JButton(imageLoad);
    ImageIcon imageSave = new ImageIcon("imgSave.gif");
    JButton toolbarSave = new JButton(imageSave);
    temp toolbar buttons for now
    newBox = new JButton("New");
    load = new JButton("Load");
    save = new JButton("Save");
    this.setFloatable(false);
    this.setOrientation(JToolBar.HORIZONTAL);
    this.add(newBox);
    this.add(load);
    this.add(save);
    newBox.addActionListener(this);
    load.addActionListener(this);
    save.addActionListener(this);
    Checks for button presses, and calls the relevant functions
    public void actionPerformed (ActionEvent event)
    Object source = event.getSource();
    /* If new has been clicked */
    if (source == newBox)
    TextDisplayFrame textBox = new TextDisplayFrame();
    Rectangle rect = mainPane.getBounds();
    /*********** CHANGED HERE ****************/
    //textBox.setBounds( rect.x - INSET, rect.y - INSET, rect.width - (INSET * 2), rect.height - (INSET * 2) );
    //this.getParent().add(textBox);
    mainPane.add(textBox, javax.swing.JLayeredPane.DEFAULT_LAYER);
    textBox.setBounds(rect.x, rect.y, 500, 500);
    /*********** END CHANGE ****************/
    textBox.setVisible(true);
    /* If load has been clicked */
    else if (source == load)
    TextDisplayFrame textBox = new TextDisplayFrame();
    frame.getContentPane().add(textBox);
    System.out.println(textBox + "");
    textBox.loadDoc();
    /* If save has been clicked */
    else if (source == save)
    //====================================================================
    // Menu (private class)
    //====================================================================
    private class Menu extends JMenu
    public Menu()
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Document");
    menu.setMnemonic(KeyEvent.VK_D);
    JMenuItem menuItem = new JMenuItem("New");
    menuItem.setMnemonic(KeyEvent.VK_N);
    menuItem.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    TextDisplayFrame textBox = new TextDisplayFrame();
    //this.getContentPane().add(textBox);
    menu.add(menuItem);
    menuBar.add(menu);
    menuBar.setVisible(true);
    //====================================================================
    // TextDisplayFrame (private class)
    //====================================================================
    private class TextDisplayFrame extends JInternalFrame
    /** The Default Title of an internal pane */
    private static final String DEFAULT_TITLE = "untitled";
    /** Path to the current File */
    private File filePath = new File ("C:" + File.separatorChar + "test.txt");
    /* Swing Components */
    private JTextArea mainTextArea;
    private JScrollPane scrollPane;
    Creates a TextDisplayFrame with the given arguments
    @param title Title of the TextDisplayFrame
    public TextDisplayFrame(String title)
    super(title, true, true, true, true); //creates resizable, closable, maximisable, and iconafiable internal frame
    this.setContentPane( textBox() );
    this.setPreferredSize( new Dimension (150, 100) );
    /*********** CHANGED HERE ****************/
    //this.setMaximumSize( new Dimension (300, 300) );
    this.setNormalBounds(new Rectangle(300,300));
    /*********** END CHANGE ****************/
    this.setVisible(true);
    Creates a resizable frame with the default title
    public TextDisplayFrame()
    this(DEFAULT_TITLE);
    Creates a blank, resizable central text area, for the entering of text
    @return Returns a JPanel object
    private JPanel textBox()
    mainTextArea = new JTextArea( new PlainDocument() );
    mainTextArea.setLineWrap(false);
    mainTextArea.setFont( new Font("monospaced", Font.PLAIN, 14) );
    scrollPane = new JScrollPane( mainTextArea );
    JPanel pane = new JPanel();
    BorderLayout bord = new BorderLayout();
    pane.setLayout(bord);
    pane.add("Center", scrollPane);
    return pane;
    @return Returns a JTextComponent to be used as document object
    public JTextComponent getDoc()
    return mainTextArea;
    public void loadDoc()
    /* Create blank Document */
    Document textDoc = new PlainDocument();
    /* Attempt to load the document in the filePath into the blank Document object*/
    try
    Reader fileInput = new FileReader(filePath);
    char[] charBuffer = new char[1000];
    int numChars;
    while (( numChars = fileInput.read( charBuffer, 0, charBuffer.length )) != -1 )
    textDoc.insertString(textDoc.getLength(), new String( charBuffer, 0, numChars ), null);
    catch (IOException error) {System.out.println(error); }
    catch (BadLocationException error) {System.out.println(error); }
    /* Set the loaded document to be the text of the JTextArea */
    this.getDoc().setDocument( textDoc );

  • JInternalFrame listeners stops working if more than one opened ?

    Hi all, I'm trying to write some kind of chat program for my term project
    I'm really stucked at this point.
    I connect to a server, get chat room lists, join to a chat room, there's no problem at this first chat room ( internalFrame ), everything is fine ( I can refresh user list with pressing F5, send messages through send message button ), when I join another chat room ( second internalFrame ), problems start to occur, I can refresh with pressing F5, but I cannot send messages to server, server recieves my messages as null messages, still I can send messages with the first internal frame I opened but cannot refresh with pressing F5 in the first frame !
    here are my codes for certain parts
    main class
    public class ChatClientMain extends JFrame
                                   implements ActionListener {
    // items etc here
        public ChatClientMain() {
            super("project");
            connectedToServer=false;
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            desktopPane = new JDesktopPane(); //a specialized layered pane
            setContentPane(desktopPane);
            desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        public void actionPerformed(ActionEvent event)
           if ( event.getSource() == connectMenuItem )
                       try
                            connectionSocket = new Socket(serverName,serverPort);
                                    inFromServer = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                            outToServer = new PrintStream(connectionSocket.getOutputStream());
                       catch (IOException e)
                            JOptionPane.showMessageDialog(null, "Cannot connect to server\nProgram will exit", "Cannot connect", JOptionPane.ERROR_MESSAGE);
                            e.printStackTrace();
                            System.exit(1);
                       createServerFrame(outToServer);
                       new ConnectionToServer(nickName,connectionSocket,inFromServer,outToServer).start();
                    // other actions etc.
        protected static void createChatFrame(String roomName)
            ChatFrame frame = new ChatFrame(roomName);
            frame.setVisible(true);
            desktopPane.add(frame);
            try
                frame.setSelected(true);
            catch (java.beans.PropertyVetoException e) {}
            outToServer.println("GET USER LIST"+roomName);
    here's thread for connection to server
    public class ConnectionToServer extends Thread
         public ConnectionToServer(String nick,Socket socket,BufferedReader bf,PrintStream ps)
              nickName=nick;
              inFromServer = bf;
              outToServer = ps;
              connectionSocket=socket;
              ChatClientMain.connectedToServer=true;
              outToServer.println("CONNECTION INITIALIZATION"+nickName);
         public void run()
              try
                   while(true)
                        recievedMessage = inFromServer.readLine();
                        System.out.println(recievedMessage);
                        if (recievedMessage.startsWith("CHATROOM")) // problem here ( in split function ), cannot parse since recieves null message
                             String[] chatRoomMessageParts = recievedMessage.split("#");
                             String chatRoomName = chatRoomMessageParts[1];
                             String chatRoomMessage = chatRoomMessageParts[2];
                             System.out.println("room name : " + chatRoomName + " message : " + chatRoomMessage);
                                    //some other protocols I implemented here
                        if (!roomListRecieving || ! userListRecieving)
                             ServerFrame.serverConversation.append(recievedMessage + "\n");
              catch (IOException e)
                   e.printStackTrace();
    code for chat frame, which works for one, but not for two :S
    public class ChatFrame extends JInternalFrame
         private static final long serialVersionUID = 1L;
         static int openFrameCount = 0;
         static int xOffset = 60;
         static int yOffset = 60;
         JPanel chatRoomContent;
         JLabel chatRoom;
         JLabel users;
         JTextArea roomConversation;
         static JList roomUserList;
         JScrollPane conversationScroll;
         JScrollPane userListScroll;
         JTextField roomMessage;
         JButton roomMessageButton;
         static DefaultListModel userListModel;
         ListSelectionListener userListListener;
         public ChatFrame(final String roomName)
              super("Chat Room : " + roomName,
                        true, //resizable
                        true, //closable
                        true, //maximizable
                        true);//iconifiable
              openFrameCount++;
              chatRoomContent = new JPanel();
              chatRoomContent.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              chatRoomContent.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
    // I set proper values for c everytime I add new item to pane
              chatRoom = new JLabel("Now chatting in : " + roomName);
              chatRoomContent.add(chatRoom,c);
              users = new JLabel("User List");
              chatRoomContent.add(users,c);
              roomConversation = new JTextArea();
              roomConversation.setEditable(false);
              conversationScroll = new JScrollPane();
              conversationScroll.setViewportView(roomConversation);
              chatRoomContent.add(conversationScroll,c);
              userListModel = new DefaultListModel();
              userListListener = new ListSelectionListener(){
                   public void valueChanged(ListSelectionEvent event) {
                        JList lsm = (JList) event.getSource();
                        if(event.getValueIsAdjusting())
                             roomConversation.append("Starting chat with " + lsm.getSelectedValue() + "\n");
                             String chatName = (String) lsm.getSelectedValue();
                             ChatClientMain.createPrivateChatFrame(chatName);
              roomUserList = new JList();
    //list props set here
              chatRoomContent.add(userListScroll,c);
              roomMessage = new JTextField();
              chatRoomContent.add(roomMessage,c);
              roomMessageButton = new JButton("Send Message");
              roomMessageButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        if (!roomMessage.getText().equals(""))
                             String message = ChatClientMain.nickName + " : " + roomMessage.getText() + "\n"; // message person wrote
                             roomConversation.append(message);
                             roomMessage.setText("");
                             ChatClientMain.outToServer.println("CHATROOM#"+roomName+"#"+message);  // message I'm sending to server
              chatRoomContent.add(roomMessageButton,c);
              this.setFocusable(true);
              this.addKeyListener(new KeyListener() {
                   @Override
                   public void keyPressed(KeyEvent arg0) {
                        int keyNo = arg0.getKeyCode();
                        if ( keyNo == KeyEvent.VK_F5)
                             ChatClientMain.outToServer.println("GET USER LIST"+roomName);       //refresh part with works just for the last internal frame I opened
                   //other methods
              this.addInternalFrameListener(new InternalFrameListener() {
                   public void internalFrameClosed(InternalFrameEvent arg0) {
                        ChatClientMain.leaveRoom(roomName);
                            //other methods here
              add(chatRoomContent);
              setSize(525,525);
              setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }I would really be thankful if you help..

    Hi all, I'm trying to write some kind of chat program for my term project
    I'm really stucked at this point.
    I connect to a server, get chat room lists, join to a chat room, there's no problem at this first chat room ( internalFrame ), everything is fine ( I can refresh user list with pressing F5, send messages through send message button ), when I join another chat room ( second internalFrame ), problems start to occur, I can refresh with pressing F5, but I cannot send messages to server, server recieves my messages as null messages, still I can send messages with the first internal frame I opened but cannot refresh with pressing F5 in the first frame !
    here are my codes for certain parts
    main class
    public class ChatClientMain extends JFrame
                                   implements ActionListener {
    // items etc here
        public ChatClientMain() {
            super("project");
            connectedToServer=false;
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            desktopPane = new JDesktopPane(); //a specialized layered pane
            setContentPane(desktopPane);
            desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        public void actionPerformed(ActionEvent event)
           if ( event.getSource() == connectMenuItem )
                       try
                            connectionSocket = new Socket(serverName,serverPort);
                                    inFromServer = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                            outToServer = new PrintStream(connectionSocket.getOutputStream());
                       catch (IOException e)
                            JOptionPane.showMessageDialog(null, "Cannot connect to server\nProgram will exit", "Cannot connect", JOptionPane.ERROR_MESSAGE);
                            e.printStackTrace();
                            System.exit(1);
                       createServerFrame(outToServer);
                       new ConnectionToServer(nickName,connectionSocket,inFromServer,outToServer).start();
                    // other actions etc.
        protected static void createChatFrame(String roomName)
            ChatFrame frame = new ChatFrame(roomName);
            frame.setVisible(true);
            desktopPane.add(frame);
            try
                frame.setSelected(true);
            catch (java.beans.PropertyVetoException e) {}
            outToServer.println("GET USER LIST"+roomName);
    here's thread for connection to server
    public class ConnectionToServer extends Thread
         public ConnectionToServer(String nick,Socket socket,BufferedReader bf,PrintStream ps)
              nickName=nick;
              inFromServer = bf;
              outToServer = ps;
              connectionSocket=socket;
              ChatClientMain.connectedToServer=true;
              outToServer.println("CONNECTION INITIALIZATION"+nickName);
         public void run()
              try
                   while(true)
                        recievedMessage = inFromServer.readLine();
                        System.out.println(recievedMessage);
                        if (recievedMessage.startsWith("CHATROOM")) // problem here ( in split function ), cannot parse since recieves null message
                             String[] chatRoomMessageParts = recievedMessage.split("#");
                             String chatRoomName = chatRoomMessageParts[1];
                             String chatRoomMessage = chatRoomMessageParts[2];
                             System.out.println("room name : " + chatRoomName + " message : " + chatRoomMessage);
                                    //some other protocols I implemented here
                        if (!roomListRecieving || ! userListRecieving)
                             ServerFrame.serverConversation.append(recievedMessage + "\n");
              catch (IOException e)
                   e.printStackTrace();
    code for chat frame, which works for one, but not for two :S
    public class ChatFrame extends JInternalFrame
         private static final long serialVersionUID = 1L;
         static int openFrameCount = 0;
         static int xOffset = 60;
         static int yOffset = 60;
         JPanel chatRoomContent;
         JLabel chatRoom;
         JLabel users;
         JTextArea roomConversation;
         static JList roomUserList;
         JScrollPane conversationScroll;
         JScrollPane userListScroll;
         JTextField roomMessage;
         JButton roomMessageButton;
         static DefaultListModel userListModel;
         ListSelectionListener userListListener;
         public ChatFrame(final String roomName)
              super("Chat Room : " + roomName,
                        true, //resizable
                        true, //closable
                        true, //maximizable
                        true);//iconifiable
              openFrameCount++;
              chatRoomContent = new JPanel();
              chatRoomContent.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              chatRoomContent.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
    // I set proper values for c everytime I add new item to pane
              chatRoom = new JLabel("Now chatting in : " + roomName);
              chatRoomContent.add(chatRoom,c);
              users = new JLabel("User List");
              chatRoomContent.add(users,c);
              roomConversation = new JTextArea();
              roomConversation.setEditable(false);
              conversationScroll = new JScrollPane();
              conversationScroll.setViewportView(roomConversation);
              chatRoomContent.add(conversationScroll,c);
              userListModel = new DefaultListModel();
              userListListener = new ListSelectionListener(){
                   public void valueChanged(ListSelectionEvent event) {
                        JList lsm = (JList) event.getSource();
                        if(event.getValueIsAdjusting())
                             roomConversation.append("Starting chat with " + lsm.getSelectedValue() + "\n");
                             String chatName = (String) lsm.getSelectedValue();
                             ChatClientMain.createPrivateChatFrame(chatName);
              roomUserList = new JList();
    //list props set here
              chatRoomContent.add(userListScroll,c);
              roomMessage = new JTextField();
              chatRoomContent.add(roomMessage,c);
              roomMessageButton = new JButton("Send Message");
              roomMessageButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        if (!roomMessage.getText().equals(""))
                             String message = ChatClientMain.nickName + " : " + roomMessage.getText() + "\n"; // message person wrote
                             roomConversation.append(message);
                             roomMessage.setText("");
                             ChatClientMain.outToServer.println("CHATROOM#"+roomName+"#"+message);  // message I'm sending to server
              chatRoomContent.add(roomMessageButton,c);
              this.setFocusable(true);
              this.addKeyListener(new KeyListener() {
                   @Override
                   public void keyPressed(KeyEvent arg0) {
                        int keyNo = arg0.getKeyCode();
                        if ( keyNo == KeyEvent.VK_F5)
                             ChatClientMain.outToServer.println("GET USER LIST"+roomName);       //refresh part with works just for the last internal frame I opened
                   //other methods
              this.addInternalFrameListener(new InternalFrameListener() {
                   public void internalFrameClosed(InternalFrameEvent arg0) {
                        ChatClientMain.leaveRoom(roomName);
                            //other methods here
              add(chatRoomContent);
              setSize(525,525);
              setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }I would really be thankful if you help..

  • "AWT-EventQueue-0" java.lang.NullPointerException and JInternalFrame

    I have two classes one with main method second with GUI methods (JFrame, JInternalFrame). When I call method to start second JInternalFrame from main everything is working but if i call it form any other method i get:
    Exception in thread "main" java.lang.NullPointerException
    at pkg1.GUI.createFrame(GUI.java:123)
    at pkg1.GUI.startFrame2(GUI.java:66)
    at pkg1.Top.cos(Top.java:25)
    at pkg1.Top.main(Top.java:20) My code:
    GUI class
    package pkg1;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Toolkit;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.plaf.basic.BasicInternalFrameUI;
    import oracle.jdeveloper.layout.XYLayout;
    public class GUI
        public JDesktopPane desktop;
        private XYLayout xYLayout1 = new XYLayout();
        public int openFrameCount = 0;
        JFrame f = new JFrame();
        public void GUII()  // Prepare JFrame
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(500, 600);
            f.setVisible(true);
        public void startFrame()
            desktop = new JDesktopPane();
            createFrame(); //create first "window"
            f.setContentPane(desktop);
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        public void startFrame2()
            createFrame(); //create second "window"
            f.setContentPane(desktop);
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        public void createFrame()
            MyInternalFrame frame = new MyInternalFrame();
            frame.setVisible(true); //necessary as of 1.3
            desktop.add(frame);
            frame.add(new GUI2());
        } Top class
    public class Top
        public static void main(String[] args)
            GUI g = new GUI();
            g.GUII(); //Create JFrame
            g.startFrame(); //Create JInternalFrame
            Top t = new Top();
            t.sth();
        public void sth()
            GUI gui = new GUI();
            gui.startFrame2();
    } MyIntternalFrame class
    import javax.swing.JInternalFrame;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    import oracle.jdeveloper.layout.XYConstraints;
    import oracle.jdeveloper.layout.XYLayout;
    /* Used by InternalFrameDemo.java. */
    public class MyInternalFrame extends JInternalFrame {
        static int openFrameCount =  0;      
        static final int xOffset = 30, yOffset = 30;
        private XYLayout xYLayout1 = new XYLayout();
        private JButton jButton1 = new JButton();
        private JLabel jLabel1 = new JLabel();
        private JFrame c = new JFrame();
        private JPanel d = new JPanel();
        private XYLayout xYLayout2 = new XYLayout();
        public MyInternalFrame() {         
            super("Document #"  + (++openFrameCount),true /*resizable*/,true /*closable*/,true /*maximizable*/,true);//iconifiable*/
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            int width = new GUI2().width + 10;
            int height = new GUI2().height + 40;
            setSize(width,height);
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    } Please tel me where is my mistake or maybe you knew another way to open JInternalFrame with public method form another class

    Some possibly helpful suggestions:
    1) Create one JDesktopPane, and do it in the constructor of GUI. You should call this constructor only once.
    2) Get rid of GUII. The GUI constructor will do all this and more.
    3) Get rid of startFrame and startFrame2.
    4) In GUI2, change your width and height to static variables if you are going to use them in outside classes. There is no reason to have to create a GUI2 object just to get those values. Get them from the class, not the instances.
    5) You're doing something funky in your Top class with your mixing of static code and non-static code. My gut tells me that Top is just a static universe that exists to get your code up and running, and that the code within it should all be static, but that's just my personal opinion.
    6) In MyInternalFrame, get the height and width from GUI2 (if that's what you want to do) again in a static fashion. Rather than new GUI2().width which makes no sense, use GUI2.width.
    Why can't you put the button inside of the JInternalFrame object? I believe that the contentPane of this object which may hold your button (unless you embed a jpanel) uses BorderLayout, so you have to take care how you add jcomponents to the jinternalframe (or more precisely, it's contentPane).

Maybe you are looking for

  • Update excel cells once placed in indesign

    Hi, Once an excel file has been placed onto an indesign document with  custom cells, how do I change these cells without placing the excel file all over again? Many thanks

  • Php post name & age to MySql database

    Back to the basics. I have a simple form to post in my database. Can anybody suggest how I make a variable to catch the list selection and text field? Your name: A value is required. Your age: 22 23 24 25 then below is the action.php file that posts

  • Waking from sleep issue

    Hello. My wife's macbook generates the following error message when waking from sleep. I am curious if others have seen and or fixed this issue? Here it is: Mon Apr 27 16:47:49 2009 panic(cpu 1 caller 0x0019EB7E): "simple lock deadlock detection: loc

  • Profile setting in the Forms

    Hi All, I have developed a New Form.And I'm having 3 organizations.My problem is that i sholud not allow the Users to see data of the Other Organizations data. So i have to restrict the Users at the form level. Can any one help me in this... Thanks,

  • .msi do not install normally, but they do from terminal msiexec

    I have a very strange problem happening right now and have tried every possible way to fix it or find a way around it. Whenever I try to install any .msi file normally by just clicking on it in the explorer it fails with "Error 1359.An internal error