Modal Internal Frames and JCombos

Hi,
I'm trying to create a modal internal frame as suggested in Sun's TechTip:
http://developer.java.sun.com/developer/JDCTechTips/2001/tt1220.html
All I need is to block the input for the rest of the GUI, I don't care about real modality (the setVisible() call returns immediately).
I need to have a JComboBox in my internal frame. It turns out that under JDK1.4.0/1.4.1 the list for the combo is visible only with the Windows Look And Feel, while in every other JDK version it's not visible, except for the portion falling out of the internal frame.
The code to verify this follows. Does anybody know how to fix this? I've opened a bug for it, but I was wondering if someone can help in the forum...
Run the application passing "Windows" or "CDE/Motif", click on "open" and play with the combo to observe the result.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Modal {
static class ModalAdapter
extends InternalFrameAdapter {
Component glass;
public ModalAdapter(Component glass) {
this.glass = glass;
// Associate dummy mouse listeners
// Otherwise mouse events pass through
MouseInputAdapter adapter =
new MouseInputAdapter(){};
glass.addMouseListener(adapter);
glass.addMouseMotionListener(adapter);
public void internalFrameClosed(
InternalFrameEvent e) {
glass.setVisible(false);
public static void main(String args[]) {
System.out.println("Installed lookAndFeels:");
UIManager.LookAndFeelInfo[] lafInfo = UIManager.getInstalledLookAndFeels();
for(int i=0; i<lafInfo.length; i++) {
System.out.println(lafInfo.getName());
String lookAndFeel = null;
if (args.length>0)
lookAndFeel = args[0];
initLookAndFeel(lookAndFeel);
final JFrame frame = new JFrame(
"Modal Internal Frame");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
final JDesktopPane desktop = new JDesktopPane();
ActionListener showModal =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Manually construct a message frame popup
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage("Hello, World");
optionPane.setMessageType(
JOptionPane.INFORMATION_MESSAGE);
// JInternalFrame modal = optionPane.
// createInternalFrame(desktop, "Modal");
                    JInternalFrame modal = new JInternalFrame("test", true, true, true);
JPanel jp = (JPanel )modal.getContentPane();
          JComboBox jcb = new JComboBox(new String[]{"choice a", "choice b"});
jp.setLayout(new BorderLayout());
          jp.add(jcb,BorderLayout.NORTH);
          jp.add(new JTextArea(),BorderLayout.CENTER);
// create opaque glass pane
JPanel glass = new JPanel();
glass.setOpaque(false);
// Attach modal behavior to frame
modal.addInternalFrameListener(
new ModalAdapter(glass));
// Add modal internal frame to glass pane
glass.add(modal);
// Change glass pane to our panel
frame.setGlassPane(glass);
// Show glass pane, then modal dialog
modal.setVisible(true);
glass.setVisible(true);
System.out.println("Returns immediately");
JInternalFrame internal =
new JInternalFrame("Opener");
desktop.add(internal);
JButton button = new JButton("Open");
button.addActionListener(showModal);
Container iContent = internal.getContentPane();
iContent.add(button, BorderLayout.CENTER);
internal.setBounds(25, 25, 200, 100);
internal.setVisible(true);
Container content = frame.getContentPane();
content.add(desktop, BorderLayout.CENTER);
frame.setSize(500, 300);
frame.setVisible(true);
private static void initLookAndFeel(String lookAndFeel) {
String lookAndFeelClassName = null;
UIManager.LookAndFeelInfo[] lafInfo = UIManager.getInstalledLookAndFeels();
for(int i=0; i<lafInfo.length; i++) {
if (lafInfo[i].getName().equals(lookAndFeel)) {
lookAndFeelClassName = lafInfo[i].getClassName();
if (lookAndFeelClassName == null)
System.err.println("No class found for lookAndFeel: "+ lookAndFeel);
try {
UIManager.setLookAndFeel(lookAndFeelClassName);
} catch (ClassNotFoundException e) {
System.err.println("Couldn't find class for specified look and feel:"
+ lookAndFeel);
System.err.println("Did you include the L&F library in the class path?");
System.err.println("Using the default look and feel.");
} catch (UnsupportedLookAndFeelException e) {
System.err.println("Can't use the specified look and feel ("
+ lookAndFeel
+ ") on this platform.");
System.err.println("Using the default look and feel.");
} catch (Exception e) {
System.err.println("Couldn't get specified look and feel ("
+ lookAndFeel
+ "), for some reason.");
System.err.println("Using the default look and feel.");
e.printStackTrace();

Hi,
Had exactly the same problem. Seems there are plenty of similar problems all related to the glass pane, so have solved the problem here by putting the event-blocking panel onto the MODAL_LAYER of the layered pane, rather than replacing the glass pane. Otherwise pretty much the same technique - you may need a property change listener to track changes in the size of the layered pane
something like ...
layer = frame.getLayeredPane();
glass.setSize (layer.getSize()); // will need to track size
glass.add (modal);
layer.add(glass, JLayeredPane.MODAL_LAYER, 0);
I've modified the original examples so the frames can be re-used so you may have to play around with the example a bit
Hope it helps
cheers.

Similar Messages

  • Is it possible or not?(Modal Internal Frames)

    Hi,
    I am continously trying with Modal JInternalFrames.
    But I donot need JOptionPane.Because in that JInternalFrame I didnot ask any confirmation,Infirmation.That InternalFrame is help Frame with a JTabel containg all the records from the database.
    So When I viewing this help page I should block the remaining GUI to accept anything.After closing the Help JInternalFrame I have to work with remaining GUI. That is simply Modal JInternalFrame.
    Is it possible?
    I try with the approch given in the site
    http://java.sun.com/developer/JDCTechTips/2001/tt1220.html
    and also with vetoablechange listener.
    But I didnot get the proper result.That is I coulnot properly implement that.But I solve some errors during development and try my level best.But Not yet correct result.
    So will anybody give me some solutions ,links or some guidance to do that.
    It will very helpful to me.
    Thank you so much.
    Meena

    Here is what I am referring to. Let me know if you need more info.
    public class MyDialog extends JDialog{
       public MyDialog(){
            add(new JButton("Test");
            setModal(true);
    public class MyInternalFrame extends JInternalFrame{
       public void handleButtonPress(){
           MyDialog dialog = new MyDialog();
           dialog.setVisible(); // this will not return until dialog is closed.
    }

  • Modal JInternal Frames?

    Is there a possibility to create REAL custom modal JInternalFrames? I mean without using JOptionPane.showInternal.. since these cannot be customized in size, and dont return a reference.
    felix

    i believe what they were referring to is that you should not use a JDialog AS an internal frame and that you should use the JOptionPane and JInternalFrame classes.
    in your case, it is still perfectly fine to pop up a modal JDialog to ask for user input...
    and i'm pretty sure you were referring to the argument between myself and James. and you are perfectly fine as your question is general enough to not need code. :)

  • How to get Internal frames as well as a background image in a JFrame?

    Hi All,
    Here's my problem. I have a JFrame with a background image that I got by overridding the paintComponent() method of a JPanel and setting as the contentPane of a JFrame. Works great.
    Now what I want is to use internal frames with this Frame a la JInternalFrame classes. But you need to create a JDesktopPane object and set this as the contentPane of the JFrame to get internal frames to work, right? Is there a way for me to have my cake and eat it so I get both internal frames and a background image? Thanks!

    Hmmm,
    so simple, why didn't I think of that? Damn Mondays!
    thanks very much!

  • A Internal frame problem: Please help me

    How can you add a panel to internal frame and show it. I add a image buffer to a panel and then I want to add that panel to internal frame which exists in a main frame. Please help me with code snippet as I am unable to it since morning and struck with my progress in my work. I will be thanki ful/
    regards,
    Ravi.

    Have a look at the code I took from the excellent FREE java swing book you can get here http://www.manning.com/sbe/
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class CommonLayouts extends JFrame {
    public Integer LAYOUT_FRAME_LAYER = new Integer(1);
    public CommonLayouts() {
    super("Common Layout Managers");
    setSize(500, 460);
    JDesktopPane desktop = new JDesktopPane();
    getContentPane().add(desktop);
    JInternalFrame fr1 =
    new JInternalFrame("FlowLayout", true, true);
    fr1.setBounds(10, 10, 150, 150);
    Container c = fr1.getContentPane();
    c.setLayout(new FlowLayout());
    c.add(new JButton("1"));
    c.add(new JButton("2"));
    c.add(new JButton("3"));
    c.add(new JButton("4"));
    desktop.add(fr1, 0);
    fr1.show();
    JInternalFrame fr2 =
    new JInternalFrame("GridLayout", true, true);
    fr2.setBounds(170, 10, 150, 150);
    c = fr2.getContentPane();
    c.setLayout(new GridLayout(2, 2));
    c.add(new JButton("1"));
    c.add(new JButton("2"));
    c.add(new JButton("3"));
    c.add(new JButton("4"));
    desktop.add(fr2, 0);
    fr2.show();
    JInternalFrame fr3 =
    new JInternalFrame("BorderLayout", true, true);
    fr3.setBounds(330, 10, 150, 150);
    c = fr3.getContentPane();
    c.add(new JButton("1"), BorderLayout.NORTH);
    c.add(new JButton("2"), BorderLayout.EAST);
    c.add(new JButton("3"), BorderLayout.SOUTH);
    c.add(new JButton("4"), BorderLayout.WEST);
    desktop.add(fr3, 0);
    fr3.show();
    JInternalFrame fr4 = new JInternalFrame("BoxLayout - X",
    true, true);
    fr4.setBounds(10, 170, 250, 80);
    c = fr4.getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
    c.add(new JButton("1"));
    c.add(Box.createHorizontalStrut(12));
    c.add(new JButton("2"));
    c.add(Box.createGlue());
    c.add(new JButton("3"));
    c.add(Box.createHorizontalGlue());
    c.add(new JButton("4"));
    desktop.add(fr4, 0);
    fr4.show();
    JInternalFrame fr5 = new JInternalFrame("BoxLayout - Y",
    true, true);
    fr5.setBounds(330, 170, 150, 200);
    c = fr5.getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
    c.add(new JButton("1"));
    c.add(Box.createVerticalStrut(10));
    c.add(new JButton("2"));
    c.add(Box.createGlue());
    c.add(new JButton("3"));
    c.add(Box.createVerticalGlue());
    c.add(new JButton("4"));
    desktop.add(fr5, 0);
    fr5.show();
    JInternalFrame fr6 =
    new JInternalFrame("SpringLayout", true, true);
    fr6.setBounds(10, 260, 250, 170);
    c = fr6.getContentPane();
    c.setLayout(new SpringLayout());
    c.add(new JButton("1"), new SpringLayout.Constraints(
    Spring.constant(10),
    Spring.constant(10),
    Spring.constant(120),
    Spring.constant(70)));
    c.add(new JButton("2"), new SpringLayout.Constraints(
    Spring.constant(160),
    Spring.constant(10),
    Spring.constant(70),
    Spring.constant(30)));
    c.add(new JButton("3"), new SpringLayout.Constraints(
    Spring.constant(160),
    Spring.constant(50),
    Spring.constant(70),
    Spring.constant(30)));
    c.add(new JButton("4"), new SpringLayout.Constraints(
    Spring.constant(10),
    Spring.constant(90),
    Spring.constant(50),
    Spring.constant(40)));
    c.add(new JButton("5"), new SpringLayout.Constraints(
    Spring.constant(120),
    Spring.constant(90),
    Spring.constant(50),
    Spring.constant(40)));
    desktop.add(fr6, 0);
    fr6.show();
    desktop.setSelectedFrame(fr6);
    public static void main(String argv[]) {
    CommonLayouts frame = new CommonLayouts();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

  • Getting the size of an internal frame?

    Hi allm
    I want to be able to get the size of an internal frame. I have set the size of the main JFrame to that of Windows by calling Toolkit.getScreenSize(); But i can't seem to find an equivalent for internal frames.
    Basically I have two components in the internal frame that I want to have equal width. I was going to find out the size of the internal frame and then half it and applay a horizontal strut to each component.
    If there is a better way of doing it i'm open to suggestions but any help at all is much appreciated
    Thanks
    Dylan
    BorderLayout border = new BorderLayout();       
             content.setLayout(border);
             Box left = Box.createVerticalBox();
             left.add(Box.createHorizontalStrut(400));
             JPanel Create = new JPanel();
                 Create.setBorder(new TitledBorder (new EtchedBorder(), "Create Database"));
                 left.add(Create);
                 Box right = Box.createVerticalBox();
                 right.add(Box.createHorizontalStrut(400));
                 JPanel Help = new JPanel();
                 Help.setBorder(new TitledBorder (new EtchedBorder(), "Help"));
                 right.add(Help);
                 content.add(left, BorderLayout.CENTER);
                 content.add(right, BorderLayout.CENTER);

    The situation is that I have a class that has about 80
    instance fields of basic data types. But it was
    getting overly complicated. As a number of these
    fields related to year and day data I tried to
    re-write with GregorianCalendar instead.
    There are in the region of 45,000 instance of my clas
    being held in an array, however when I tried to use my
    modified class (with the Calendar fields replacing the
    basic data types) I kept running into OutOfMemoryError
    after about 25,000 instances were created. So I
    figured that the GregorianCalendar class must be
    eating up my memory. Was intrigued, but couldn't find
    out how to calculate the size of my new class.
    Hmmm, serialize it you say? Ok, I'll try that.ok don't do that ;)
    ummm i was giving advice assuming (incorrectly i turns out) that you were trying to see how much space the serialized object would take up when written to disk or over a network etc.
    this does not appear to be your problem.
    so here are my new more informed suggestions.
    1) if you were going to write out the "data" parts of your object so
    it could be re-created what would they be. i'm thinking you could
    just boil it all down maybe to a long as in Date.getTime(); then
    you could have a long[] array with 45,000 slots. this should take up far less memory than having myObject[] with 45,000 slots. then you
    could have one actual object that you insert the data into to play
    around with. this may not be the idealists solution but if you have a
    lot of objects you may not want to carry around all the excess
    stuff.
    2) as an aside you say you tried to re-write the GregorianCalendar...
    have your tried extending it or extending Calendar. the idea of
    extending other non-final classes is you can provide your own
    implementation of some things or add totally new methods without having
    to re-write an existing class.
    just some ideas...

  • Urgent!! Internal Frame

    Hi,
    I have an internal frame and i need to capture when i press '+' in the frame
    The internal frame contains textfields, so i captured the keypressed in each textfield... but i don`t want it to write '+', i only want to capture it in the frame and don�t write it
    can you help me?
    Thanks a lot
    gaby

    First you disable all default focus in your textfields.
    1) Scenario 1 --> no TextField is currently focused (cursor on )
    you have your InternalFrame implements KeyListener and catch the Key + action.
    2) Scenario 2 -->one TextField is currently focused
    *All Text Field should have KeyListener listen to + key.
    *InternalFrame should have KeyListener
    Dispathed this KeyEvent to the InternalFrame and do whatever you want.
    Problem:
    You will not be able to add the + character into you TextFields.
    Solutuion:
    Usually people do Ctrl + or Alt +. Or some other key combines with + key.
    Good luck,
    LP

  • Disposing an internal frame

    When i use the dispose method of the internal frame and dispose it,and then i call desktop.getComponents to check if the internal frame is removed,it still exists and
    desktop.getComponents returns the frame.
    How do i remove the frame from the desktop?

    I guess you have the answer in that question. desktop.remove(....);

  • Disabling an internal frame

    Is there an easy way to disable (and enable) an internal frame and all the items on it? I know how to do it by disabling all the items on it seperately, but that is not an efficient way...
    debeumers

    You can use the glass pane. See
    http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html
    rykk

  • Image icon on internal frame disappearing and re-appearing

    I have just upgraded to jdk 1.4.1-b21 from 1.4.0_01-b03 and have noticed that after adding an Internal Frame to a desktop and moving the mouse over the image icon in the left hand corner the image disappears. The image re-appears again, once I presume, when the desktop and its frames are repainted.
    Is this a bug or has something changed between the two jdk's.
    Thanks.
    Steve.

    Hi,
    I attempted the Disk Utility Repair but it did not work.
    So I disabled the application 'StickyWindows' and this resolved the problem.
    Hope this helps.

  • Internal Frames problem

    Hi,
    I am writing a piece of code where I want to able to choose from a menu a screen that displays multiple graphs (using Internal frames.) I am using cardlayout to bring up the various options I choose from the menu. I have simplified my program as much as possible but I still seem to be getting the same error
    Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container .......
    I know I shouldn't be adding a window to a container but I can't see how I can change my code so it has the functionality I desire.
    Here is the code I am using
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame
         public Test()
             JPanel card1 = new JPanel();
             card1.add(new InternalFrameDemo());
              getContentPane().add(card1);
        public static void main(String[] args)
              Test frame = new Test();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class InternalFrameDemo extends JFrame
        JDesktopPane desktop;
        static final int xOffset = 30, yOffset = 30;
        private JLabel graph1;
        private String Graph1;
        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);
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        //Create a new internal frame.
        protected void createFrame() {
            MyInternalFrame frame = new MyInternalFrame();
            frame.setVisible(true);
            desktop.add(frame);
            try {
                frame.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
        //Quit the application.
        protected void quit() {
            System.exit(0);
       public void MyInternalFrame() {
         System.out.println("graph1");
         graph1 = new JLabel("", 
                       new ImageIcon("../images/Graph1.jpg"),
                       JLabel.CENTER);
         getContentPane().add(graph1);
         //...Then set the window size or call pack...
         setSize(500,550);
    }If anyone could point me in the right direction it would be great. Thanks in advance!

    But I actually do not understand what that card layout thing is all about. If you want to hide/show internal frames you can simply use setVisible() and setSelected() like examplified below (I did put all code in the same file for my convenince). I have put a text in the label so that you can see that it is replaced. Using aJLabel to show an image is however a little bit weird.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    class MyInternalFrame extends JInternalFrame
      private JLabel graph1;
      public MyInternalFrame(String text)
        graph1 = new JLabel(text, 
                            new ImageIcon("../images/Graph1.jpg"),
                            JLabel.CENTER);
        getContentPane().add(graph1);
        setSize(500,550);
    public class InternalFrameDemo extends JFrame
      private JDesktopPane desktop;
      private final MyInternalFrame[] frames;
      public InternalFrameDemo()
        super("InternalFrameDemo");
        frames = new MyInternalFrame[3];
        //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
        setContentPane(desktop);
        frames[0] = createFrame("Hello world!");
        frames[1] = createFrame("Hello again, world!");
        frames[2] = createFrame("Goodbye cruel world!");
        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        setSize(500, 500);
        Thread animThread = new Thread()
            public void run()
              for (int i = 0; i < frames.length; ++i)
                final int frameId = i;
                SwingUtilities.invokeLater(new Runnable()
                    public void run()
                      // Hide frame that is showing.
                      if (frameId != 0)
                        frames[frameId - 1].setVisible(false);
                      System.out.println("Replacing image: " + frameId);
                      frames[frameId].setVisible(true);
                      try
                        frames[frameId].setSelected(true);
                      catch (java.beans.PropertyVetoException exc)
                        exc.printStackTrace();
                try
                  Thread.sleep(3000);
                catch (InterruptedException exc)
                  exc.printStackTrace();
        animThread.start();
      //Create a new internal frame.
      protected MyInternalFrame createFrame(String text)
        MyInternalFrame frame = new MyInternalFrame(text);
        desktop.add(frame);
        return frame;
      public static void main(String[] args)
        JFrame frame = new InternalFrameDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }Using lazy initialization where you postpone the creation of an internal frame until it is actually shown would be an improvement.
    The setVisible/Selected() call can of course be triggered by something else in your application.
    Note that changes of swing components shall be made in the EDT.

  • Internal frame dragging perfermance problem in JDK1.4.1

    Hi there,
    When using internal frame with outline(not faster or LIVE_DRAG_MODE) property with JDK 1.4.1_01 (windows), the speed of internal frame dragging is terrible(very very slow).
    The same code runs fine with JDK1.3.X, and it's performance(dragging speed) is acceptable(not very good, so so) when using JDK 1.4.0_X.
    I've tried both motheds to set the property as follow, and got the same result:
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    desktop.putClientProperty("JDesktopPane.dragMode", "outline");
    But, after I commented the line: g.setXORMode(Color.white); //line Num: 279
    in the class javax.swing.DefaultDesktopManager.java, the speed of dragging is very well(as same as when running with JDK1.3.X).
    My qestions are:
    - How can I improve the internal frame dragging performance in JDK 1.4.1_01(windows)?
    - Does my testing mean to a bug in the implementation of the abstract method Graphics.setXORMode() in the JDK 1.4.1_01 windows version ?
    TIA
    In terms of the test case, we may just use the follows:
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/InternalFrameDemo.java
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/MyInternalFrame.java

    Anyone know if this is registered as a bug? I couldn't find it.

  • Openinig internal frames by clicking menuitems

    Hi,
    I have been trying to open internal frames by clicking menu items but
    have not been able to do so because menuitems support only action listeners and not all mouse event listeners.
    Actually I wanted the event to return the frame n which the event has occured
    e.g., event,getframe(), so that I could create an internal frame in the same frame.
    But such kind of function is unavailable.
    Kindly suggest something...the code is given below (it works perfectly)..it need a text file from which the menuitems are read. This is also given below:
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.io.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.*;
    import javax.swing.undo.*;
    class Action extends JFrame
         ActionListener FListener = new ActionListener()
               public void actionPerformed(ActionEvent event)
                  {System.out.println("Menu item " + event.getActionCommand(  ) +"  of File Menu was pressed.");}
        ActionListener EListener = new ActionListener()
               public void actionPerformed(ActionEvent event)
                  {System.out.println("Menu item " + event.getActionCommand(  ) +"  of Edit Menu was pressed.");}
        ActionListener VListener = new ActionListener()
               public void actionPerformed(ActionEvent event)
                  {System.out.println("Menu item " + event.getActionCommand(  ) +"  of View Menu was pressed.");}
        ActionListener TListener = new ActionListener()
               public void actionPerformed(ActionEvent event)
                  {System.out.println("Menu item " + event.getActionCommand(  ) +"  of Tools Menu was pressed.");}
        ActionListener HListener = new ActionListener()
               public void actionPerformed(ActionEvent event)
                  {System.out.println("Menu item " + event.getActionCommand(  ) +"  of Help Menu was pressed.");}
         /*     protected class MyUndoableEditListener  implements UndoableEditListener
                  protected UndoManager undo = new UndoManager();
                  public void undoableEditHappened(UndoableEditEvent e)
                 //Remember the edit and update the menus
                 undo.addEdit(e.getEdit());
                 undoAction.updateUndoState();
                 redoAction.updateRedoState();
          class framecreator extends JFrame
               public JFrame CreateFrame(JMenuBar m)
             JDesktopPane jdp= new JDesktopPane();
              JFrame.setDefaultLookAndFeelDecorated(true);       
            JFrame frame = new JFrame("PEA");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         
            frame.setContentPane(jdp);
            jdp.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);          
            frame.setJMenuBar(m);       
            frame.pack();
            frame.setVisible(true);
            frame.setSize(600,600);
            frame.setLocation(100,100);
            return frame;
          class internalframecreator extends JFrame
             public JInternalFrame CreateInternalFrame(JFrame f)
              Container cp= f.getContentPane();
              JInternalFrame jif = new JInternalFrame("internal frame",true,true,true,true);
             cp.add(jif);
             jif.pack();
             jif.setVisible(true);
             jif.setSize(300,300);
             jif.setLocation(80,80);
             return jif;    
      class menucreator
         public String[] filereader()
              String[] menuitems=new String[21];
              int i=0,j=0;
              String record = null;            
                   for(int h=0;h<21;h++){ menuitems[h]=null;}
               try { 
                    FileReader fr = new FileReader("projectconfig2.txt");  
                     BufferedReader br = new BufferedReader(fr);
                         while ( (record=br.readLine()) != null )
                           StringTokenizer st = new StringTokenizer(record,"\n");
                             while (st.hasMoreTokens())
                          menuitems= st.nextToken();
         System.out.println(menuitems[i]);
    i++;
                   /* StringTokenizer st1 = new StringTokenizer(record,"\n");
         while (st1.hasMoreTokens())
         while ( (record=br.readLine()) != null )
         StringTokenizer st2 = new StringTokenizer(record,":");
         while (st2.hasMoreTokens())
         menuitems[i][j]= st2.nextToken();
         System.out.println(menuitems[i][j]);
              j++;      
         i++;
              } catch(IOException e)
         System.out.println("Error reading file");
         return (menuitems);
         public JMenuBar CreateMenu(Action a, String menuitems[])
    JMenuBar mb = new JMenuBar();
    JMenu fileB = new JMenu(menuitems[0]);
    JMenu editB = new JMenu(menuitems[8]);
    JMenu viewB = new JMenu(menuitems[11]);
    JMenu toolsB = new JMenu(menuitems[14]);
    JMenu helpB = new JMenu(menuitems[18]);
    mb.add(fileB);
    mb.add(editB);
    mb.add(viewB);
    mb.add(toolsB);
    mb.add(helpB);
    JMenuItem newpolicyB = new JMenuItem(menuitems[1]);
    newpolicyB.addActionListener(a.FListener);
    //newpolicyB.addUndoableEditListener(new MyUndoableEditListener());
    JMenuItem openB = new JMenuItem(menuitems[2]);
    openB.addActionListener(a.FListener);
    JMenuItem saveB = new JMenuItem(menuitems[3]);
    saveB.addActionListener(a.FListener);
    JMenuItem saveasB = new JMenuItem(menuitems[4]);
    saveasB.addActionListener(a.FListener);
    JMenuItem printxmlB = new JMenuItem(menuitems[5]);
    printxmlB.addActionListener(a.FListener);
    JMenuItem printreadablepolicyB = new JMenuItem(menuitems[6]);
    printreadablepolicyB.addActionListener(a.FListener);
    JMenuItem exitB = new JMenuItem(menuitems[7]);
    exitB.addActionListener(a.FListener);
    JMenuItem undoB = new JMenuItem(menuitems[9]);
    undoB.addActionListener(a.EListener);
    JMenuItem redoB = new JMenuItem(menuitems[10]);
    redoB.addActionListener(a.EListener);
    JMenuItem xmlB = new JMenuItem(menuitems[12]);
    xmlB.addActionListener(a.VListener);
    JMenuItem readablepolicyB = new JMenuItem(menuitems[13]);
    readablepolicyB.addActionListener(a.VListener);
    JMenuItem validateB = new JMenuItem(menuitems[15]);
    validateB.addActionListener(a.TListener);
    JMenuItem signandpublishB = new JMenuItem(menuitems[16]);
    signandpublishB.addActionListener(a.TListener);
    JMenuItem optionsB = new JMenuItem(menuitems[17]);
    optionsB.addActionListener(a.TListener);
    JMenuItem pemanualB = new JMenuItem(menuitems[19]);
    pemanualB.addActionListener(a.HListener);
    JMenuItem aboutB = new JMenuItem(menuitems[20]);
    aboutB.addActionListener(a.HListener);
    fileB.add(newpolicyB);
    fileB.add(openB);
    fileB.add(saveB);
    fileB.add(saveasB);
    fileB.add(printxmlB);
    fileB.add(printreadablepolicyB);
    fileB.add(exitB);
    editB.add(undoB);
    editB.add(redoB);
    viewB.add(xmlB);
    viewB.add(readablepolicyB);
    toolsB.add(validateB);
    toolsB.add(signandpublishB);
    toolsB.add(optionsB);
    helpB.add(pemanualB);
    helpB.add(aboutB);
    mb.setSize(300,200);
    mb.setVisible(true);
    return mb;
    public class project
    public static void main(String args[])
              Action a =new Action();           
              framecreator fc=new framecreator();           
         menucreator mc=new menucreator();     
         internalframecreator ifc= new internalframecreator();          
         ifc.CreateInternalFrame(fc.CreateFrame(mc.CreateMenu(a,mc.filereader())));
    The text file called projectconfig2.txt
    File
    New Policy
    Open...
    Save
    Save As...
    Print XML
    Print Readable Policy
    Exit
    Edit
    Undo
    Redo
    View
    XML
    Readable Policy
    Tools
    Validate
    Sign & Publish
    Options
    Help
    PE Manual
    About

    The problem is that you are adding the JInternalFrame to the JFrame's contentPane when it should be added to the JDesktopPane. See your code ...
    public JInternalFrame CreateInternalFrame( JFrame  f )
         Container  cp = f.getContentPane();
         JInternalFrame jif = new JInternalFrame("internal frame",true,true,true,true);
         cp.add( jif );

  • Custom internal frames

    Hello,
    I have written some custom internal frames, along with their UI's, title panes, and desktop icons. Everything seems to work fine when I'm in JBuilder and I use the "run" command, but when I compile the program and run it as a batch file, my internal frames appear as gray boxes that can't be moved or resized.
    package KComponent;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import Theme.*;
    import java.io.*;
    import javax.swing.border.*;
    public class KInternalFrame extends JInternalFrame {
      private JLabel titleLabel;
      private String title;
      public static Color titleColor = Color.white;
      public static Color titleBarColor = Theme.DARK;
      private KButton maximize, minimize, normalize;
      private static final String PATH = "pics" + File.separator;
      public KInternalFrame(String title) {
        super(title, true, false, true, true);
        this.title = title;
        this.titleColor = titleColor;
        this.titleBarColor = titleBarColor;
        //getContentPane().add(content, BorderLayout.CENTER);
        //setContentPane(content);
        //LineBorder line = new LineBorder(titleBarColor, 2);
        //setBorder(line);
        setBorder(BorderFactory.createRaisedBevelBorder());
        this.getDesktopIcon().setUI(new KDesktopIconUI(title, titleBarColor, titleColor));
        setUI(new KInternalFrameUI(this));
    package KComponent;
    import javax.swing.plaf.basic.*;
    import javax.swing.*;
    import java.awt.*;
    import Theme.*;
    public class KInternalFrameUI extends BasicInternalFrameUI {
      public KInternalFrameUI(JInternalFrame frame) {
        super(frame);
      protected void installDefaults(){
          Icon frameIcon = frame.getFrameIcon();
          frame.setFrameIcon(null);
          /* enable the content pane to inherit background color from its
             parent by setting its background color to null. Fixes bug#
             4268949. */
          JComponent contentPane = (JComponent) frame.getContentPane();
          if (contentPane != null) {
            Color bg = contentPane.getBackground();
          else {
            Color bg = null;
          //LookAndFeel.installBorder(frame, "InternalFrame.border");
      protected JComponent createNorthPane(JInternalFrame w) {
        titlePane = new KInternalFrameTitlePane(w, w.getTitle(), Theme.DARK, Color.white);
        return titlePane;
    package KComponent;
    import javax.swing.plaf.basic.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import Theme.*;
    public class KInternalFrameTitlePane extends BasicInternalFrameTitlePane implements ActionListener {
      private JInternalFrame frame;
      private final String PATH = "pics" + File.separator;
      private KButton maxButton;
      private KButton minButton;
      private KButton normButton;
      private JLabel titleLabel;
      private File maxIcon = new File(PATH, "maximize.gif");
      private File maxOver = new File(PATH, "maximize_rollover.gif");
      private File minIcon = new File(PATH, "minimize.gif");
      private File minOver = new File(PATH, "minimize_rollover.gif");
      private File norIcon = new File(PATH, "normal.gif");
      private File norOver = new File(PATH, "normal_rollover.gif");
      String title;
      Color activeTitle;
      Color activeTitleText;
      Color inactiveTitle;
      Color inactiveTitleText;
      public KInternalFrameTitlePane(JInternalFrame frame, String title, Color activeTitle, Color activeTitleText) {
        super(frame);
        this.frame = frame;
        this.title = title;
        this.activeTitle = activeTitle;
        this.activeTitleText = activeTitleText;
        //this.inactiveTitle = inactiveTitle;
        //this.inactiveTitleText = inactiveTitleText;
        installTitlePane();
      public void installTitlePane() {
        titleLabel = new JLabel(" " + title + " ");
        titleLabel.setFont(new Font("verdana", Font.PLAIN, 11));
        titleLabel.setForeground(activeTitleText);
        titleLabel.setBorder(null);
        titleLabel.setOpaque(false);
        File icon = new File(PATH, "maximize.gif");
        File rollover = new File(PATH, "maximize_rollover.gif");
        maxButton = new KButton(icon, rollover, rollover, false);
        maxButton.setOpaque(false);
        maxButton.setToolTipText("Maximize window");
        maxButton.setActionCommand("maximize");
        //maxButton.addActionListener(this);
        icon = new File(PATH, "minimize.gif");
        rollover = new File(PATH, "minimize_rollover.gif");
        minButton = new KButton(icon, rollover, rollover, false);
        minButton.setOpaque(false);
        minButton.setToolTipText("Minimize window");
        minButton.setActionCommand("minimize");
        //minButton.addActionListener(this);
        icon = new File(PATH, "normal.gif");
        rollover = new File(PATH, "normal_rollover.gif");
        normButton = new KButton(icon, rollover, rollover, false);
        normButton.setOpaque(false);
        normButton.setToolTipText("Normalize window");
        normButton.setActionCommand("normal");
        //normButton.addActionListener(this);
        JPanel buttonHeader = new JPanel(new GridLayout(1, 3, 0, 0));
        buttonHeader.setOpaque(false);
        buttonHeader.add(minButton);
        buttonHeader.add(normButton);
        buttonHeader.add(maxButton);
        JPanel titlePane = new JPanel(new BorderLayout());
        titlePane.setBackground(activeTitle);
        titlePane.add(titleLabel, BorderLayout.WEST);
        titlePane.add(buttonHeader, BorderLayout.EAST);
        setBackground(activeTitle);
        setLayout(new BorderLayout());
        //add(titleLabel, BorderLayout.WEST);
        //add(buttonHeader, BorderLayout.EAST);
        add(titlePane, BorderLayout.CENTER);
        //installDefaults();
        createActions();
        enableActions();
        //createActionMap();
        assembleSystemMenu();
        createButtons();
      protected void createButtons() {
          minButton.addActionListener(iconifyAction);
          minButton.setActionCommand("minimize");
          minButton.addActionListener(this);
          maxButton.addActionListener(maximizeAction);
          maxButton.setActionCommand("maximize");
          maxButton.addActionListener(this);
          normButton.addActionListener(restoreAction);
          normButton.setActionCommand("normal");
          normButton.addActionListener(this);
          //setButtonIcons();
      public void setButtonIcons() {}
      public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if (command.equals("maximize")) {
          maxButton.setEnabled(false);
          minButton.setEnabled(true);
        else if (command.equals("minimize")) {
          //maxButton.setEnabled(true);
          //minButton.setEnabled(false);
        else if (command.equals("normal")) {
          maxButton.setEnabled(true);
          minButton.setEnabled(true);
    package KComponent;
    import javax.swing.plaf.basic.BasicDesktopIconUI;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.border.*;
    public class KDesktopIconUI extends BasicDesktopIconUI {
      private final String PATH = "pics" + File.separator;
      private File norIcon = new File(PATH, "normal.gif");
      private File norOver = new File(PATH, "normal_rollover.gif");
      JComponent iconPane;
      String title;
      Color activeTitle;
      Color activeTitleText;
      KButton norButton;
      MouseInputListener mouseInputListener;
      public KDesktopIconUI(String title, Color activeTitle, Color activeTitleText) {
        this.title = title;
        this.activeTitle = activeTitle;
        this.activeTitleText = activeTitleText;
      protected void installComponents() {
          frame = desktopIcon.getInternalFrame();
          norButton = new KButton(norIcon, norOver, norOver, false);
          norButton.setOpaque(true);
          norButton.setBackground(activeTitle);
          iconPane = new JPanel(new BorderLayout());
          JLabel jlTitle = new JLabel(" " + title + " ");
          jlTitle.setFont(new Font("verdana", Font.PLAIN, 11));
          jlTitle.setForeground(activeTitleText);
          jlTitle.setBackground(activeTitle);
          jlTitle.setOpaque(true);
          iconPane.add(jlTitle, BorderLayout.CENTER);
          iconPane.add(norButton, BorderLayout.EAST);
          desktopIcon.setLayout(new BorderLayout());
          desktopIcon.add(iconPane, BorderLayout.CENTER);
          desktopIcon.setBackground(activeTitle);
          desktopIcon.setForeground(activeTitleText);
          iconPane.setBorder(BorderFactory.createRaisedBevelBorder());
          desktopIcon.setBorder(null);
      protected void installListeners() {
          mouseInputListener = createMouseInputListener();
          desktopIcon.addMouseMotionListener(mouseInputListener);
          desktopIcon.addMouseListener(mouseInputListener);
          norButton.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
              deiconize();
      public Dimension getMinimumSize(JComponent c) {
          return iconPane.getMinimumSize();
      public Dimension getMaximumSize(JComponent c){
          return iconPane.getMaximumSize();
      public Dimension getPreferredSize(JComponent c) {
          JInternalFrame iframe = desktopIcon.getInternalFrame();
          Border border = iframe.getBorder();
          int w2 = 157;
          int h2 = 18;
          //if(border != null)
              //h2 += border.getBorderInsets(iframe).bottom +
                //    border.getBorderInsets(iframe).top;
          return new Dimension(w2, h2);
      protected void uninstallComponents() {
          desktopIcon.setLayout(null);
          desktopIcon.remove(iconPane);
    package KComponent;
    import javax.swing.*;
    import java.awt.*;
    import Theme.*;
    import javax.swing.plaf.metal.*;
    public class KDesktop extends JDesktopPane {
      ImageIcon icon;
      boolean isWatermark;
      JInternalFrame gb, proj, stat, cal;
      boolean gbOpen, projOpen, statOpen, calOpen;
      public KDesktop(boolean isWatermark) {
        this.isWatermark = isWatermark;
        icon = Theme.getBackground();
        setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
      public void setBackgroundImage(ImageIcon i) {
        icon = i;
      public ImageIcon getBackgroundImage() {
        return icon;
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (!isWatermark) {
          if (getWidth() > icon.getIconWidth() || getHeight() > icon.getIconHeight()){
            g.drawImage(icon.getImage(), 0,0, getWidth(), getHeight(), null);
          else {
            if (getProportionalHeight(getWidth()) < getHeight()) {
              g.drawImage(icon.getImage(), 0, 0,
                          getProportionalWidth(getHeight()), getHeight(), null);
            else
              g.drawImage(icon.getImage(), 0,0,
                          getWidth(), getProportionalHeight(getWidth()), null);
        else {
          int w = icon.getIconWidth();
          int h = icon.getIconHeight();
          if (w == '\u0000' || h == '\u0000') {
            super.paint(g);
          else {
            int currX = 0;
            int currY = 0;
            boolean keepPainting = true;
            while (keepPainting) {
              if (currX < (getWidth()+w/2)) {
                g.drawImage(icon.getImage(), currX, currY, null);
                currX += w;
              else if (currY < (getHeight()+h/2)) {
                currX = 0;
                currY += h;
                g.drawImage(icon.getImage(), currX, currY, null);
              else keepPainting = false;
      public int getProportionalHeight(int width) {
        double percentage = (double)width/icon.getIconWidth();
        return (int)(percentage*icon.getIconHeight());
      public int getProportionalWidth(int height) {
        double percentage = (double)height/icon.getIconHeight();
        return (int)(percentage*icon.getIconWidth());
    }Any ideas? I don't see how everything could work fine within the JBuilder environment and then screw up when I compile the code.
    Thanks for any help.

    And this is how I call up the UI from my main function:
    displayFrame.setUI(new MyInternalFrameUI(intFrame));Thanks!

  • Passing data from a Table in a Dialog to a Listbox in a Internal Frame

    Hi All,
    Currently I have 2 .java classes.
    In the first class, DisplayListBox.java, it would have listboxes in it and a textbox with a button, Find.
    Upon clicking on the "Find" button, it would create a dialog window and call the second class, TableSelection.java.
    Therefore now, the dialog window would contain a table with all the datas.
    Just in case you guys would like to know, the dialog window was created in the DisplayListBox.java class and the internal frame was being created in another cls upon clicking the menu btn.
    Upon selecting a cell in the table, i'd like to pass the value to the listbox in the internal frame, how can i go about doing it?
    I've got the coding for getting the value of a selected cells. However, i'm unsure of how i can pass the value retrieved to the listbox in the internal frame.
    Any help and advices are gladly appreciated! (:

    Thanks for your reply.
    However, I am quite new to java so is it possible for you to explain in details of how i should go about going it?
    To start off, could you tell me:
    1. Where do I create the ListSelectionListener? In the DisplayListBox.java or TableSelection.java?
    Sorry for the trouble but i just picked up java so I am pretty much unsure of all these stuff.
    Thanks for your help! (:

Maybe you are looking for