2 classes, open JDialog

I am new to Java... and have a problem: I have two classes in 2 different files (2 main methods). The first class, "Game", displays a JFrame with JPanel etc etc. Then I created a second class, "CTabel", that shows a complex table - I used the Netbeans 5 GUI Builder to do this. It's a JDialog (public class CTable extends javax.swing.JDialog)
I am feeling a bit sheepish about it but I don't know how to open this CTable from my first class "Game" :/
Thanks for your help!

But one of the fundamentals is missing: how do I call a class which is in another file? How can I call "public class CTable extends javax.swing.JDialog" from my first class?
Hmm... It's really hard to know exactly where your disjoint is so I'll punt.
You can instantiate an object of type CTable with:
CTable table = new CTable();  //using default constructor, there may be others....Then, since it extends JDialog you can display it with:
table.setVisible(true);If, when you say "I have two main functions" that you wrote two functions with this header:
public staic void main(String []args) {Then you're probably going to want to move some code around. Minimally, you won't be calling main() on CTable. To be more robust, you'd move almost all logic out of both main() methods and into the constructors and bodies of your two classes. You may even want to use a common practice of having a jbInit() method which can be called in GUI classes, so that different constructors can easily provide consistent behavior.
Currently you may have something like:
class CTable extends JDialog {
    //A few over-ridden methods exist here perhaps.
    public static void main(String []args) {
        //almost all code exists here....
class Game {
    //A few utility methods etc may exist here...
    public static void main(String []args) {
        //almost all code exists here....
}What you could try is:
class CTable extends JDialog {
    CTable() {
        super();
        jbInit();
    CTable(JComponent parent) {
        super(parent);
        jbInit();
    jbInit() {
        //All GUI initialization goes here.
    //Other useful functionality goes here, modularized into methods.
    //A few over-ridden methods exist here perhaps.
    public static void main(String []args) {
        //almost all code exists here....
class Game {
    Game() {
        initialize();
    initialize() {
        //most initialization logic goes here...
    public void startPlaying() {
        //game is set into motion (assuming it was initalized) here.
    //Useful/modular methods, and possibly even internal classes exist here.
    public static void main(String []args) {
        Game g = new Game();
        g.startPlaying();
}This may seem rather long and tedious, but it's a powerful framework, and moves the complexity of your code out of one or two knots into a common framework that other programmers will easily understand. (Also, how you organize your code is all about your own personal "coding style" so feel free to look around at other's projects and examples and use ideas you really like...)
One final thought here. I'm not going to recommend some book or tutorial at this point, because it's clear that you're very new to programming (and from the last thread/discussion we had) that you're picking things up pretty quickly. Instead, I recommend you get into a good basic "intro" to programming class as quickly as possible, perhaps at a local community college if you can't find anything else more available.
This would give you a solid foundation and teach you some good habits early so you don't have to break bad habits later on. (We could debate the relative merits of self-directed study and formal education all day, but my personal experience is that close contact with a seasoned educator is the most effective way to learn the fundamentals.)
Oh yeah... and if I'm way off base here, a code snippet or two would help us figure out what's going on.

Similar Messages

  • Constructing a class extending JDialog when invoked from main application

    In an application that extends JFrame a method, showJDialogGUI, is called to instantiate an object of another class (called enterGUI) that extends JDialog. This object, enterGUIDialog, is modal; user must click on its Submit button in order to dismiss it and be able to continue in MainProgram. I have troubles getting error messages resolved when the constructor of the enterGUIDialog JDialog object is called. Perhaps there are other things wrong with below code. Any help appreciated - snippet of code from both classes is below.
    public class MainProgram extends JFrame {
    enterGUI enterGUIDialog; // declaration for object of class extending JDialog
    public MainProgram() {     // constructor
    myContainer = getContentPane();
    showJDialogGUI(); // calls method to initialize
    public void showJDialogGUI() {
    enterGUIDialog = new enterGUI (this, true);
    enterGUIDialog.setDefaultCloseOperation (DISPOSE_ON_CLOSE );
    enterGUIDialog.setSize(200,200);
    enterGUIDialog.setVisible( true );
    enterGUIDialog.show();
    } // end of class MainProgram
    public class enterGUI extends JDialog{
    Container myContainer;
    JPanel myPanel;
    //// How to call the constructor to create this JDialog????
    public loginGUI( JRootPane theRoot, boolean theModal ) // passed in 'this', and 'true'
    // or maybe??? public About(Frame parent, boolean modal) {
    this.setRootPane( theRoot ); //???????
    // or maybe ??? super(theRoot, flag);
    //super(theRoot, flag); // calls Dialog class constructor
    this.setModal( theModal ); // ?????
    myContainer = getContentPane();
    myContainer.setLayout( new FlowLayout() );
    thePanel = new JPanel();
    // next add components to JPanel, then add to the JDialog container
    fieldsPanel.add( pageLabel ); etc.
    myContainer.add( fieldsPanel );
    // etc.
    myContainer.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
    myContainer.setVisible(true);
    } // end of constructor
    // more methods etc
    }

    Error received is:
    E:\Ghost>
    MainProgram.java:670: cannot resolve symbol
    symbol : constructor enterGUI (MainProgram,boolean)
    location: class MyPackage.enterGUI
    enterGUIDialog = new enterGUI(this, true);
    'new enterGUI(this, true); ' seems to be at start of
    error
    TIAThe error message could not be any more clear. To wit: the compiler is telling you it cannot find a constructor for class enterGUI that takes as parameters a reference to a javax.swing.JFrame, and a boolean value. Supply the constructor and the error will not be raised.

  • Writing a class to open jDialog that can be used over and over

    Hi All
    I am hoping that some out there can help me with this.
    I have a lot of Dialogs that I what to open and close.
    I am using the code to do that , and it works fine.
    What i would like to do is write a class that I can call and just pass in the name of the dialog that I what to open.
    Something like this
    private String dialogeName;
    dialogeName = Contacts;
    So from another class using a button I could do this type of call
    some way of passing into this class the Dialog name. I don't know how to do that ether .
    Is there some way of getting to this private String dialogeName; from another class ??
    Is this posable ??
    PLEASE SOMEONE HELP ME .....................
        Contacts dlg = new Contacts();   // Works fine  but to have to call the same code over and over
       // is a pain and the only difference is the name of the dialog.
        dialogeName = Contacts;  // this is what I would like to be able to do
       // dialogeName dlg = new dialogeName();
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = getSize();
        Point loc = getLocation();
        dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x,
                        (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setModal(true);
        dlg.pack();
        dlg.show();Thanks to all that have taken the time to look and to help
    Craig

    Why not simply create a method that wraps all the redundant stuff?
    public JDialog showDialog(JDialog dlg)
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = dlg.getSize();
        Point loc = dlg.getLocation();
        dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x,
                        (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setModal(true);
        dlg.pack();
        dlg.show();
        return dlg;
    }Then you could call it with all your various dialog types:
    Contacts dlg = (Contacts)showDialog(new Contacts());
    OtherDialog dlg2 = (OtherDialog)showDialog(new OtherDialog());Of course in this example Contacts and OtherDialog classes must extend JDialog.

  • Eclispe e4 application in part class open with scene builder time ERROR

    com.oracle.javafx.authoring.persist.FXMLDocument$FxmlParseException: Failed to load FXML file
    at com.oracle.javafx.authoring.persist.FXMLDocument.makeParseException(FXMLDocument.java:400)
    at com.oracle.javafx.authoring.persist.FXMLDocument.load(FXMLDocument.java:311)
    at com.oracle.javafx.authoring.persist.FXMLDocument.checkLayout(FXMLDocument.java:239)
    at com.oracle.javafx.authoring.persist.FXMLDocument.checkLayout(FXMLDocument.java:224)
    at com.oracle.javafx.authoring.Project.forFxml(Project.java:835)
    at com.oracle.javafx.authoring.Project.forFxml(Project.java:807)
    at com.oracle.javafx.authoring.DesignerTool.loadFXMLLayout(DesignerTool.java:197)
    at com.oracle.javafx.authoring.DesignerTool.loadFXMLLayout(DesignerTool.java:185)
    at com.oracle.javafx.authoring.DesignerTool.commonInit(DesignerTool.java:513)
    at com.oracle.javafx.authoring.DesignerTool.init(DesignerTool.java:457)
    at com.oracle.javafx.authoring.SceneBuilderLauncher$RunningWithJMXInstance.launch(SceneBuilderLauncher.java:71)
    at com.oracle.javafx.authoring.Main.start(Main.java:72)
    at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
    at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
    at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
    at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
    at java.lang.Thread.run(Thread.java:724)
    Caused by: javafx.fxml.LoadException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[2,1]
    Message: Content is not allowed in prolog.
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2180)
    at com.oracle.javafx.authoring.persist.FXMLDocument$2.call(FXMLDocument.java:301)
    at com.oracle.javafx.authoring.util.Utils.withFXMLDefaultClassLoader(Utils.java:2216)
    at com.oracle.javafx.authoring.persist.FXMLDocument.load(FXMLDocument.java:298)
    ... 21 more
    Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[2,1]
    Message: Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598)
    at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:88)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2150)
    ... 24 more

    Without seeing the file you open is SB we can't help. But to me it looks
    like the FXML is invalid at least for SBs parser.
    Tom
    On 22.07.15 08:12, Lalit Solanki wrote:
    > com.oracle.javafx.authoring.persist.FXMLDocument$FxmlParseException:
    > Failed to load FXML file
    > at
    > com.oracle.javafx.authoring.persist.FXMLDocument.makeParseException(FXMLDocument.java:400)
    >
    > at
    > com.oracle.javafx.authoring.persist.FXMLDocument.load(FXMLDocument.java:311)
    >
    > at
    > com.oracle.javafx.authoring.persist.FXMLDocument.checkLayout(FXMLDocument.java:239)
    >
    > at
    > com.oracle.javafx.authoring.persist.FXMLDocument.checkLayout(FXMLDocument.java:224)
    >
    > at com.oracle.javafx.authoring.Project.forFxml(Project.java:835)
    > at com.oracle.javafx.authoring.Project.forFxml(Project.java:807)
    > at
    > com.oracle.javafx.authoring.DesignerTool.loadFXMLLayout(DesignerTool.java:197)
    >
    > at
    > com.oracle.javafx.authoring.DesignerTool.loadFXMLLayout(DesignerTool.java:185)
    >
    > at
    > com.oracle.javafx.authoring.DesignerTool.commonInit(DesignerTool.java:513)
    > at com.oracle.javafx.authoring.DesignerTool.init(DesignerTool.java:457)
    > at
    > com.oracle.javafx.authoring.SceneBuilderLauncher$RunningWithJMXInstance.launch(SceneBuilderLauncher.java:71)
    >
    > at com.oracle.javafx.authoring.Main.start(Main.java:72)
    > at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
    > at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
    > at
    > com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
    > at
    > com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
    > at java.security.AccessController.doPrivileged(Native Method)
    > at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
    > at
    > com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
    >
    > at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    > at
    > com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
    > at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
    > at java.lang.Thread.run(Thread.java:724)
    > Caused by: javafx.fxml.LoadException:
    > javax.xml.stream.XMLStreamException: ParseError at [row,col]:[2,1]
    > Message: Content is not allowed in prolog.
    > at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2180)
    > at
    > com.oracle.javafx.authoring.persist.FXMLDocument$2.call(FXMLDocument.java:301)
    >
    > at
    > com.oracle.javafx.authoring.util.Utils.withFXMLDefaultClassLoader(Utils.java:2216)
    >
    > at
    > com.oracle.javafx.authoring.persist.FXMLDocument.load(FXMLDocument.java:298)
    >
    > ... 21 more
    > Caused by: javax.xml.stream.XMLStreamException: ParseError at
    > [row,col]:[2,1]
    > Message: Content is not allowed in prolog.
    > at
    > com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598)
    >
    > at
    > javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:88)
    >
    > at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2150)
    > ... 24 more
    >

  • Class opener

    1-  i've a class '1' with her function
    2-  i've another class '2' with other function
    now in class 1 i create a new object for class 2 and i go in  her function:
    //example
    //in my class 1 to the top
    //preloaduve is class 2
    //////THIS IS PART OF CLASS 1
    Dim PreloadUve As PreloadUve
    dim str as string
    ......code
    ....code
    ....code ecc
    public function go()
    preloaduve = new preloaduve
    str = "hello boy"
    PreloadUve.myfunction()
    end function
    //////THIS IS PARTOF CLASS 2
    public function myfunction()
      class2.messagebox(class1.str) //THIS DON'T WORKING
       //in this point i want to ask a class 1, the value of str, but i can't use a parameter function, this is a stupid example , i have another problem, ma this is the concept
    end function

    Ciao Gianluca,
    1 This Forum is about SAP Business One SDK - as you know - whereas your question is a general question about programming and therefore it does not fit in here (there are several sites in the Web which are about such issues)
    2 Unless you pass a reference to the instance of the class 1 object which creates the class 2 object to the class 2 object, you have to declare the variable str as a static variable of class 1
    Regards,
    Frank
    PS: it seems that it might help you to if you would gather some more knowledge about OO programming since your question is pretty basic?

  • Btn in JFrame to Open JDialog

    Hi Guys
    In NetBeans GUI Builder I have created and designed a MainGUI (JFrame Form) that has some buttons. I also went ahead and created and designed a SubGUI (JDialog Form).
    What do I need to do to link MainGUI to SubGUI through the press of a button ????
    I have added the ActionPerformed / ActionEvent method to the button, and inside that I have tried:
    SubGUI.setVisible(true);but it doesn't work !!
    I would greatly appreciate any help.
    Thank You.

    Here is the other bit that I think might be relevant:
    private void starterBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            StarterDialog.setVisible(true);
        private void maincourseBtnActionPerformed(java.awt.event.ActionEvent evt) {                                             
            MainCourseDialog.setVisible(true);
        private void dessertBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            DessertDialog.setVisible(true);
        private void adminBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
            AdminDialog.setVisible(true);
        private void starterListMouseClicked(java.awt.event.MouseEvent evt) {                                        
            Starter selectedStarter = (Starter)starterList.getSelectedValue();
            if (selectedStarter != null)
                populateSDialog(selectedStarter);
        private void sOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        private void sCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            this.dispose();
        private void maincourseListMouseClicked(java.awt.event.MouseEvent evt) {                                           
            MainCourse selectedMC = (MainCourse)maincourseList.getSelectedValue();
            if (selectedMC != null)
                populateMCDialog(selectedMC);
        private void mcOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
            // TODO add your handling code here:
        private void mcCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
        private void dessertListMouseClicked(java.awt.event.MouseEvent evt) {                                        
            Dessert selectedDessert = (Dessert)dessertList.getSelectedValue();
            if (selectedDessert != null)
                populateDDialog(selectedDessert);
        private void dOKBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
            // TODO add your handling code here:
        private void dCancelBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
            // TODO add your handling code here:
        private void populateSDialog(Starter s1)
            sNameJLi.setText(s1.getName());
            sCalsJLi.setText(String.valueOf(s1.getCalories()));
            sDescTA.setText(s1.getDescription());
            sPriceJLi.setText(String.valueOf(s1.getPrice()));
        private void populateMCDialog(MainCourse mc1)
            mcNameJLi.setText(mc1.getName());
            mcCalsJLi.setText(String.valueOf(mc1.getCalories()));
            mcDescTA.setText(mc1.getDescription());
            mcPriceJLi.setText(String.valueOf(mc1.getPrice()));
        private void populateDDialog(Dessert d1)
            dNameJLi.setText(d1.getName());
            dCalsJLi.setText(String.valueOf(d1.getCalories()));
            dDescTA.setText(d1.getDescription());
            dPriceJLi.setText(String.valueOf(d1.getPrice()));
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainGUI().setVisible(true);
        }

  • Z10 and First Class ( an Open Text application for corporate email)

    Hi
    I recently upgraded to a Z10 from a Bold 9800. I had no problems adding email accounts to my previous model but the current Z10 is not accepting my First Class (Open Text) email work account with the Upper Grand DSB. I have tried the regular add on application and then also tried adding it as an IMAP (with Rogers). Is there an issue with some email apps? I've spoken with both Rogers and Target (who sold me the phone) but no one can help....

    Hi
    I recently upgraded to a Z10 from a Bold 9800. I had no problems adding email accounts to my previous model but the current Z10 is not accepting my First Class (Open Text) email work account with the Upper Grand DSB. I have tried the regular add on application and then also tried adding it as an IMAP (with Rogers). Is there an issue with some email apps? I've spoken with both Rogers and Target (who sold me the phone) but no one can help....

  • 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

  • JFrames and JDialog

    I have a parent JFrame window which instantiates a customised JDialog window (DW1) which in turn initantiates another JDialog window(DW2). DW2 instantiates another small Message Dialog window (MD)( sub class of JDialog ) . This has ok button which when I click nothing happens. But if I close DW2 the ok button on MD becomes active.
    Does anybody know why this happens ? All these JDialog windows have the same JFrame parent .

    java version "1.3.0_02"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0_02)
    Java HotSpot(TM) Client VM (build 1.3.0_02, mixed mode)
    I haven't had any problems opening multiple JFrames. The issue you mentioned with 1.3.1 a bug?

  • How to use the Rectangle class to draw an image and center it in a JPanel

    I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
    I have divided the code into three parts. They are all supposed to be on one file in order to execute.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class CenterRect extends JPanel {
        public static Rectangle srcRect;
        Insets insets = null;
        Image image;
        MyImage imp;
        private double magnification;
        private int dstWidth, dstHeight;
        public CenterRect(MyImage imp){
            insets = getInsets();
            this.imp = imp;
            int width = imp.getWidth();
            int height = imp.getHeight();
            ImagePanel.init();
            srcRect = new Rectangle(0,0, width, height);
            srcRect.setLocation(0,0);
            setDrawingSize(width, height);
            magnification = 1.0;
        public void setDrawingSize(int width, int height) {
            dstWidth = width;
            dstHeight = height;
            setSize(dstWidth, dstHeight);
        public void paintComponent(Graphics g) {
            Image img = imp.getImage();
         try {
                if (img!=null)
                    g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
              srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);
            catch(OutOfMemoryError e) {e.printStackTrace();}
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Opener().openImage();
    class Opener{
        private String dir;
        private String name;
        private static String defaultDirectory;
        JFrame parent;
        public Opener() {
            initComponents();
         public void initComponents(){
            parent = new JFrame();
            parent.setContentPane(ImagePanel.panel);
            parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
            parent.setVisible(true);
        public void openDialog(String title, String path){
            if (path==null || path.equals("")) {
                FileDialog fd = new FileDialog(parent, title);
                defaultDirectory = "dir.image";
                if (defaultDirectory!=null)
                    fd.setDirectory(defaultDirectory);
                fd.setVisible(true);
                name = fd.getFile();
                if (name!=null) {
                    dir = fd.getDirectory();
                    defaultDirectory = dir;
                fd.dispose();
                if (parent==null)
                    return;
            } else {
                int i = path.lastIndexOf('/');
                if (i==-1)
                    i = path.lastIndexOf('\\');
                if (i>0) {
                    dir = path.substring(0, i+1);
                    name = path.substring(i+1);
                } else {
                    dir = "";
                    name = path;
        public MyImage openImage(String directory, String name) {
            MyImage imp = openJpegOrGif(dir, name);
            return imp;
        public void openImage() {
            openDialog("Open...", "");
            String directory = dir;
            String name = this.name;
            if (name==null)
                return;
            MyImage imp = openImage(directory, name);
            if (imp!=null) imp.show();
        MyImage openJpegOrGif(String dir, String name) {
                MyImage imp = null;
                Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
                if (img!=null) {
                    imp = new MyImage(name, img);
                    FileInfo fi = new FileInfo();
                    fi.fileFormat = fi.GIF_OR_JPG;
                    fi.fileName = name;
                    fi.directory = dir;
                    imp.setFileInfo(fi);
                return imp;
    }

    This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
    class MyImage implements ImageObserver{
        private int imageUpdateY, imageUpdateW,width,height;
        private boolean imageLoaded;
        private static int currentID = -1;
        private int ID;
        private static Component comp;
        protected ImageProcessor ip;
        private String title;
        protected Image img;
        private static int xbase = -1;
        private static int ybase,xloc,yloc;
        private static int count = 0;
        private static final int XINC = 8;
        private static final int YINC = 12;
        private int originalScale = 1;
        private FileInfo fileInfo;
        ImagePanel win;
        /** Constructs an ImagePlus from an AWT Image. The first argument
         * will be used as the title of the window that displays the image. */
        public MyImage(String title, Image img) {
            this.title = title;
             ID = --currentID;
            if (img!=null)
                setImage(img);
        public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
             imageUpdateY = y;
             imageUpdateW = w;
             imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
         return !imageLoaded;
        public int getWidth() {
             return width;
        public int getHeight() {
             return height;
        /** Replaces the ImageProcessor, if any, with the one specified.
         * Set 'title' to null to leave the image title unchanged. */
        public void setProcessor(String title, ImageProcessor ip) {
            if (title!=null) this.title = title;
            this.ip = ip;
            img = ip.createImage();
            boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
         width = ip.getWidth();
         height = ip.getHeight();
         if (win!=null && newSize) {
                win = new ImagePanel(this);
        public void draw(){
            CenterRect ic = null;
            win = new ImagePanel(this);
            if (win!=null){
                win.addIC(this);
                win.getCanvas().repaint();
                ic = win .getCanvas();
                win.panel.add(ic);
                int width = win.imp.getWidth();
                int height = win.imp.getHeight();
                Point ijLoc = new Point(10,32);
                if (xbase==-1) {
                    xbase = 5;
                    ybase = ijLoc.y;
                    xloc = xbase;
                    yloc = ybase;
                if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
                    yloc = ybase+20;
                    int x = xloc;
                    int y = yloc;
                    xloc += XINC;
                    yloc += YINC;
                    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                    count++;
                    if (count%6==0) {
                        xloc = xbase;
                        yloc = ybase;
                    int scale = 1;
                    while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
                        if (scale>1) {
                   originalScale = scale;
                   ic.setDrawingSize(width/scale, height/scale);
        /** Returns the current AWT image. */
        public Image getImage() {
            if (img==null && ip!=null)
                img = ip.createImage();
            return img;
        /** Replaces the AWT image, if any, with the one specified. */
        public void setImage(Image img) {
            waitForImage(img);
            this.img = img;
            JPanel panel = ImagePanel.panel;
            width = img.getWidth(panel);
            height = img.getHeight(panel);
            ip = null;
        /** Opens a window to display this image and clears the status bar. */
        public void show() {
            show("");
        /** Opens a window to display this image and displays
         * 'statusMessage' in the status bar. */
        public void show(String statusMessage) {
            if (img==null && ip!=null){
                img = ip.createImage();
            if ((img!=null) && (width>=0) && (height>=0)) {
                win = new ImagePanel(this);
                draw();
        private void waitForImage(Image img) {
        if (comp==null) {
            comp = ImagePanel.panel;
            if (comp==null)
                comp = new JPanel();
        imageLoaded = false;
        if (!comp.prepareImage(img, this)) {
            double progress;
            while (!imageLoaded) {
                if (imageUpdateW>1) {
                    progress = (double)imageUpdateY/imageUpdateW;
                    if (!(progress<1.0)) {
                        progress = 1.0 - (progress-1.0);
                        if (progress<0.0) progress = 0.9;
    public void setFileInfo(FileInfo fi) {
        fi.pixels = null;
        fileInfo = fi;
    }

  • JInternalFrame not opening in JAR file, but works when not in JAR

    I have a folder that contains multiple .class files. I make all the class files into one jar file with this command:
    jar cmf mainClass.txt myapplication.jar *.class
    The mainClass.txt contains the following:
    Main-Class: myapplication
    class-path: myapplication.jar
    The myapplication.class opens up a JDesktopPane inside a JFrame. It also contains a start menu, which again has elements that opens up misc JInternalFrames inside the JDesktopPane. The problem is this:
    When I run the application from a .bat file, everything works fine. However, after making the JAR Executable file, everything works except 1 JInternalFrame. Now, the code for this JInternalFrame is far too much to post, so I'll have to ask as follows;
    Are there any reason why a JInternalFrame would not work from inside a JAR Executable, but work when not in the JAR file? Especially when other JInternalFrames are working? What can make 1 JInternalFrame different from the others in this regard?

    Perhaps the problem lies somewhere else.
    Obviously if other JInternalFrames are working then there is a difference in the one missing internal frame that causes it not to show up.
    My guess is that perhaps you are missing one or two classes in your JAR that are used by that JInternalFrame and that an exception is being thrown causing it not to show.
    Double check the contents of your JAR and make sure that all the classes are present and that they are the right versions.

  • Stock report on the basis of valcation class

    hi expert
    My abaper have create a stock report on the valuation class the report contain opening balance, inward stock, outward stock, clossing stock.i have done with the report the problem which i am getting in some of the valuation class i am getting the wrong all the figure
    Please guide me for to fetch proper field and table.
    regard
    nabil

    Hi jayant
    i dont want MB5W because its analysis reprot. i want to get report on the basis of monthly, in which valuation class- opening balance, inward movement (value), outward movement (value), clossing balance.
    regard
    nabil

  • How to see which methods/classes are important?

    Hi Everyone,
    I am a beginner writing one of my first applications and I have a very newby question. How do I organize and manage many methods (and classes) to see which are the important ones and which are not?
    The questions arised for me because I noticed that I am a bit reluctant to introduce new helper private methods in a class, because I fear there would be too many methods and I couldn’t handle/oversee them... I know it’s probably very wrong and stupid. That’s why I would really like to put it right in me.
    So for example I create a class with a few public methods that are of course the most important part of the class. Those public methods need some more private methods that still do something important and maybe complex thing. But then I stilll need more methods to make clear code in the previous methods. Finally I end up with 20-30 methods in a supposed to be simple class. If I just look into it in Eclipse I have to scroll up and down a lot and even in the package explorer I can’t tell the importants methods apart from the rest. Is this normal?* (Please confirm it is; it would bring relief to me :))
    I thought some kind of method hierarchy shown in the package explorer and expressed in the indentation of the code would help. It would be based on the call hierarchy, but I realize that may be ambiguous. Still, do you know if there is any tool, plugin, solution for this?
    I mean something like this:
    SomeClass:
    ..-veryImportantMethod
    ....-importantMethod
    ....-imprtantMehtod2
    ........-method
    ........-method2
    ........-method3
    ............-reallyNotImportanMethod
    The same thing goes for classes. I start with a few important ones and introduce many less important later. I guess I can’t organize them into different packages based on importance because packages are not for that. It’s just looks strange for me to see a small unimportant helper class opened in the tab next to my main delagator class. (I'm not sure I know correclty what delegator means but that's not important at the moment :))
    I am really just a beginner (needless to say probably :)) but I think it would be easier to intellectually manage the code if there would be some importance hierarchy. It doesn’t even have to be unambiguous as it would only be a way to display the code by the IDE; it wouldn’t affect the program in any way.
    If you have any comments about why this whole thing is not important “because when you write your code..... “ or why I am totally lost and wrong here; I would really appreciate that as well :)
    Thanks in advance,
    lemonboston

    lemonboston wrote:
    Hi Everyone,
    I am a beginner writing one of my first applications and I have a very newby question. How do I organize and manage many methods (and classes) to see which are the important ones and which are not?
    The questions arised for me because I noticed that I am a bit reluctant to introduce new helper private methods in a class, because I fear there would be too many methods and I couldn’t handle/oversee them... I know it’s probably very wrong and stupid. That’s why I would really like to put it right in me.
    So for example I create a class with a few public methods that are of course the most important part of the class. Those public methods need some more private methods that still do something important and maybe complex thing. But then I stilll need more methods to make clear code in the previous methods. Finally I end up with 20-30 methods in a supposed to be simple class. If I just look into it in Eclipse I have to scroll up and down a lot and even in the package explorer I can’t tell the importants methods apart from the rest. Is this normal?* (Please confirm it is; it would bring relief to me :))
    I thought some kind of method hierarchy shown in the package explorer and expressed in the indentation of the code would help. It would be based on the call hierarchy, but I realize that may be ambiguous. Still, do you know if there is any tool, plugin, solution for this?
    I mean something like this:
    SomeClass:
    ..-veryImportantMethod
    ....-importantMethod
    ....-imprtantMehtod2
    ........-method
    ........-method2
    ........-method3
    ............-reallyNotImportanMethod
    The same thing goes for classes. I start with a few important ones and introduce many less important later. I guess I can’t organize them into different packages based on importance because packages are not for that. It’s just looks strange for me to see a small unimportant helper class opened in the tab next to my main delagator class. (I'm not sure I know correclty what delegator means but that's not important at the moment :))
    I am really just a beginner (needless to say probably :)) but I think it would be easier to intellectually manage the code if there would be some importance hierarchy. It doesn’t even have to be unambiguous as it would only be a way to display the code by the IDE; it wouldn’t affect the program in any way.
    If you have any comments about why this whole thing is not important “because when you write your code..... “ or why I am totally lost and wrong here; I would really appreciate that as well :)
    Thanks in advance,
    lemonbostonI think you would benefit from this http://en.wikipedia.org/wiki/Domain-driven_design

  • Can not opening the file

    My program must opens file "abc.txt" which cotains float numbers (one number in aline)
    and stores its contents in an array of float type but it does not.it has some errors i could not fix them
    i am just beginner.& the open file code based on another example i found it here.
    i will appreciate any help.
    here is the program
    import java.util.*;
    import java.io.*;
    class TextFileReader
    private BufferedReader inputFile;
    private String fileName;
    private boolean dataLeft;
    public TextFileReader (String name)
    fileName = name;
    try {inputFile = new BufferedReader (new FileReader(fileName));}
    catch (Exception error)
    System.err.println ("An error occured opening file " +
    fileName + "!\n");
    System.exit(1);
    dataLeft = true;
    public String readLine ()
    String inputLine;
    try
    if ( (inputLine = inputFile.readLine()) == null )
    dataLeft = false;
    return "";
    else return inputLine;
    catch (Exception error)
    System.err.println ("An error occurred reading from file " +
    fileName + "!\n");
    System.exit(1);
    return "";
    public boolean moreData ()
    return dataLeft;
    public class Open {
    ptivate TextFileReader inFile;
    public static void main (String [] args)
    float[] array;
    inFile = new TextFileReader("c:\\me.txt");
    for(int i =0;i<10;i++)
    String next_line= TextFileReader.readLine();
    System.out.println(next_line);
    array=float.parseFloat(next_line);
    /*****the rest of the program does not have problems*****************/
    int [] in1 = { 0,0,0,80,0,0,100,0,0,90,0,0,70,60};
    // Remember Original Positions, giving precedence to earlier occurrence
    ArrayList Values = new ArrayList();
    HashMap OriginalPosition = new HashMap();
    for (int i=in1.length-1; i>=0; i--) {
    OriginalPosition.put(new Integer(in1[i]),new Integer(i+1));
    Values.add(new Integer(in1[i]));
    // Sort incoming array
    Collections.sort(Values);
    PrintStream MyOutput = null;
    try {
    MyOutput = new PrintStream(new FileOutputStream("abc123.txt"));
    catch (IOException e)
    System.out.println("OOps");
    // List out sorted values in reverse order, with position numbers
    if (MyOutput != null) {
    for (int i=Values.size()-1; i>=0; i--) {
    int val = ((Integer)(Values.get(i))).intValue();
    MyOutput.print("" + val + " ");
    MyOutput.println(OriginalPosition.get(new Integer(val)));
    MyOutput.close();
    } else {
    System.out.println("No output file written");

    Hi,
    Since array is an Array , you need to index it while assigning values to it like array[index]
    something like
    for(int i = 0 ; i < 10 ; i++ )
    array= ...
    u need to provide index for array data values.
    try this out.. lets see if it works.

  • Opening a .txt file from an application

    I have an application that extends JFrame. There is a JButton that I want to use to open a file called
    "Instructions.txt."
    and the path to the file is
    "E:\CM0112\Code\Instructions.txt".
    I want to open this file using TextPad, I have tried the code
    Runtime.getRuntime.().exec()but I keep getting compile errors. Any hints would be greatly appreciated.

    try this code
    public class Open
      public static void main(String[] args)
         String line;
         EasyReader inFile = new EasyReader("instructions.txt")
         if(inFile.bad())
            System.out.println(" *** Can't Open instructions.txt *** ");
            System.exit(1);
         while((line = inFile.readLine()) != null)
           //implement your own code, each time loop executes
           //line is the next line in the file until it is null.
      Go to www.rfrank.net/cs-labs/1400-tasmania/EasyReader.java to find EasyReader.java

Maybe you are looking for

  • Apple TV (1st Gen) can't connect to network. error -25.

    I have the Apple airport as my router.  I had to change my network user name and id, as 2  of my devices wouldn't connect.  Now every device will connect except the Apple TV.It says invalid password error -25.  The only thing I changed was the networ

  • ABAP Objects for CRM

    Preparing for a project in CRm ABAP .Please help with list of ABAP objects related to CRM which I need to know

  • URL link is visible instead text in pdf  OBIEE 11.1.1.6.7

    I used formula column with GO URL link in the analysis. ''||"CIS_POLOZKA"."POPIS"||'' I set the column format to @[HTML]. Links work fine. Customer would like to print this analysis in pdf. I get hyperlink instead value of column after print and expo

  • Automatic update of Tax on change of tax driver  in SRM SC and PO

    Hello Experts, I ma facing one issue in Extended Classic secenario. At the time of creating the SC or PO the tax is calculated from the Vertex . So i already did a setting of calculted Tax in the Backend. Now when we create SC or PO the tax is calcul

  • Loading JPGs into Movie Clip

    Can anyone help? I am building a site that requires the user to click on a button to change a large JPG image in a movie clip. The button is part of a small movie clip that contains a text number which is the button in question and a thumbnail of the