Problem with jDialog in a JFrame

Hello to everyone...i'm newby java GUI developer, and i've got a problem with a JDialog within a JFrame...
I made a JFrame which creates a new customized JDialog in his contructor, like this:
MioJdialog dlg = new MioJdialog(this, true);
dlg.setVisible(true);
...The "MioJdialog" class store his JFrame parent under a private attribute, in this way:
class MioJdialog {...
private Frame parent;
public MioJdialog (Frame parent, boolean modal){
    this.parent=parent;
....}and here's the problem: when i try to close the parent JFrame with a command like this:
parent.dispose();
( in order to close the whole window), sometimes happens that the JFrame is still visible on the screen...and i don't know why...
got some hints?
thanks to everyone!
Edited by: akyra on Jan 14, 2008 4:36 AM
Edited by: akyra on Jan 14, 2008 4:37 AM
Edited by: akyra on Jan 14, 2008 4:37 AM

If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
http://homepage1.nifty.com/algafield/sscce.html
Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
http://forum.java.sun.com/help.jspa?sec=formatting

Similar Messages

  • Problem with JDialogs

    Hi All,
    I have a problem with JDialogs in my standalone application. This app pops-up multiple JDialogs, say a stack of JDialogs.
    I have a standalone application which runs as a JFrame, call it JFrame1, which is working fine. JFrame1 pops-up a JDialog, on some button click on JFrame1, call it JDialog1, which is also working fine. Now JDialog1 pops-up another JDialog, again on some button click on JDialog1, call it JDialog2, which is too working fine. But, after I finish with JDialog2 and dispose it my JDialog1 is not working fine, though that is the front dialog at present.
    Any ideas why JDialog1 is not working fine? Am I missing anything?
    Thanks,
    Srinivas.

    Hi,
    I have a component called DateComponent that works similar to a JComboBox. When you click a small button of DateComponent, it pops-up a Calendar similar to the drop down list of JComboBox and user can pick a date from it. It gets closed when it loses focus.
    I have this DateComponent on JFrame1, JDialog1 and JDialog2. The Calendar is not being diaplayed on JDialog1 upon clicking the small button of DateComponent after JDialog2 is disposed. But it is being diaplayed properly on JDialog1 before JDialog1 opens JDialog2. What could be wrong?
    I am using JDK1.3.1.
    Thanks,
    Srinivas.

  • Problem with JDialog box

