Invoking a JPanel in a Frame

How do we invoke a JPanel in an existing JFrame on an Action event.

Hi leemax,
I am invoking a JInternalFrame in a Jframe using MDIDesktopPane.
In my JInternalFrame i instantiate a JPanel on an ActionPerformed event.
But that panel doesn't show up in my JInternalFrame.
Class SomeClass extends JInternalFrame{
JPanel jPanel1=new JPanel();
this.getContentPane().add(jPanel1);
void some_ActionPerformed(ActionEvent e){
JPanel a= new MyPanel(); //instantiating a JPanel in another Java file
jPanel1.add(a);//jPanel1 is a JPanel in my JInternalFrame.
//window.repaintImmediately() doesn't work

Similar Messages

  • User-resizable JPanel within my frame?

    Hi all,
    I've got a JFrame which contains a bunch of content in FlowLayout. One of the components in my frame is a JPanel that has the potential to display a lot of content -- it's reading a webpage obtained from the user. The panel has a scroll-bar, of course, but if there is a lot of content the user would prefer to see a bigger panel.
    Does anyone know of anyway to have an embedded JPanel use draggable borders so that they can re-size the panel at will? Naturally, everything in the panel and out of the panel should respect the new dimensions, and so components surrounding the panel in flowlayout, for example, should react accordingly.
    Is this possible?
    Thanks!
    Tim

    I could do that if I made my entire content pane a series of split panes, but I don't think that wouldn't really be a reusable solution (if I misunderstand what you meant, apologies).
    What I'm hoping for is something that's a property of the JPanel component itself. That way I can insert this expandable JPanel anywhere and everything else ought to respect its resizing. If such a thing is impossible, then some solution that mimics that would be fine.
    Any thoughts?

  • My jList won't show up on the frame

    My problem is that I can't see the JList in the scrollPane. I am able to run and compile this frame through JBuilder, however I get this error message:
    java.lang.NullPointerException new JList(helpTopics)
    If I remove the jpanel from the frame and just drop in the scrollPane with the nested jlist on the frame I am then able to see the list and the items in the list. But I'd like to have it on a panel.
    BTW I am calling this frame from another class that contains the main function. Here is my code:
    import java.awt.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class NewFrame extends JFrame{
    private final String[] helpTopics = {"Load Cells", "Strain Gages",
    "Op Amps", "RTD", "Wheatstone Bridge"};
    JPanel jPanel1 = new JPanel();
    JList lstTopics = new JList(helpTopics);
    JScrollPane jScrollPane1 = new JScrollPane();
    public NewFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.add(lstTopics, null);
    Any help with my problem would greatly reduce my stress factor.
    Thanks.

    You haven't added the panel to the frame from the code you have just posted.

  • How to invoke servlet in a package in iPlanet Web Server 4.01 platform ?

    I want to use a servlet which is in a package.
    http://10.251.9.194/servlet/aibd.GetService
    servlet is mapping to /home03/zhangxs/bbn/servlets.
    but the servlet can not be invoked.
    I read the errors file as following:
    [02/ 7��/2001:17:06:35] warning (19620):
    requested file not found
    (uri=/servlet/aibd.GetService,
    filename=/home03/zhangxs/bbn/servlets/aibd.GetService)
    html invoking statement is as following:
    <frame src="/servlet/aibd.GetService>
    I already set the CLASSPATH env variable.
    I think it should be applied using servlet of a package.
    Maybe I missed some setting.
    I hope u can help me.
    Thanks in advance.

    There is an option in the Netscape admin functionality for mapping the servlet virtual directory from the request URI into the physical directory.
    However I say don't. The Java support in Netscape 4.xx is lousy. Use Tomcat instead. It's more stable and a more complete implementation. Unfortunatly it's even more difficult to set up.

  • D&D problem since SDK1.4. Dropped object falls through JPanel

    Hi,
    my application consists of two JInternalFrame.
    First frame consists of JTree and JPanel.
    Second frame consists of JTextArea.
    JTree is DragSource, JTextArea is DropTarget. JPanel-object is neither DragSource, nor DropTarget.
    It is possible to drag tree nodes from the JTree and to drop into the JTextArea.
    Drag & drop from the JTree into JPanel does not work - as expected.
    But it still possible to provide "drag & drop", even if the JTextArea is covered(partly or --completely) byJPanel. That means,that the dropped node "falls" through  the JPanel on the underlying JTextArea.
    This phenomenon occurs only since jdk 1.4.
    How can I prevent my application from such a behaviour?
    Thanks,
    Sergey35
    import javax.swing.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    public class TestDnD extends JFrame implements DragGestureListener,
    DragSourceListener,
    DropTargetListener
    JTree tree = new JTree();
    JPanel panel = new JPanel();
    JTextArea text = new JTextArea();
    JDesktopPane desktop = new JDesktopPane();
    JInternalFrame frameFirst = new JInternalFrame("First",true,true,true,true);
    JInternalFrame frameSecond = new JInternalFrame("Second",true,true,true,true);
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,tree,panel);
    public TestDnD()
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.getContentPane().add(desktop);
    this.setSize(400,400);
    this.setVisible(true);
    desktop.add(frameSecond);
    desktop.add(frameFirst);
    frameFirst.getContentPane().add(split);
    frameSecond.getContentPane().add(text);
    frameFirst.setBounds(0,0,200,200);
    frameSecond.setBounds(100,100,200,200);
    frameSecond.setVisible(true);
    frameFirst.setVisible(true);
    DragSource dragSource = DragSource.getDefaultDragSource();
    dragSource.createDefaultDragGestureRecognizer(tree,
    DnDConstants.ACTION_COPY_OR_MOVE,
    this);
    new DropTarget(text, DnDConstants.ACTION_COPY_OR_MOVE,
    this);
    public void dragGestureRecognized(DragGestureEvent e)
    Object o =tree.getLastSelectedPathComponent();
    StringSelection transObject=new StringSelection(o.toString());
    try
    e.startDrag(DragSource.DefaultMoveDrop, // cursor
    null, // Image image
    null, // Point offset
    transObject,
    this); // drag source listener
    catch(InvalidDnDOperationException dnd)
    dnd.printStackTrace();
    /** DragSourceListener implementation.*/
    public void dragDropEnd(DragSourceDropEvent e){ }
    public void dragEnter(DragSourceDragEvent e) { }
    public void dragExit(DragSourceEvent e){ }
    public void dragOver(DragSourceDragEvent e) { }
    public void dropActionChanged(DragSourceDragEvent e) { }
    /** Implementation of DropTargetListener. */
    public void drop(DropTargetDropEvent e)
    try
    Transferable tr = e.getTransferable();
    if(e.isDataFlavorSupported(DataFlavor.stringFlavor))
    String string = (String)tr.getTransferData(DataFlavor.stringFlavor);
    e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    e.dropComplete(true);
    text.setText(string);
    else
    e.rejectDrop();
    catch(Exception ex)
    ex.printStackTrace();
    }// End drop
    /** Implementation of DropTargetListener. */
    public void dragOver(DropTargetDragEvent e)
    System.out.print(".");
    public void dropActionChanged(DropTargetDragEvent e) { }
    public void dragEnter(DropTargetDragEvent e) {   }
    public void dragExit(DropTargetEvent e) {   }
    public static void main(String[] arg)
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception e){  }
    new TestDnD();

    Drag & drop has changed dramaticaly for jdk1.4, the methods you use are obsolete now. Check out the differences: http://java.sun.com/j2se/1.4.1/docs/guide/swing/1.4/dnd.html

  • Line wrapping and scrolling in JPanel

    Hello,
    I've got an empty JPanel to which I want to add an (unknown) number of JLabels. Each JLabel has a text which is just one word. When my program is adding JLabels to the JPanel, I want it to have the same behaviour as a normal text editor: when a line is full, the next line gets filled (line wrapping).
    If I just keep adding JLabels to a JPanel of a fixed size with .add(), there's no line wrapping. I tried it by giving the JPanel a fixed size, flowLayout and nesting it within a JScrollPane, but it keeps filling one long line, instead of jumping to the next one.
    Any obvious solutions??
    Thanks
    Mark

    well this depends on how your layout is build, you should post some code so we can see what your trying to do.
    For example if your JPanel is the Frame's main panel, fixing a MaximumSize or PreferredSize wont have any effect, it will grow as big as you defined the JFrame size.
    If you have only a JPanel with a max size of 200,300 in a JFrame with a size of 800,600, it will grow to 800,600.
    You could create a BoxLayout with X axis, then insert an HorizontalStruts, insert your JPanel and another Horizontal Struts(Box.createHorizontalStrut(int width) ) to force the JPanel to be smaller than the JFrame.
    I did not test this a lot, but it seams to work
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
      public static MyFrame frame ;
      public static void main(String[] args) {
        frame = new MyFrame();
        frame.show(true);
        frame.pack();
      public static class MyFrame extends JFrame {
        JLabel a, b, c, d, e, f, g, h, i, j, k ;
        public MyFrame(){
          super();
          JPanel sizeLimiter = (JPanel)this.getContentPane();
          sizeLimiter.setLayout(new BoxLayout(sizeLimiter, BoxLayout.X_AXIS));
         // sizeLimiter.setPreferredSize(new Dimension(800,600));
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new FlowLayout());
          mainPanel.setPreferredSize(new Dimension(400,300));
          mainPanel.setMinimumSize(new Dimension(400,300));
          a = new JLabel("this is sample test ");
          b = new JLabel("to demonstrate an example ");
          c = new JLabel("of simple a flow layout ");
          d = new JLabel("which is wrapping ");
          e = new JLabel("when it reaches the end ");
          f = new JLabel("of a line. ");
          g = new JLabel("Set the maximum size of the panel ");
          h = new JLabel("And it should work ");
          i = new JLabel("If it doesnt post your code so we can");
          j = new JLabel("check it out to see whats wrong ");
          k = new JLabel("sincerly yours, Jf Beaulac ");
          mainPanel.add(a);
          mainPanel.add(b);
          mainPanel.add(c);
          mainPanel.add(d);
          mainPanel.add(e);
          mainPanel.add(f);
          mainPanel.add(g);
          mainPanel.add(h);
          mainPanel.add(i);
          mainPanel.add(j);
          mainPanel.add(k);
          // Fix some "margins"
          sizeLimiter.add(Box.createHorizontalStrut(200));
          // Squeeze the panel
          sizeLimiter.add(mainPanel);
          sizeLimiter.add(Box.createHorizontalStrut(200));
        protected void processWindowEvent(WindowEvent e) {
          super.processWindowEvent(e);
          if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            this.dispose();
    }Regards,
    Jf Beaulac

  • Refresh a JPanel every time.

    Hi,
    How can you refresh a JPanel every time you invoke this JPanel?
    I have a Swing Application with a JSplitPane: a JTree on the left and a JPanel on the right. The JTree is used as a menu to display the right JPanel on the right. At this moment, the JPanels will only be created when I start the Application, so not on every time when I click on the JTree. Is it possible to get a new instance of the JPanel every time I reach it from the JTree (or at least get a trigger so that the latest information will be shown)?
    I hope someone can help. Thanks!
    Tongue78.
    |JTree                |  Place to show the JPanels  |
    |  ShowJPanel1  |                                           |
    |  ShowJPanel2  |                                           |
    |  ShowJPanel3  |                                           |
    |                        |                                           |
    |                        |                                           |
    --------------------------------------------------------------------

    A problem usually becomes easier when you disregard technical specs for a moment and think about it from a functional standpoint. In this case it would be something like "when I click on a node in the tree, I want to display a specific panel", right?
    For your right panel, check out the CardLayout. It allows you to put multiple panels in the same space, while only one is visible at a time.
    For the JTree, check out the event listeners that are part of Swing. A MouseListener for example will allow you to listen for mouse clicks on a certain component, so the start would be to install a mouselistener in the JTree.
    A google search for something like "java JTree node mouselistener" will probably get you further on this subject, for example to get sample code how to get the currently selected node.

  • Problem extending JPanel

    Hi,
    What is the best format to have a class with a JFrame and a number of JPanels, one of which needs to be painted on using Graphics.
    class Demo extends JPanel{
    public JFrame frame;
    public JPanel panel1;
    public JPanel panel2;
    public JPanel panel3;
       Demo(){
          // initialise JFrame
          frame = new JFrame();
          // initialise a few JPanels
          panel1 = new JPanel();
          panel2 = new JPanel();
          panel3 = new JPanel();
          // refer to the JPanel I'm painting on
          frame.getContentPane(this);   // Is this correct?
         public void paint(Graphics g)     {
              g.drawString("Click below", 50, 50);               
                  // now this method should paint over one of the JPanels only, the one I'm extending..
    }Any thought appreciated.

    Thanks for the pointers Haynese ,
    I understand what I should be doing.
    I have another issue with this now, maybe its constructed badly...
    I can get the graphics objects on the JPanel to display but not the JButton or label I add. If I click in the region of the button and hit it, it appears. Any ideas?
    public class GraphEditor extends JPanel implements MouseListener
    public JButton button;
    public JLabel label5;
         public GraphEditor(){
              //  JPanel Button, displays if clicked on.
              button = new JButton("JPanel Button, displays if clicked on...");
              this.add(button);
                                             //  This should display but never does
              label5 = new JLabel("This should display but never does");
              add(label5);
              setSize(50,50);
              setVisible(true);
         public void paint(Graphics g)     {
                                            // This displays fine
              g.drawString("This displays fine", 5, 5);               
    }and:
    public class SystemWindow extends JFrame {     
    public JButton button;
    public JPanel topPanel;
    public JPanel bottomPanel;
    public JPanel mainPanel;
    public JLabel topPanelLabel;
    public JLabel bottomPanelLabel;
    public JButton getPathButton;
    private GraphEditor mainMap = new GraphEditor(this);
         SystemWindow(){     
             topPanel = new JPanel();
              bottomPanel = new JPanel();
              mainPanel = new JPanel();
              // 10 is horizontal
                                               // 01 is vertical
              getContentPane().setLayout(new GridLayout(0,1));
              getContentPane().add(mainPanel);
              mainPanel.add(topPanel);
              mainPanel.add(bottomPanel);
              topPanelLabel = new JLabel("Top Panel");
              topPanel.add(topPanelLabel);
              bottomPanelLabel = new JLabel("Bottom Panel");
              bottomPanel.add(bottomPanelLabel);
              button = new JButton("Save");
              //button.addActionListener(this);
              bottomPanel.add(button);
              getPathButton = new JButton("Get");
              //getPathButton.addActionListener(this);
              bottomPanel.add(getPathButton);
              getContentPane().add(mainMap);
              setTitle("App Title");          
              setSize(500,300);          
              setLocation(100,100);     
              mainPanel.setVisible(true);
              topPanel.setVisible(true);
             bottomPanel.setVisible(true);
             setVisible(true);
         }          Any suggestions welcome.

  • Exception when use getAppletContext().showDocument(url);

    I want to open a page using getAppletContext().showDocument(yourURL), but it troughs the following exception:
    java.lang.NullPointerException
    java.applet.Applet.getAppletContext(Unkonow Source)
    This happen when i put the getappletcontext() in a method that I invoke at the end of the proces of my applet..but when I put the getAppletcontext() in the first method of my applet it works......., but because of the flow of my applet I have to put the getAppletContext() at the end...
    So my quiestion is: when do I have to use getAppletContext() and why is this exception is happening?

    Here is the code: for instance if I put getAppletcontext().showDocument(url) in the init() method or even in the onButtonClick() method it works, but the place where i have to put it is in the onSendData() method, but there doesn't work and happened the exception.....
    public class TestApplet2 extends JApplet implements ActionListener {
    UCapture active;
    JButton button;
    JComboBox scanner;
    JPanel buttonPanel;
    JPanel comboPanel;
    JPanel activePanel;
    JFrame frame;
    int scannerElegido;
    public void init() {
    try {
    System.out.println("begin..........");
    active = new UCapture();
    Evento appListener = new Evento();
    active.add_DUCaptureEventsListener(appListener);
    } catch (Exception e) {
    System.out.println("error en el constructor........");
    e.printStackTrace();
    try {
    activePanel = new JPanel();
    activePanel.setBorder(BorderFactory.createLineBorder(Color.black));
    activePanel.add(active);
    button = new JButton(" Capture ");
    button.setMnemonic(KeyEvent.VK_C);
    button.setBorder(BorderFactory.createRaisedBevelBorder());
    buttonPanel = new JPanel();
    buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    buttonPanel.add(button);
    Container container = getContentPane();
    container.add(active,BorderLayout.CENTER);
    container.add(buttonPanel,BorderLayout.PAGE_START);
    String[] scanners= new String[numScanner+1];
    scanners[0] = "Select Scanner";
    for (int i = 1; i <= numScanner; i++) {
    scanners[i] = active.getSensorManufacturerTR(i);
    scanner = new JComboBox(scanners);
    scanner.setSelectedIndex(0);
    scanner.setBorder(BorderFactory.createRaisedBevelBorder());
    comboPanel = new JPanel();
    comboPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    comboPanel.add(scanner);
    container.add(comboPanel, BorderLayout.PAGE_END);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    onButtonClick();
    setVisible(true);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void onButtonClick() {
    try {
    scannerElegido = scanner.getSelectedIndex();
    boolean openSensor = active.openSensor(scannerElegido);
    boolean captureFinger = active.captureFinger();
    } catch (Exception ex) {
    ex.printStackTrace();
    public void onSendData(Template template) {
    try {
    URL urlServlet = new URL("http://localhost:8080/triad/test.do");
    URLConnection con = (URLConnection) urlServlet.openConnection();
    // con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type","application/x-java-serialized-object");
    // send data to the servlet
    ObjectOutputStream oos = new ObjectOutputStream(con.getOutputStream());
    oos.writeObject(template.getTemplate());
    oos.flush();
    oos.close();
    // receive result from servlet
    con.getInputStream();
    ObjectInputStream inputFromServlet = new ObjectInputStream(con.getInputStream());
    Object result = (Object) inputFromServlet.readObject();
    inputFromServlet.close();
    // HERE IS WHERE THE EXCEPTION OCCURS
    URL urlServlet1 = new URL("http://localhost:8080/triad/test.do");
    System.out.println(getAppletContext().ShowDocument( urlServlet1);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void stop() {
    try{
    active.closeSensor();
    catch (Exception ex) {
    ex.printStackTrace();
    public void actionPerformed(ActionEvent event) {
    }

  • Referencing main class from created instances

    The quick setup:
    My Main class creates a JFrame and adds a few custom JPanels. One of the JPanels has a mouse listener and responses to the mouse clicks, and it works great.
    I'd like to know if there's a way to have that JPanel invoke public, non-static methods from the Main class (the class which created it) without passing a reference for the instance of the Main class to the JPanel when it's (the JPanel) is created. Or is that the way you're supposed to do it?
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?
    Thanks so much,
    Matt

    Hi Rhesus21,
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?Yes, simply this way :
    public class MainFrame extends JFrame {
        private MyPanel panel;
        panel = new MyPanel(this);
    public class MyPanel extends JPanel {
        private MainFrame frame;
        public MyPanel(MainFrame frame) {
            this.frame = frame;
    }

  • Having a Translucent window, how to make a button not translucent?

    Seems to be a simple question. I have a JFrame that I make translucent following this guide:
    http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/
    I add a JPanel to this frame and it is also translucent and then I add JButtons to the JPanel. I want the buttons to be solid and not translucent.
    Having great problems, sure be happy if I got any advice.
    Shares some code, dont know if it helps, the buttons use imageicons. This is the Jpanel code:
    public class ClockFrame extends JPanel {
         private ClassLoader cl;
         private JButton[][] clock = new JButton[6][60];
         boolean gradient = true;
         public ClockFrame()
              this.setOpaque(!gradient);
              this.setLayout(null);
              this.setVisible(true);
              this.setDoubleBuffered(false);
              cl = this.getClass().getClassLoader();
              init();
          protected void paintComponent(Graphics g) {
             if (g instanceof Graphics2D && gradient) {
                 final int R = 240;
                 final int G = 240;
                 final int B = 240;
                 Paint p =
                 new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
                     getWidth(), getHeight(), new Color(R, G, B, 255), true);
                 Graphics2D g2d = (Graphics2D)g;
                 g2d.setPaint(p);
                 g2d.fillRect(0, 0, getWidth(), getHeight());
             } else {
                 super.paintComponent(g);
    private void buttonHelper(JButton b, double radix, int type)
              b.setBorderPainted(false);
              b.setContentAreaFilled(false);
              b.setFocusable(false);
              b.setBounds(findPosX(radix,type) + 250, findPosY(radix,type) + 200, 200, 200);
              this.add(b);
         }

    http://picasaweb.google.com/lh/photo/8g0eDzQs_0Qt3MJKBLMTDQ?feat=directlink
    can you see this image? think it shows pretty clearly what effect I wish to have. Picture is taken running from eclipse.
    I think it is a pretty interesting problem so will share rest of the code.
    First is Main JFrame class, second is AWTUtilitiesWrapper from guide posted in first post.
    public class MainFrame {
         private static final long serialVersionUID = 1L;
         private static JFrame frame;
         private static Container c;
        private boolean isTranslucencySupported;
        private GraphicsConfiguration translucencyCapableGC;
         public MainFrame()
              frame = new JFrame( "Time" );
              frame.setSize(800     ,      600);
              frame.setResizable(false);
              c = frame.getContentPane();
              c.setLayout(new OverlayLayout(c));
              c.add(new ClockFrame());
            isTranslucencySupported = AWTUtilitiesWrapper.isTranslucencySupported(AWTUtilitiesWrapper.PERPIXEL_TRANSLUCENT);
            translucencyCapableGC = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
            if (!AWTUtilitiesWrapper.isTranslucencyCapable(translucencyCapableGC)) {
                translucencyCapableGC = null;
                GraphicsEnvironment env =
                        GraphicsEnvironment.getLocalGraphicsEnvironment();
                GraphicsDevice[] devices = env.getScreenDevices();
                for (int i = 0; i < devices.length && translucencyCapableGC == null; i++) {
                    GraphicsConfiguration[] configs = devices.getConfigurations();
    for (int j = 0; j < configs.length && translucencyCapableGC == null; j++) {
    if (AWTUtilitiesWrapper.isTranslucencyCapable(configs[j])) {
    translucencyCapableGC = configs[j];
    if (translucencyCapableGC == null) {
    isTranslucencySupported = false;
              //sets custom location on screen and sets no default os border
              frame.setLocation(300,100);     
              frame.setUndecorated(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
              init();
         public static Container getContainer()
              return c;
         private void init()
              if(isTranslucencySupported)
              AWTUtilitiesWrapper.setWindowOpacity(frame, 0.7f);
              AWTUtilitiesWrapper.setWindowOpaque(frame, false);
    import java.awt.GraphicsConfiguration;
    import java.awt.Shape;
    import java.awt.Window;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author Anthony Petrov
    public class AWTUtilitiesWrapper {
    private static Class<?> awtUtilitiesClass;
    private static Class<?> translucencyClass;
    private static Method mIsTranslucencySupported, mIsTranslucencyCapable, mSetWindowShape, mSetWindowOpacity, mSetWindowOpaque;
    public static Object PERPIXEL_TRANSPARENT, TRANSLUCENT, PERPIXEL_TRANSLUCENT;
    static void init() {
    try {
    awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
    translucencyClass = Class.forName("com.sun.awt.AWTUtilities$Translucency");
    if (translucencyClass.isEnum()) {
    Object[] kinds = translucencyClass.getEnumConstants();
    if (kinds != null) {
    PERPIXEL_TRANSPARENT = kinds[0];
    TRANSLUCENT = kinds[1];
    PERPIXEL_TRANSLUCENT = kinds[2];
    mIsTranslucencySupported = awtUtilitiesClass.getMethod("isTranslucencySupported", translucencyClass);
    mIsTranslucencyCapable = awtUtilitiesClass.getMethod("isTranslucencyCapable", GraphicsConfiguration.class);
    mSetWindowShape = awtUtilitiesClass.getMethod("setWindowShape", Window.class, Shape.class);
    mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
    mSetWindowOpaque = awtUtilitiesClass.getMethod("setWindowOpaque", Window.class, boolean.class);
    } catch (NoSuchMethodException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    static {
    init();
    private static boolean isSupported(Method method, Object kind) {
    if (awtUtilitiesClass == null ||
    method == null)
    return false;
    try {
    Object ret = method.invoke(null, kind);
    if (ret instanceof Boolean) {
    return ((Boolean)ret).booleanValue();
    } catch (IllegalAccessException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    return false;
    public static boolean isTranslucencySupported(Object kind) {
    if (translucencyClass == null) {
    return false;
    return isSupported(mIsTranslucencySupported, kind);
    public static boolean isTranslucencyCapable(GraphicsConfiguration gc) {
    return isSupported(mIsTranslucencyCapable, gc);
    private static void set(Method method, Window window, Object value) {
    if (awtUtilitiesClass == null ||
    method == null)
    return;
    try {
    method.invoke(null, window, value);
    } catch (IllegalAccessException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
    Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
    public static void setWindowShape(Window window, Shape shape) {
    set(mSetWindowShape, window, shape);
    public static void setWindowOpacity(Window window, float opacity) {
    set(mSetWindowOpacity, window, Float.valueOf(opacity));
    public static void setWindowOpaque(Window window, boolean opaque) {
    set(mSetWindowOpaque, window, Boolean.valueOf(opaque));

  • Modal dialog issue

    I have subclassed JDialog in way that permits me to use it like this: String data = DialogUI.getData(...);
    However, it seams as if I have two conflicting requirements. I want the dialog to block until the user has made a selection. Then, the selection should be returned as illustrated. However, I want the dialog to close if they move to a different field.
    Is there a way (a hack) to close a modal dialog if the user clicks some outside the boundaries?
    If I have to make it non-modal, is there a way to make the dialog return a value when the dialog is closed?
    Also, does the following code make since, from an architecture and design view point?
    Next
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Insets;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    class DialogUI extends JDialog {
      private JButton _btnOk = null;
      private JPanel _pnlMain = null;
      private JPanel _pnlSouth = null;
      protected JPanel _pnlCenter = null;
      private String _result;
      public DialogUI(Frame frame){
        super(frame, "", true);
        _pnlSouth = new JPanel();
        _pnlSouth.setPreferredSize(new Dimension(0, 40));
        _pnlSouth.setMinimumSize(new Dimension(0, 0));
        _pnlSouth.setMaximumSize(new Dimension(0, 0));
        _pnlCenter = new JPanel();
        _pnlMain = new JPanel();
        _pnlCenter.setOpaque(true);
        _pnlMain.setLayout(new BorderLayout());
        _pnlMain.add(_pnlSouth, BorderLayout.SOUTH);
        _pnlMain.add(_pnlCenter, BorderLayout.CENTER);
        BoxLayout layout = new BoxLayout(_pnlSouth, BoxLayout.X_AXIS);
        _pnlSouth.setLayout(layout);
        _btnOk = new JButton("OK");
        _btnOk.setPreferredSize(new Dimension(50, 0));
        _btnOk.setText("OK");
        _btnOk.setActionCommand("OK");
        _btnOk.setMargin(new Insets(1,0,1,0));
        _pnlSouth.add(Box.createHorizontalGlue());
        _pnlSouth.add(_btnOk, null);
        this.getContentPane().add(_pnlMain);
        _btnOk.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
            _result = String.valueOf(new Date());
            dispose();
      public void open(){
        setSize(new Dimension(200, 100));
        setVisible(true);
      public static String getData(JComponent invoker) throws Exception{
        Frame frame = (Frame)javax.swing.SwingUtilities.getRoot(invoker);
        DialogUI dsw = new DialogUI(frame);
        dsw.setUndecorated(true);
        Point p = new Point();
        if(invoker != null){
          p.x = invoker.getLocationOnScreen().x;
          p.y = invoker.getLocationOnScreen().y + invoker.getHeight();
          dsw.setLocation(p);
        dsw.open();
        return dsw._result;
    public class TextMP extends JPanel {
      private JTextField _text;
      private JButton _button;
      public TextMP() {
        _text = new JTextField();
        _button = new JButton("X");
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        add(_text);
        add(_button);
      public JButton getButton() {
        return _button;
      public JTextField getText() {
        return _text;
      public static void main(String[] args) {
        final TextMP t = new TextMP();
        t.getButton().addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            try{
              String data = DialogUI.getData(t.getButton());
              t.getText().setText(data);
            catch(Exception e){
              e.printStackTrace();
        JFrame frame = new JFrame();
        frame.getContentPane().add(t);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }

    You should decide what is more important - forcing the end user to enter something, or allowing a default value.
    If you do the former, then keep it modal. If the later, then non-modal and default the field.
    I did not read through your code and so I don't know what you are trying to design. But I will say that it makes more sense in general (thinking of how most forms are designed - whether they be applications for the desktop, or the web) you allow the user to navigate over the form and enter or not at will. Then when some event is triggered - often a button being pressed - then you validate the entire form (or part of it if it is embedded in larger unit) and force entry or default depending on needs.
    ~Bill

  • ComponentListener works in Java 1.5, not in Java 1.6

    Hi there,
    I'm having an odd problem. I have a GUI application that has a JFrame with a JDesktopPane as its content pane, with several sub-windows (JInternalFrames).
    The master JFrame listens for when a JInternalFrame closes and performs an action. Each JInternalFrame executes:
    addComponentListener(parent);The JFrame (parent) implements ComponentListener and includes:
        public void componentHidden(ComponentEvent e) {
             System.out.println(e.getComponent().getClass().getName());
             dostuff();
        }This works fine with Java 1.5. But if I compile a .jar and run it on Java 1.6, componentHidden is never called.
    Any suggestions?
    Many thanks,
    Peter.

    Hello there!
    I've been experiencing similar problem. As the author of the original post I have JFrame and JDesktopPane on it. I have several JInternalFrames. Internal frame has BorderLayout. I have two JPanels, that I want to add to Internal frame (one at a time). Other JPanel is removed and made invisible by calling setVisible(false). When I am adding JPanel to internal frame and calling method setVisible(true), componnetShown method is called as it should be. When I call method setVisible(false) and remove JPanel, method componentHidden is not called. I did workaround by calling active_panel.getComponentListeners()[0].componentHidden(null) at the time when setVisible(false) is called, but I do not like that. I'd like to know if I am misunderstanding something or if it is a bug.

  • Image.getWidth(ImageObserver obs) returns -1

    hello everyone i have used following code to load an image
    URL location=Sprite.class.getClassLoader().getResource(path);
        img=Toolkit.getDefaultToolkit().getImage(location);and this code to draw an image:
    g2d.drawImage(img, x, y, this);now i need to know the width and height of image for detecting collision.
    getWidth() and getHeight() returns -1.
    System.out.println(img.getWidth(this));my images are getting displayed in the frame.but when i try to access width and height of an image then it returns -1 which means width and height of image is not known yet.
    help !!
    thanks.

    sorry.
    This problem is in my game code.Since the code is very long so i am giving a small code reflecting my problem
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.net.URL;
    import javax.swing.*;
    import java.awt.Graphics;
    public class Sprite extends JPanel
    private JFrame frame;
    private Image img;
    public Sprite()
    frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,400);
    frame.getContentPane().add(this);
    frame.setVisible(true);
    URL location=Sprite.class.getClassLoader().getResource("small.jpg");
    img=Toolkit.getDefaultToolkit().getImage(location);
    this.repaint();
    System.out.println(img.getWidth(null));
    public void paintComponent(Graphics g)
    g.drawImage(img,150,150,this);
    public static void main(String[] args)
    new Sprite();
    }So i want the width and height of an image.But when i try to get it, it just returns -1 which means width and height is not known yet, according to java doc.
    if i use img=new ImageIcon("small.jpg").getImage() to load an image and if i access the width and height of an image using img.getWidth(ImageObserver obs) then i get correct value of width and height.
    i want to use above code that i provided to load an image.So pls help me out.Why it is returning -1 ?.
    Edited by: JGarage on Dec 6, 2008 7:59 AM
    Edited by: JGarage on Dec 6, 2008 8:00 AM

  • Refreshing the panels when new content added?

    Hey, guys. My first post here; hope I'm not too much of a JNewbie for you. :)
    I'm getting my feet wet in Swing, working on an invoice program for work. I want it to look like a regular invoice, with fields for SKU, description, cost per unit, units, and total per line item. Right now, I have those five fields in a Jpanel that I add to the bottom of the layout.
    The problem is that I need the ability to go to File => Add New Item... and have another JPanel with those five fields add to the bottom so a 2nd item can be added to the form below the first. I tried making a function that adds them to the panel, using the same type of syntax that the generated code (using a form builder in NetBeans) did. I don't see the lines get added.
    My thought is that there is some function I need to call to redraw or refresh the panel so that the new components start drawing. However, my Great Javadoc Adventure has turned up no clues.
    Can anyone please give me a hand with making this happen, or at the least coming up with an alternate solution that will achieve similar results?
    Thanks much.
    Jaeden Stormes
    [email protected]

    I tried revalidate() , but no change.
    Here's the function I'm using to try to add the item...
    private void NewLineItem()
    javax.swing.JPanel jLine = new javax.swing.JPanel();
    jLine.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jItemCode.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jLine.add(jItemCode, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 110, -1));
    jCourseDelivery.setHorizontalAlignment(javax.swing.JTextField.LEFT);
    jLine.add(jCourseDelivery, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 0, 240, -1));
    jItemQuantity.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jLine.add(jItemQuantity, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 0, 110, -1));
    jItemRate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jLine.add(jItemRate, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 0, 100, -1));
    jItemAmount.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jLine.add(jItemAmount, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 0, 100, -1));
    jLineItemSection.add(jLine);
    jLineItemSection.revalidate();
    pack();
    JLineItemSection is a JPanel inside my frame.
    Any suggestions? I think the way I am using the AbsoluteContraints is screwed up, as I'm having a lot of trouble with the layouts in general. The form editor in NetBeans (at least, the version in 3.6) needs a LOT of work.

Maybe you are looking for

  • Help!! ipod touch 2nd gen (8gb) is running by itself!

    I just got a ipod touch 2nd gen (8gb) from a friend. This ipod has some problem.. it is running by itself! When I on it, and for example go to Settings, it will just randomly go to a next selection as if responding to my selection but I never touch a

  • Export attachments to Excel

    Is it possible to export an attachment (or an indicator of an attachment) to Excel, from a fillable form, using the "Merge Data Files Into Spreadsheet" option?  My fillable form PDF has two paperclip (attach file) documents inserted into it (as an ex

  • Dreamcolor LP2480zx monitor showing red tint in every inputs

    Hi, I recently obtained this monitor from someone else and when I first power it on, I noticed that it is showing a red tint. At first, I suspect that someone was playing around with the settings so I did a factory reset. Nothing changed. Then I susp

  • Controling itunes on another mac

    Hi there. I really want to be able to control itunes on my main mac from my iBook. I have wireless networking and so far have tried: AirControl Which is really really bad. iHam on iRye. Nice interface, totally chokes on large libraries, I gave up wai

  • OS X Mavericks breaks Bonjour printing

    Since upgrading to Mavericks none of my machines can reliably print on a wireless Canon MX885 I have followed all steps including removing MAC address filtering and making the network SID broadcast installing all the newest drivers but after few days