    Hi Guys,
    I have a problem with the JDialog box. The close button (Cross mark of the box) is not displayed when I was trying to use my custom LookAndFeel and Custom theme. I am pasting the code sample here.
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.LookAndFeel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
    import javax.swing.plaf.ColorUIResource;
    import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
    import com.jgoodies.looks.plastic.PlasticTheme;
    import com.medplexus.looks.plastic.theme.SkyGreen;
    public class TestTheDialog implements ActionListener {
    JFrame mainFrame = null;
    JButton myButton = null;
    public TestTheDialog() {
    mainFrame = new JFrame("TestTheDialog Tester");
    mainFrame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    try{
         MyLookAndFeel.setCurrentTheme(new CustomLaF());
         UIManager.setLookAndFeel(new MyLookAndFeel());
         SwingUtilities.updateComponentTreeUI(mainFrame);
         CustomDialog cd = new CustomDialog();
         cd.setDefaultLookAndFeelDecorated(true);
    catch(Exception e){
    myButton = new JButton("Test the dialog!");
    myButton.addActionListener(this);
    mainFrame.setLocationRelativeTo(null);
    mainFrame.getContentPane().add(myButton);
    mainFrame.setSize(200, 150);
    //mainFrame.pack();
    mainFrame.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    if(myButton == e.getSource()) {
    System.err.println("Opening dialog.");
    CustomDialog myDialog = new CustomDialog(mainFrame, true, "Do you like Java?");
    System.err.println("After opening dialog.");
    if(myDialog.getAnswer()) {
    System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
    else {
    System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
    static class CustomLaF extends PlasticTheme {
    protected ColorUIResource getPrimary1() {
    return new ColorUIResource(255,128,0);
    public ColorUIResource getPrimary2() {
              return (new ColorUIResource(Color.white));
         public ColorUIResource getPrimary3() {
              return (new ColorUIResource(255,128,0));
    public ColorUIResource getPrimaryControl() {
    return new ColorUIResource(Color.GREEN);
    protected ColorUIResource getSecondary1() {
    return new ColorUIResource(Color.CYAN);
    protected ColorUIResource getSecondary2() {
              return (new ColorUIResource(Color.gray));
         protected ColorUIResource getSecondary3() {
              return (new ColorUIResource(235,235,235));
         protected ColorUIResource getBlack() {
              return BLACK;
         protected ColorUIResource getWhite() {
              return WHITE;
         private Object getIconResource(String s) {
    return LookAndFeel.makeIcon(getClass(), s);
    private Icon getHastenedIcon(String s, UIDefaults uidefaults) {
    Object obj = getIconResource(s);
    return (Icon) ((javax.swing.UIDefaults.LazyValue) obj).createValue(uidefaults);
    static class MyLookAndFeel extends Plastic3DLookAndFeel {
              protected void initClassDefaults(UIDefaults table) {
                   super.initClassDefaults(table);
              protected void initComponentDefaults(UIDefaults table) {
                   super.initComponentDefaults(table);
                   Object[] defaults = {
                             "MenuItem.foreground",new ColorUIResource(Color.white),
                             "MenuItem.background",new ColorUIResource(Color.gray),
                             "MenuItem.selectionForeground",new ColorUIResource(Color.gray),
                             "MenuItem.selectionBackground",new ColorUIResource(Color.white),
                             "Menu.selectionForeground", new ColorUIResource(Color.white),
                             "Menu.selectionBackground", new ColorUIResource(Color.gray),
                             "MenuBar.background", new ColorUIResource(235,235,235),
                             "Menu.background", new ColorUIResource(235,235,235),
                             "Desktop.background",new ColorUIResource(235,235,235),
                             "Button.select",new ColorUIResource(255,128,0),
                             "Button.focus",new ColorUIResource(255,128,0),
                             "TableHeader.background", new ColorUIResource(255,128,0),
                             "TableHeader.foreground", new ColorUIResource(Color.white),
                             "ScrollBar.background", new ColorUIResource(235,235,235),
                             "OptionPane.questionDialog.border.background", new ColorUIResource(Color.gray),
                             "OptionPane.errorDialog.titlePane.foreground", new ColorUIResource(Color.white),
                             "OptionPane.questionDialog.titlePane.background", new ColorUIResource(255,128,0),
                             "InternalFrame.borderColor", new ColorUIResource(Color.gray),
                             "InternalFrame.activeTitleForeground", new ColorUIResource(Color.white),
                             "InternalFrame.activeTitleBackground", new ColorUIResource(Color.gray),
                             "InternalFrame.borderColor", new ColorUIResource(Color.white),
                             "Table.selectionBackground",new ColorUIResource(255,128,0)
                   table.putDefaults(defaults);
    public static void main(String argv[]) {
    TestTheDialog tester = new TestTheDialog();
    package CustomThemes;
    import javax.swing.JDialog;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import java.awt.event.ActionEvent;
    public class CustomDialog extends JDialog implements ActionListener {
    private JPanel myPanel = null;
    private JButton yesButton = null;
    private JButton noButton = null;
    private boolean answer = false;
    public boolean getAnswer() { return answer; }
    public CustomDialog(){
    public CustomDialog(JFrame frame, boolean modal, String myMessage) {
    super(frame, modal);
    setTitle("Guess?");
    myPanel = new JPanel();
    getContentPane().add(myPanel);
    myPanel.add(new JLabel(myMessage));
    yesButton = new JButton("Yes");
    yesButton.addActionListener(this);
    myPanel.add(yesButton);
    noButton = new JButton("No");
    noButton.addActionListener(this);
    myPanel.add(noButton);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pack();
    setLocationRelativeTo(frame);
    setVisible(true);
    public void actionPerformed(ActionEvent e) {
    if(yesButton == e.getSource()) {
    System.err.println("User chose yes.");
    answer = true;
    setVisible(false);
    else if(noButton == e.getSource()) {
    System.err.println("User chose no.");
    answer = false;
    setVisible(false);
    Thanks and Regards
    Kumar.

    Hi All,
    I am using the JGoodies Look and feel (looks2.0.1.jar). I wrote my own custom LookAndFeel and Theme , but the problem with this is the JDialog/JOptionPane dialog boxes are displayed with out the close button (cross button on the titlebar).
    I am pasting the code here.
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.LookAndFeel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
    import javax.swing.plaf.ColorUIResource;
    import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
    import com.jgoodies.looks.plastic.PlasticTheme;
    import com.medplexus.looks.plastic.theme.SkyGreen;
    public class TestTheDialog implements ActionListener {
        JFrame mainFrame = null;
        JButton myButton = null;
        public TestTheDialog() {
            mainFrame = new JFrame("TestTheDialog Tester");
            mainFrame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {System.exit(0);}
            try{
                 MyLookAndFeel.setCurrentTheme(new CustomLaF());
                 UIManager.setLookAndFeel(new MyLookAndFeel());
                 //Plastic3DLookAndFeel.setCurrentTheme(new SkyGreen());
                 //UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
                 SwingUtilities.updateComponentTreeUI(mainFrame);
                 CustomDialog cd = new CustomDialog();
                 cd.setDefaultLookAndFeelDecorated(true);
            catch(Exception e){
            myButton = new JButton("Test the dialog!");
            myButton.addActionListener(this);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.getContentPane().add(myButton);
            mainFrame.setSize(200, 150);
            //mainFrame.pack();
            mainFrame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            if(myButton == e.getSource()) {
                System.err.println("Opening dialog.");
                CustomDialog myDialog = new CustomDialog(mainFrame, true, "Do you like Java?");
                System.err.println("After opening dialog.");
                if(myDialog.getAnswer()) {
                    System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
                else {
                    System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
        static class CustomLaF extends PlasticTheme {
            protected ColorUIResource getPrimary1() {
              return new ColorUIResource(255,128,0);
            public ColorUIResource getPrimary2() {
                  return (new ColorUIResource(Color.white));
             public ColorUIResource getPrimary3() {
                  return (new ColorUIResource(255,128,0));
            public ColorUIResource getPrimaryControl() {
              return new ColorUIResource(Color.GREEN);
            protected ColorUIResource getSecondary1() {
              return new ColorUIResource(Color.CYAN);
            protected ColorUIResource getSecondary2() {
                  return (new ColorUIResource(Color.gray));
             protected ColorUIResource getSecondary3() {
                  return (new ColorUIResource(235,235,235));
             protected ColorUIResource getBlack() {
                  return BLACK;
             protected ColorUIResource getWhite() {
                  return WHITE;
             private Object getIconResource(String s) {
                return LookAndFeel.makeIcon(getClass(), s);
            private Icon getHastenedIcon(String s, UIDefaults uidefaults) {
                Object obj = getIconResource(s);
                return (Icon) ((javax.swing.UIDefaults.LazyValue) obj).createValue(uidefaults);
          static class MyLookAndFeel extends Plastic3DLookAndFeel {
                  protected void initClassDefaults(UIDefaults table) {
                       super.initClassDefaults(table);
                  protected void initComponentDefaults(UIDefaults table) {
                       super.initComponentDefaults(table);
                       Object[] defaults = {
                                 "MenuItem.foreground",new ColorUIResource(Color.white),
                                 "MenuItem.background",new ColorUIResource(Color.gray),
                                 "MenuItem.selectionForeground",new ColorUIResource(Color.gray),
                                 "MenuItem.selectionBackground",new ColorUIResource(Color.white),
                                 "Menu.selectionForeground", new ColorUIResource(Color.white),
                                 "Menu.selectionBackground", new ColorUIResource(Color.gray),
                                 "MenuBar.background", new ColorUIResource(235,235,235),
                                 "Menu.background", new ColorUIResource(235,235,235),
                                 "Desktop.background",new ColorUIResource(235,235,235),
                                 "Button.select",new ColorUIResource(255,128,0),
                                 "Button.focus",new ColorUIResource(255,128,0),
                                 "TableHeader.background", new ColorUIResource(255,128,0),
                                 "TableHeader.foreground", new ColorUIResource(Color.white),
                                 "ScrollBar.background",  new ColorUIResource(235,235,235),
                                 "OptionPane.questionDialog.border.background", new ColorUIResource(Color.gray),
                                 "OptionPane.errorDialog.titlePane.foreground", new ColorUIResource(Color.white),
                                 "OptionPane.questionDialog.titlePane.background", new ColorUIResource(255,128,0),
                                 "InternalFrame.borderColor", new ColorUIResource(Color.gray),
                                 "InternalFrame.activeTitleForeground", new ColorUIResource(Color.white),
                                 "InternalFrame.activeTitleBackground", new ColorUIResource(Color.gray),
                                 "InternalFrame.borderColor", new ColorUIResource(Color.white),
                                 "Table.selectionBackground",new ColorUIResource(255,128,0)
                       table.putDefaults(defaults);
        public static void main(String argv[]) {
            TestTheDialog tester = new TestTheDialog();
    import javax.swing.JDialog;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import java.awt.event.ActionEvent;
    public class CustomDialog extends JDialog implements ActionListener {
        private JPanel myPanel = null;
        private JButton yesButton = null;
        private JButton noButton = null;
        private boolean answer = false;
        public boolean getAnswer() { return answer; }
        public CustomDialog(){
        public CustomDialog(JFrame frame, boolean modal, String myMessage) {
            super(frame, modal);
            setTitle("Guess?");
            myPanel = new JPanel();
            getContentPane().add(myPanel);
            myPanel.add(new JLabel(myMessage));
            yesButton = new JButton("Yes");
            yesButton.addActionListener(this);
            myPanel.add(yesButton);       
            noButton = new JButton("No");
            noButton.addActionListener(this);
            myPanel.add(noButton);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setLocationRelativeTo(frame);
            setVisible(true);
        public void actionPerformed(ActionEvent e) {
            if(yesButton == e.getSource()) {
                System.err.println("User chose yes.");
                answer = true;
                setVisible(false);
            else if(noButton == e.getSource()) {
                System.err.println("User chose no.");
                answer = false;
                setVisible(false);
    }Thanks and Regards
    Kumar.

  • Problem with JDialogs and Threads

    Hi. I'm new to this forum and I hope I'm not asking a repeat question. I didn't find what I needed after a quick search of existing topics.
    I have this problem with creating a new JDialog from within a thread. I have a class which extends JDialog and within it I'm running a thread which calls up another JDialog. My problem is that the JDialog created by the Thread does not seem to function. Everything is unclickable except for the buttons in the titlebar. Is there something that I'm missing out on?

    yeah, bad idea, don't do that.

  • Problem with Background image and JFrame

    Hi there!
    I've the following problem:
    I created a JFrame with an integrated JPanel. In this JFrame I display a background image. Therefore I've used my own contentPane:
    public class MContentPane extends JComponent{
    private Image backgroundImage = null;
    public MContentPane() {
    super();
    * Returns the background image
    * @return Background image
    public Image getBackgroundImage() {
    return backgroundImage;
    * Sets the background image
    * @param backgroundImage Background image
    public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    * Overrides the painting to display a background image
    protected void paintComponent(Graphics g) {
    if (isOpaque()) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    if (backgroundImage != null) {
    g.drawImage(backgroundImage,0,0,this);
    super.paintComponent(g);
    Now the background image displays correct. But as soon as I click on some combobox that is placed within the integrated JPanel I see fractals of the opened combobox on the background. When I minimize
    the Frame they disappear. Sometimes though I get also some fractals when resizing the JFrame.
    It seems there is some problem with the redrawing of the background e.g. it doesn't get redrawn as often as it should be!?
    Could anyone give me some hint, on how to achieve a clear background after clicking some combobox?
    Thx in advance

    I still prefer using a border to draw a background image:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class CentredBackgroundBorder implements Border {
        private final BufferedImage image;
        public CentredBackgroundBorder(BufferedImage image) {
            this.image = image;
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = x + (width-image.getWidth())/2;
            int y0 = y + (height-image.getHeight())/2;
            g. drawImage(image, x0, y0, null);
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        public boolean isBorderOpaque() {
            return true;
    }And here is a demo where I load the background image asynchronously, so that I can launch the GUI before the image is done loading. Warning: you may find the image disturbing...
    import java.awt.*;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BackgroundBorderExample {
        public static void main(String[] args) throws IOException {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame f = new JFrame("BackgroundBorderExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea area = new JTextArea(24,80);
            area.setForeground(Color.WHITE);
            area.setOpaque(false);
            area.read(new FileReader(new File("BackgroundBorderExample.java")), null);
            final JScrollPane sp = new JScrollPane(area);
            sp.setBackground(Color.BLACK);
            sp.getViewport().setOpaque(false);
            f.getContentPane().add(sp);
            f.setSize(600,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
            final Border bkgrnd = new CentredBackgroundBorder(ImageIO.read(new URL(url)));
            Runnable r = new Runnable() {
                public void run() {
                    sp.setViewportBorder(bkgrnd);
                    sp.repaint();
            SwingUtilities.invokeLater(r);
    }

  • Problem with submit button of jframe

    hi all
    i am having problems with the submit button. once the submit button is clicked the values should be updated to an array of objects. it is doing this. the problem is i want the current frame to close once i click submit button. i have a GUI at the background and once i click something this frame appears asking for details for th user to input. but i want only the current form to close, not the whole progrmy code is shown below
    thanks in advance
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class TextForm extends JPanel {
    public JTextField[] fields;
    public MainInteractiveMap mainClass;
    public TextForm(MainInteractiveMap m)
    mainClass= m;
    public TextForm(String[] labels, char[] mnemonics, int[] widths, String[] tips)
    super(new BorderLayout());
    JPanel labelPanel= new JPanel(new GridLayout(labels.length,1));
    JPanel fieldPanel= new JPanel(new GridLayout(labels.length,1));
    add(labelPanel, BorderLayout.WEST);
    add(fieldPanel, BorderLayout.CENTER);
    fields= new JTextField[labels.length];
    for(int i=0; i< labels.length;i+=1)
    fields[i] = new JTextField();
    if (i<tips.length)fields.setToolTipText(tips[i]);
    if (i<widths.length)fields[i].setColumns(widths[i]);
    JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
    lab.setLabelFor(fields[i]);
    if (i<mnemonics.length)lab.setDisplayedMnemonic(mnemonics[i]);
    labelPanel.add(lab);
    JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
    p.add(fields[i]);
    fieldPanel.add(p);
    public String getText(int i){
    return (fields[i].getText());
    public void printForm()
    String[] labels = {"Location","No of Bedrooms","No of Bathrooms", "Garage","last selling price","current selling price"};
    char[] mnemonics ={'L','B','b','G','L','C'};
    int[] widths = {15,1,1,4,9,9};
    String[] desc = {"Location","No of Bedrooms","No of Bathrooms", "Garage","last selling price","current selling price"};
    final TextForm form = new TextForm(labels,mnemonics,widths,desc);
    JButton submit = new JButton("Submit");
    submit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
    String location;
    final int sellingPrice;
    final int numOfRooms;
    final int marketPrice;
    final int numOfBathrooms;
    final int numOfGarages;
    location=form.getText(0);
    sellingPrice=Integer.parseInt(form.getText(1));
    numOfRooms=Integer.parseInt(form.getText(2));
    marketPrice=Integer.parseInt(form.getText(3));
    numOfBathrooms=Integer.parseInt(form.getText(4));
    numOfGarages=Integer.parseInt(form.getText(5));
    mainClass.Testing(location);
    System.out.println(numOfGarages);
    System.exit(0);
    JFrame f = new JFrame("Input details of House");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(form, BorderLayout.NORTH);
    JPanel p = new JPanel();
    p.add(submit);
    f.getContentPane().add(p, BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
    regards

    you just need to change (at end of actionPerformed())
    System.exit(0);
    to
    [whateverFrame].dispose();
    easier to show a simple demo
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JButton btn1 = new JButton("Open new Frame");
        final JFrame f1 = new JFrame("#1");
        f1.getContentPane().add(btn1);
        f1.pack();
        f1.setLocationRelativeTo(null);
        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f1.setVisible(true);
        btn1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            JButton btn2 = new JButton("Close/Return");
            final JFrame f2 = new JFrame("#2");
            f2.getContentPane().add(btn2);
            f2.pack();
            f2.setLocationRelativeTo(null);
            f2.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//do not want to close with 'X'
            f1.setVisible(false);
            f2.setVisible(true);
            btn2.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent ae){
                f2.dispose();
                f1.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Problems with JDialog

    I've got a JFrame opened with a menu from where I open a modal JDialog, this JDialog window has a button, let say a "Cancel button" which I want to use to close this J Dialog window, let say to hide it, I do not want to lose the instances variables of this JDialog object, after hiding this JDialgo pressing it's "Cancel button", I want to be able to return to the JFrame, and I want to be able to show this JDialog frome the menu like at the begining, and of course with all the information that I could introduce in the JDialog (not losing instances variables of the JDialog hidden), I don't Know how to do it, I would apreciate any information or help in how to do it, thankyou very much

    Do not create ("new") the modal JDialog everytime the menu is selected. Instead create it in the constructor of your JFrame. Then show() this dialog when its clicked, and hide() when the cancel is selected. In this way, the same dialog would be used everytime, retaining all values and variables in the dialog.

  • 'Philosophical' problem with JDialog

    I'm looking for advices to manage my modal Dialogs windows in my application.
    I precise that I'm not searching the solution for a specific problem but a general way of coding.
    How can I retrieve the result of a modal window in the bean which launch it ? I need to know if the window has been closed by a OK button (for example) or if it has been closed by a cancel button or a the System cross (in Windows). I need to get either results from the editing done in that window.
    I see one solution :
    - Creating a specific parameterClass with all the field I need in the specific context in the Bean and pass it to the Window (constructor or setter). The window fill it and the bean read it when finished.
    Is this solution the one you are using in your developments ? Is there other solutions ? Am I annoying with my questions ? :-)
    P.S. : Please excuse my 'lots of mistakes' english...

    I use a canceled property in the custom dialog that defaults to true. If the user selects Ok, then the dialog(or its controller) sets the property to false. Then when the the code comes back to the controlling class I can check the value of isCanceled() and get other properties as appropriate. You can also have the controlling class listen for an event like the ok button being clicked (or whatever, depending on how much you want to abstract).
    Mark

  • Problem with  getLayout() on a JFrame

    Hello,
    Thank you for reading my post and trying to help me.
    Something is a bit unclear to me. I create a JFrame object and give it a GridLayout as in the following:
            JFrame frame = new JFrame();
            frame.setLayout(new GridLayout(3, 2, 15, 15));I pass this JFrame object to another class constructor and save it as a private variable of type JFrame, and at some point I want to be able to return this GridLayout so I call getLayout() in a method of that class: GridLayout currentLayout = (GridLayout) frame.getLayout();.
    I typecast the returned member because it is a LayoutManager, a class that GridLayout implements. When I run this code, I get a runtime error saying getLayout() returned a BorderLayout and I cannot typecast it to a GridLayout.
    This is where I am confused. As I passted a GridLayout to setLayout() before, how come getLayout() gives me back a BorderLayout please? Is there anyway to get the GridLayout back rather than store it as a variable please (the use of this GridLayout is very rare, which is why I would like to avoid keeping a variable for it) ?
    I really appreciate your help and thank you for helping me.

    Jary316 wrote:
    Thank you, it is a bit strange they chose it to work this way but it explains it.Not really when you read on why they do this: [http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html]
    It increases the flexibility and power of Swing.

  • Problem with a template method in JDialog

    Hi friends,
    I'm experiencing a problem with JDialog. I have a base abstract class ChooseLocationDialog<E> to let a client choose a location for database. This is an abstract class with two abstract methods:
    protected abstract E prepareLocation();
    protected abstract JPanel prepareForm();Method prepareForm is used in the constructor of ChooseLocationDialog to get a JPanel and add it to content pane.
    Method prepareLocation is used to prepare location of a database. I have to options - local file and networking.
    There are two subclasses ChooseRemoteLocationDialog and ChooseLocalFileDialog.
    When I start a local version, ChooseLocalFileDialog with one input field for local file, everything works fine and my local client version starts execution.
    The problem arises when I start a network version of my client. Dialog appears and I can enter host and port into the input fields. But when I click Select, I get NullPointerException. During debugging I noticed that the values I entered into these fields ("localhost" for host and "10999" for port) were not set for corresponding JTextFields and when my code executes getText() method for these input fields it returns empty strings. This happens only for one of these dialogs - for the ChooseRemoteLocationDialog.
    The code for ChooseLocationDialog class:
    public abstract class ChooseLocationDialog<E> extends JDialog {
         private E databaseLocation;
         private static final long serialVersionUID = -1630416811077468527L;
         public ChooseLocationDialog() {
              setTitle("Choose database location");
              setAlwaysOnTop(true);
              setModal(true);
              Container container = getContentPane();
              JPanel mainPanel = new JPanel();
              //retrieving a form of a concrete implementation
              JPanel formPanel = prepareForm();
              mainPanel.add(formPanel, BorderLayout.CENTER);
              JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
              JButton okButton = new JButton(new SelectLocationAction());
              JButton cancelButton = new JButton(new CancelSelectAction());
              buttonPanel.add(okButton);
              buttonPanel.add(cancelButton);
              mainPanel.add(buttonPanel, BorderLayout.SOUTH);
              container.add(mainPanel);
              pack();
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              Dimension screenSize = toolkit.getScreenSize();
              int x = (screenSize.width - getWidth()) / 2;
              int y = (screenSize.height - getHeight()) / 2;
              setLocation(x, y);
              addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        super.windowClosing(e);
                        System.exit(0);
         public E getDatabaseLocation() {
                return databaseLocation;
         protected abstract E prepareLocation();
         protected abstract JPanel prepareForm();
          * Action for selecting location.
          * @author spyboost
         private class SelectLocationAction extends AbstractAction {
              private static final long serialVersionUID = 6242940810223013690L;
              public SelectLocationAction() {
                   putValue(Action.NAME, "Select");
              @Override
              public void actionPerformed(ActionEvent e) {
                   databaseLocation = prepareLocation();
                   setVisible(false);
         private class CancelSelectAction extends AbstractAction {
              private static final long serialVersionUID = -1025433106273231228L;
              public CancelSelectAction() {
                   putValue(Action.NAME, "Cancel");
              @Override
              public void actionPerformed(ActionEvent e) {
                   System.exit(0);
    }Code for ChooseLocalFileDialog
    public class ChooseLocalFileDialog extends ChooseLocationDialog<String> {
         private JTextField fileTextField;
         private static final long serialVersionUID = 2232230394481975840L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel();
              panel.add(new JLabel("File"));
              fileTextField = new JTextField(15);
              panel.add(fileTextField);
              return panel;
         @Override
         protected String prepareLocation() {
              String location = fileTextField.getText();
              return location;
    }Code for ChooseRemoteLocationDialog
    public class ChooseRemoteLocationDialog extends
              ChooseLocationDialog<RemoteLocation> {
         private JTextField hostField;
         private JTextField portField;
         private static final long serialVersionUID = -2282249521568378092L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel(new GridLayout(2, 2));
              panel.add(new JLabel("Host"));
              hostField = new JTextField(15);
              panel.add(hostField);
              panel.add(new JLabel("Port"));
              portField = new JTextField(15);
              panel.add(portField);
              return panel;
         @Override
         protected RemoteLocation prepareLocation() {
              String host = hostField.getText();
              int port = 0;
              try {
                   String portText = portField.getText();
                   port = Integer.getInteger(portText);
              } catch (NumberFormatException e) {
                   e.printStackTrace();
              RemoteLocation location = new RemoteLocation(host, port);
              return location;
    }Code for RemoteLocation:
    public class RemoteLocation {
         private String host;
         private int port;
         public RemoteLocation() {
              super();
         public RemoteLocation(String host, int port) {
              super();
              this.host = host;
              this.port = port;
         public String getHost() {
              return host;
         public void setHost(String host) {
              this.host = host;
         public int getPort() {
              return port;
         public void setPort(int port) {
              this.port = port;
    }Code snippet for dialog usage in local client implementation:
    final ChooseLocationDialog<String> dialog = new ChooseLocalFileDialog();
    dialog.setVisible(true);
    location = dialog.getDatabaseLocation();
    String filePath = location;Code snippet for dialog usage in network client implementation:
    final ChooseLocationDialog<RemoteLocation> dialog = new ChooseRemoteLocationDialog();
    dialog.setVisible(true);
    RemoteLocation location = dialog.getDatabaseLocation();Exception that I'm getting:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:42)
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:1)
         at suncertify.client.gui.dialog.ChooseLocationDialog$SelectLocationAction.actionPerformed(ChooseLocationDialog.java:87)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
         at java.awt.Component.processMouseEvent(Component.java:6134)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
         at java.awt.Component.processEvent(Component.java:5899)
         at java.awt.Container.processEvent(Container.java:2023)
         at java.awt.Component.dispatchEventImpl(Component.java:4501)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
         at java.awt.Container.dispatchEventImpl(Container.java:2067)
         at java.awt.Window.dispatchEventImpl(Window.java:2458)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
         at java.awt.Dialog$1.run(Dialog.java:1046)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Client VM (build 1.6.0-b09, mixed mode, sharing)
    OS: Ubuntu 8.04
    Appreciate any help.
    Thanks.
    Edited by: spyboost on Jul 24, 2008 5:38 PM

    What a silly error! I have to call Integer.parseInt instead of getInt. Integer.getInt tries to find a system property. A small misprint, but a huge amount of time to debug. I always use parseInt method and couldn't even notice that silly misprint. Sometimes it's useful to see the trees instead of whole forest :)
    It works perfectly. Sorry for disturbing.

  • Esc key not working with JDialog

    Hi,
    We are facing a KeyListening problem with JDialog. We developed an application using JRE 1.4.0. When we migrate from 1.4.0 to 1.4.2.The Esc keys(All keys) associated with the JDialog is not listening. Following is code piece is showing the Esc key. The same piece of code is working with 1.4.0 and with lesser versions. U'r help will be appriciated.
    import java.awt.Container;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    public class EscDialog extends JDialog implements KeyListener {
         static EscDialog ed = new EscDialog();
         public static void main(String[] args) {
              ed.setSize(200, 300);
              ed.addKeyListener(ed);
              JButton jb = new JButton("Test");
              JPanel jp = new JPanel();
              jp.add(jb);
              Container cp = ed.getContentPane();
              cp.add(jp);
              ed.show();
         public void keyPressed(KeyEvent anEvent) {
              if (anEvent.getKeyCode() == KeyEvent.VK_ESCAPE)
                   System.exit(0);
         public void keyTyped(KeyEvent anEvent) {
         public void keyReleased(KeyEvent anEvent) {
    }

    An example:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JDialog {
        public Test () {
            getContentPane ().setLayout (new FlowLayout ());
            getContentPane ().add (new JLabel ("Press escape to exit..."));
            getRootPane ().getInputMap ().put (KeyStroke.getKeyStroke (KeyEvent.VK_ESCAPE, 0), "dispose");
            getRootPane ().getActionMap ().put ("dispose", new AbstractAction () {
                public void actionPerformed (ActionEvent event) {
                    dispose ();
            pack ();
            setDefaultCloseOperation (DO_NOTHING_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

  • Problem with refreshing JFrames and JDialogs

    My program is based on few JDialogs and one JFrame. I'm still changing them, one time one of the JDialogs is visible, other time JFrame. During this change I call dispose() for one window or frame and I create (if it wasn't created before) other component and call setVisible(true) for it. Problem is that sometimes (only sometimes! like 5% of calls) my windows appears but they are not refreshing (not showing new objects added to their lists or sth like that) until I resize my window by dragging mouse on the edge of it. Is there anyway to ensure that window will be displayed properly?

    I ran into this problem about a year ago...so I don't really remember but I think a call to validate(), or paint() or repaint() or something like that should do the trick (forgive me for not knowing the exact one but as I said it has been a while). Its been about that year since I stopped coding in java and moved to c#. You want the window to redraw its self what ever that is.

  • Problems with 'background' JFrame focus when adding a modal JDialog

    Hi all,
    I'm trying to add a modal JDialog to my JFrame (to be used for data entry), although I'm having issues with the JFrame 'focus'. Basically, at the moment my program launches the JFrame and JDialog (on program load) fine. But then - if I switch to another program (say, my browser) and then I try switching back to my program, it only shows the JDialog and the main JFrame is nowhere to be seen.
    In many ways the functionality I'm looking for is that of Notepad: when you open the Find/Replace box (albeit it isn't modal), you can switch to another program, and then when you switch back to Notepad both the main frame and 'JDialog'-esque box is still showing.
    I've been trying to get this to work for a couple of hours but can't seem to. The closest I have got is to add a WindowFocusListener to my JDialog and I hide it via setVisible(false) once windowLostFocus() is fired (then my plan was to implement a similar functionality in my JFrame class - albeit with windowGainedFocus - to show the JDialog again, i.e. once the user switches back to the program). Unfortunately this doesn't seem to work; I can't seem to get any window or window focus listeners to actually fire any methods, in fact?
    I hope that kind of makes sense lol. In short I'm looking for Notepad CTRL+R esque functionality, albeit with a modal box. As for a 'short' code listing:
    Main.java
    // Not all of these required for the code excerpt of course.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsEnvironment;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicSplitPaneDivider;
    import javax.swing.plaf.basic.BasicSplitPaneUI;
    public class Main extends JFrame implements ActionListener, WindowFocusListener, WindowListener, FocusListener {
         static JFrame frame;
         private static int programWidth;
         private static int programHeight;
         private static int minimumProgramWidth = 700;
         private static int minimumProgramHeight = 550;
         public static SetupProject setupProjectDialog;
         public Main() {
              // Setup the overall GUI of the program
         private static void createSetupProjectDialog() {
              // Now open the 'Setup Your Project' dialog box
              // !!! Naturally this wouldn't auto-open on load if the user has already created a project
              setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );
              // Okay, for this we want it to be (say) 70% of the progamWidth/height, OR *slightly* (-25px) smaller than the minimum size of 700/550
              // Change (base on programWidth/Height) then setLocation
              int currProgramWidth = getProgramWidth();
              int currProgramHeight = getProgramHeight();
              int possibleWidth = (int) (currProgramWidth * 0.7);
              int possibleHeight = (int) (currProgramHeight * 0.7);
              // Set the size and location of the JDialog as needed
              if( (possibleWidth > (minimumProgramWidth-25)) && (possibleHeight > (minimumProgramHeight-25)) ) {
                   setupProjectDialog.setPreferredSize( new Dimension(possibleWidth,possibleHeight) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-(possibleWidth/2)), ((currProgramHeight/2)-(possibleHeight/2)) );
               else {
                   setupProjectDialog.setPreferredSize( new Dimension( (minimumProgramWidth-25), (minimumProgramHeight-25)) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-((minimumProgramWidth-25)/2)), ((currProgramHeight/2)-((minimumProgramHeight-25)/2)) );
              setupProjectDialog.setResizable(false);
              setupProjectDialog.toFront();
              setupProjectDialog.pack();
              setupProjectDialog.setVisible(true);
         public static void main ( String[] args ) {
              Main frame = new Main();
              frame.pack();
              frame.setVisible(true);
              createSetupProjectDialog();
            // None of these get fired when the Jframe is switched to. I also tried a ComponentListener, but had no joy there either.
         public void windowGainedFocus(WindowEvent e) {
              System.out.println("Gained");
              setupProjectDialog.setVisible(true);
         public void windowLostFocus(WindowEvent e) {
              System.out.println("GainedLost");
         public void windowOpened(WindowEvent e) {
              System.out.println("YAY1!");
         public void windowClosing(WindowEvent e) {
              System.out.println("YAY2!");
         public void windowClosed(WindowEvent e) {
              System.out.println("YAY3!");
         public void windowIconified(WindowEvent e) {
              System.out.println("YAY4!");
         public void windowDeiconified(WindowEvent e) {
              System.out.println("YAY5!");
         public void windowActivated(WindowEvent e) {
              System.out.println("YAY6!");
         public void windowDeactivated(WindowEvent e) {
              System.out.println("YAY7!");
         public void focusGained(FocusEvent e) {
              System.out.println("YAY8!");
         public void focusLost(FocusEvent e) {
              System.out.println("YAY9!");
    SetupProject.java
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SetupProject extends JDialog implements ActionListener {
         public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
              // Bad code. Is only temporary
              add( new JLabel("This is a test.") );
              // !!! TESTING
              addWindowFocusListener( new WindowFocusListener() {
                   public void windowGainedFocus(WindowEvent e) {
                        // Naturally this now doesn't get called after the setVisible(false) call below
                   public void windowLostFocus(WindowEvent e) {
                        System.out.println("Lost");
                        setVisible(false); // Doing this sort of thing since frame.someMethod() always fires a null pointer exception?!
    }Any help would be very much greatly appreciated.
    Thanks!
    Tristan

    Hi,
    Many thanks for the reply. Isn't that what I'm doing with the super() call though?
    As in, in Main.java I'm doing:
    setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );Then the constructor in SetupProject is:
    public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              And isn't the super call (since the class extends JDialog) essentially like doing new JDialog(frame,title,modal)?
    If not, that would make sense due to the null pointer exception errors I've been getting. Although I did think I'd done it right hence am confused as to the right way to handle this,if so.
    Thanks,
    Tristan
    Edited by: 802573 on 20-Oct-2010 08:27

  • Is there a problem with JFrame and window listeners?

    As the subject implies, i'm having a problem with my JFrame window and the window listeners. I believe i have implemented it properly (i copied it from another class that works). Anyway, none of the events are caught and i'm not sure why. Here's the code
    package gcas.gui.plan;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.util.Hashtable;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import gcas.plandata.TaskData;
    import gcas.util.GCASProperties;
    import gcas.gui.planlist.MainPanel;
    * MainFrame extends JPanel and is the main class for the plan details window
    public class MainFrame extends JFrame implements WindowListener
         * the container for this window
        private Container contentPane;
         * a string value containing the name of the plan being viewed
        private String labelText;
         * a string value containing the name of the window (GCAS - plan list)
        private static String title;
         * an instance of JDialog class
        private static MainFrame dialog;
         * hashTable that correlates the task name to its id as found in the
         * plan
        private Hashtable taskNameToId = new Hashtable();
         * an instance of taskSetPane.  This is the current instance of taskSetPane
         * being viewed
        private PlanTaskSet currentPane;
         * instance of TaskData class.  Each instance will hold information on
         * an individual task
        private TaskData taskData;
         * hashTable containing instances of the taskSetPane class
        private Hashtable taskSetPanes = new Hashtable();
         * an instance of the OuterPanel class
        OuterPanel mainPanel;
         * an instance of the ButtonPanel class
        ButtonPanel buttonsPanel;
         * an instance of the LeftPanel class
        LeftPanel leftPanel;
         * an instance of the the GCASProperties class
        GCASProperties gcasProps;
        private static MainFrame thisPlanMain = null;
        private MainPanel planListMain;
         * constructor for MainFrame
         * @param frame the parent frame calling this class
         * @param locationComp the location of the component that initiated the opening of the dialog
         * @param labelText the name of the plan that is being viewed
         * @param title title of window
        private MainFrame(JFrame frame, Component locationComp, String labelText,
                String title)
            super(title);
            gcasProps = GCASProperties.getInstance();
            mainPanel = new OuterPanel(labelText, currentPane,
                    taskNameToId, taskSetPanes);
            leftPanel = mainPanel.getLeftPanel();
            System.out.println("LABLE: " + labelText);
            leftPanel.setMainPanelContents();
            buttonsPanel = new ButtonPanel(labelText, taskSetPanes,
                    taskNameToId, leftPanel);
            contentPane = getContentPane();
            contentPane.add(mainPanel, BorderLayout.CENTER);
            contentPane.add(buttonsPanel, BorderLayout.PAGE_END);
            this.addWindowListener(this);
            this.labelText = labelText;
            pack();
            setLocationRelativeTo(locationComp);
            this.setVisible(true);
            planListMain = MainPanel.getInstance();
            planListMain.setVisible(false);
        public static MainFrame getInstance(JFrame frame, Component locationComp, String labelText,
                String title)
            if (thisPlanMain == null)
                thisPlanMain = new MainFrame(frame, locationComp, labelText,
                        title);
            return thisPlanMain;
        public static MainFrame getDialogObject()
        {   //from the location this is called (ButtonPanel), this will never
            //be null
            return thisPlanMain;
        public static void setABMDDialogNull()
            thisPlanMain = null;
         * returns an instance of MainFrame
         * @return MainFrame instance
        public static MainFrame getDialog()
            return dialog;
         * setter for MainFrame
         * @param aDialog a MainFrame instance
        public static void setDialog(MainFrame aDialog)
            dialog = aDialog;
         * window opened event
         * @param windowEvent the window event passed to this method
        public void windowOpened(WindowEvent windowEvent)
         * The window event when a window is closing
         * @param windowEvent the window event passed to this method
        public void windowClosing(WindowEvent windowEvent)
            gcasProps.storeProperties("PlanList");
            MainPanel abmd = MainPanel.getInstance();
    //        planMain = this.getDialogObject();
    //        if(planMain != null)
    //            planMain.setVisible(false);
    //            abmd.setVisible(true);
    //            planMain.setABMDDialogNull();
            if(this.getDialogObject()!= null)
                abmd.setVisible(true);
                setVisible(false);
                setABMDDialogNull(); 
         * Invoked when the Window is set to be the active Window
         * @param windowEvent the window event passed to this method
        public void windowActivated(WindowEvent windowEvent)
         * Invoked when a window has been closed as the result of calling dispose on the window
         * @param windowEvent the window event passed to this method
        public void windowClosed(WindowEvent windowEvent)
         * Invoked when a Window is no longer the active Window
         * @param windowEvent the window event passed to this method
        public void windowDeactivated(WindowEvent windowEvent)
            System.out.println("HI");
         * Invoked when a window is changed from a minimized to a normal state
         * @param windowEvent the window event passed to this method
        public  void windowDeiconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
           System.out.println("Invoked when a window is changed from a minimized to a normal state.");
         * Invoked when a window is changed from a normal to a minimized state
         * @param windowEvent the window event passed to this method
        public  void windowIconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
    //        System.out.println("Invoked when a window is changed from a normal to a minimized state.");
    }anyone know whats wrong?

    It turned out that my ide was running the old jar and not updating it, so no matter what code i added, it wasn't being seen. Everything should be fine now.

  • Problem with setContentPane() in JFrame class

    I recently discovered a problem with the setContentPane method in the JFrame class. When I use setContentPane(Container ..), the previously existing contentPane remains in the stack. I have tried nullifying getContentPane(), and all manner of things, but, each time I use setContentPane, I have another instance of a JPanel in the stack.
    I'm using code similar to setContentPane(new CustomJPanel()); and each time the user changes screens, and a similar call to that is made, the old CustomJPanel instance remains in the stack. Can anyone suggest a way around this? On their own the panels do not take up very much memory, but after several hours of usage, they will build up.

    I tried what you suggested; it only resulted in a huge performance decrease. The problem with memory allocation is still there.
    Here is the method I use to switch screens in my app:
    public static void changeScreen (JPanel panel){
              try{
                   appFrame.setTitle("Wordinary : \""+getTitle()+"\"");
                   appFrame.setContentPane(panel);
                   appFrame.setSize(appFrame.getContentPane().getPreferredSize());     
                   appFrame.getContentPane().setBackground(backColour);
                   for (int i = 0; i < appFrame.getContentPane().getComponents().length; i++)
                        appFrame.getContentPane().getComponents().setForeground(textColour);
                   //System.out.println("Background colour set to "+backColour+" text colour set to "+textColour);
                   appFrame.validate();
              catch (Exception e){
                   //System.out.println("change");
                   e.printStackTrace();
    And it is called like this:
    changeScreen(new AddWordPanel());The instantiation of the new instance is what is causing the memory problems, but I can't think of a way around it.

Maybe you are looking for

  • Re: OracleDriver cannot be resolved to a type

    I still have the same problem which was reported in the first post. I tried all the changes mentioned above but doesn't help as I am totally new to jsp please suggest me a way out in detail. An error occurred at line: 6 in the jsp file: /one.jsp orac

  • I am having trouble with a photo book when I preview

    I am having trouble submitting a photo book because the images are showing up funny when I preview.  Can you help me to fix this problem?  I spent weeks making this as a gift.  Am so disappointed.

  • UE-V 2.0 Bug

    Hi there I'm not sure if anyone has reported this before or if there is a fix already but I could not find anything about it anywhere. Basically once you install UE-V 2.0 and you use the default Microsoft templates, when you double click an excel spr

  • How access SWF Library items?

    Is it possible to access SWF Library items from main FLA? Ex: I am loading swf on level1, i want to access level1 library items from level0 file

  • KPI's in BIP report (up and down arrows) - How?

    All, Can we show the KPI's (Key Performance Indicators) i.e. the up and down arrows indicating increase or decrease of performance. if yes, please explain how. thanks in advance. Narasimha