JFrame 1 and JFrame 2

Need help please.....
how to send a text from jTextField1 of JFrame 1 to jTextField2 of JFrame 2? i'm using netbeans.... thanks..

use something like this....
public class frame1 extends JFrame{
    private JTextField text1;
    public frame1(){
        text1 = new JTextField();
        JButton button = new JButton("My Button");
        text1.setText("hello world!!!");
        add(text1);
        add(button);
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                new frame2(this).setVisible(true);
    public String getText(){
        return text1.getText();
public class frame2 extends JFrame{
    public frame2(frame1 frame){
        JTextField text1 = new JTextField();
        text1.setText(frame.getText());
        add(text1);
}

Similar Messages

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • JFrames and Java3D simple problem

    Hi ive created a program using jframes in Java and im wanting to move it over to java 3d but im having problems. Ive litterally just looked at java 3d so my knowledge is limited. All i want is to set up my canvas so that i have a Jframe panel on the right and a 3d ball on the left. Here's my failed attempt......
    import com.sun.j3d.utils.geometry.*;
    import com.sun.j3d.utils.universe.*;
    import com.sun.j3d.utils.image.*;//imports image functions
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.awt.*;
    public class Prog extends JFrame
        private Canvas3D canvas;
        private SimpleUniverse universe = new SimpleUniverse();  // Create the universe      
        private BranchGroup group = new BranchGroup(); // Create a structure to contain objects
        private Bounds bounds;
        public Prog()
            super("Program");
            GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
            canvas = new Canvas3D(config);
            //getContentPane().setLayout( new BorderLayout( ) );
            //getContentPane().add(canvas, "Center");
            Container c = getContentPane();
            setSize(600,400);
            c.setLayout(new BorderLayout( ));
            JPanel leftPanel = new JPanel( );
            leftPanel.setBackground(Color.BLACK);
            c.add(leftPanel, BorderLayout.CENTER);
            c.setLayout(new BorderLayout( ));
            JPanel rightPanel = new JPanel( );
            rightPanel.setBackground(Color.GRAY);
            c.add(rightPanel, BorderLayout.EAST);
            JButton goButton = new JButton("  Go  ");
            goButton.setBackground(Color.RED);
            rightPanel.add(goButton);
         Light();//Creates A Light Source
           // Create a ball and add it to the group of objects
           Sphere sphere = new Sphere(0.5f);
           group.addChild(sphere);
           // look towards the ball
           universe.getViewingPlatform().setNominalViewingTransform();
           // add the group of objects to the Universe
           universe.addBranchGraph(group);
        public void Light()
            // Create a white light that shines for 100m from the origin
            Color3f light1Color = new Color3f(1.8f, 1.8f, 1.8f);
           BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
            Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
           DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction);
            light1.setInfluencingBounds(bounds);
           group.addChild(light1);
        public static void main(String[] args)
           Prog frame = new Prog();
         frame.setVisible(true);
    }It Compiles but the 3d ball and the Jframe gui are in different windows but i want them in the same window but i duno how ?

    Hi tesla66 I'm sorry if I didn't correct your code, but drop some new code trying to solve the problem. I've used the cube instead the sphere because it's easier to see is rotating but just change "new ColorCube(0.4f)" with " new Sphere( 0.4f )". I wrote even some coments tought they're helpful. Tell me if I solved the problem
    import java.awt.*;
    import javax.swing.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import com.sun.j3d.utils.universe.SimpleUniverse;
    import com.sun.j3d.utils.geometry.*;
    public class JFrameAndCanvas3D extends JFrame
         private Canvas3D canvas3D;
         public static void main(String[] args)
            new JFrameAndCanvas3D();
         public JFrameAndCanvas3D()
              initialize();
        public BranchGroup createSceneGraph()
            BranchGroup objRoot = new BranchGroup(); //root
            // Creates a bounds for lights and interpolator
            BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
            //Ambient light
            Color3f ambientColour = new Color3f(0.2f, 0.2f, 0.2f);
            AmbientLight ambientLight = new AmbientLight(ambientColour);
            ambientLight.setInfluencingBounds(bounds);
            objRoot.addChild(ambientLight);
            ///Creates a group for transforms
            TransformGroup objMove = new TransformGroup();
            //You must set the capability bit to allow to write transform on the object
            objMove.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
            //Adds a color cube
            objMove.addChild(new ColorCube(0.4));
            //Creates a timer
            Alpha rotationAlpha = new Alpha(-1, //-1 = infinite loop
                                            4000 // rotation time in ms
            //creates a transform 3D based on Y axis roation
            Transform3D t3d = new Transform3D();
            t3d.rotY(Math.PI/2);
            //Creates an rotation interpolator with an alpha and a TransformGroup
            RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objMove);
            rotator.setTransformAxis(t3d);//setta l'asse di rotazione
            //sets a bounding region. withouth this scheduling bounds the interpolator won't work
            rotator.setSchedulingBounds(bounds);
            //add the interpolator to the group
            objMove.addChild(rotator);
            //Adding the group to the root
            objRoot.addChild(objMove);
            objRoot.compile();//improve the performance
            return objRoot;
        public void initialize()
            setSize(800, 600);
            setLayout(new BorderLayout());
            GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();//default config
            canvas3D = new Canvas3D(config);
            canvas3D.setSize(400, 600);
            add(canvas3D, BorderLayout.WEST); //adding the canvas to the west side of the JFrame
            SimpleUniverse simpleU = new SimpleUniverse( canvas3D );
            JPanel controlPanel = new JPanel();
            controlPanel.setLayout(new BorderLayout());
            controlPanel.setSize(400, 600);
            JLabel label = new JLabel();
            label.setText("I'm the control Panel");
            controlPanel.add(label, BorderLayout.CENTER);
            add(controlPanel, BorderLayout.EAST);
            //Positioning the view
            TransformGroup viewingPlatformGroup = simpleU.getViewingPlatform().getViewPlatformTransform();
            Transform3D t3d = new Transform3D();
            t3d.setTranslation(new Vector3f(0, 0, 3)); //moving back from the cube--> +z
            viewingPlatformGroup.setTransform(t3d);
            canvas3D.getView().setBackClipDistance(300.0d); //sets the visible distance
            canvas3D.getView().setFrontClipDistance(0.1d);
            canvas3D.getView().setMinimumFrameCycleTime(20); //minimum time refresh
            canvas3D.getView().setTransparencySortingPolicy(View.TRANSPARENCY_SORT_GEOMETRY); //rendering order
            BranchGroup scene = createSceneGraph();
            simpleU.addBranchGraph(scene);
            setVisible(true);
    }-->Davil

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Inability to draw simple graphics in Java properly (threads and JFrame)

    I am trying to use a thread to continually draw randomly positioned and randomly sized squares in the middle of a JFrame window. I have got 'something' working with the following code, however when run, the actual window doesn't come up properly. If I resize the window it does, and I get the result I wanted, but when the window is first opened it does not fully draw itself on screen. Can anybody help here? I am a bit of a novice when it comes to Java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class TestDraw extends JFrame implements Runnable {
    //DECLARE VARIABLES
         private JLabel lblText;
         private JButton btnBegin;
         private JPanel contentPane;
         private int CoordX, CoordY,SizeX, SizeY, Colour;     // Co'ords for drawing the squares
         Random random = new Random();                              // Random numbers (for square dimensions and colours)
         int n_1 = 450, n_2 = 130, n_3 = 100, n_4 = 4;          // The different ranges of randoms I require
         Thread squares = new Thread(this);                         // Implements a new thread
    //END OF DECLARE VARIABLES
    // CALLS INITIAL PROCEDURE, SETS VISIBLE ETC
         public TestDraw() {
              super();
              initializeComponent();
              this.setVisible(true);
    // INITIALISATION PROCEDURE CALL
         private void initializeComponent() {
              lblText = new JLabel();
              btnBegin = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // lblText
              lblText.setText("This should draw squares on screen...");
              // btnBegin
              btnBegin.setText("Start");
              btnBegin.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        btnBegin_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, lblText, 10,300,364,18);
              addComponent(contentPane, btnBegin, 144,10,101,28);
              // TestDraw
              this.setTitle("TestDraw Program for CM0246");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(390, 350));
    // POSITION COMPONENTS ON SCREEN
         private void addComponent(Container container,Component c,int x,int y,int width,int height)     {
              c.setBounds(x,y,width,height);
              container.add(c);
    // EVENT HANDLING PROCEDURES
         private void btnBegin_actionPerformed(ActionEvent e) {
              System.out.println("\nAction Event from btnBegin called...");
              squares.start(); //STARTS THE SQUARES DRAWING THREAD (Draws random squares on screen)
    // THE MAIN METHOD (STARTS THE PROGRAM)
         public static void main(String[] args) {
              TestDraw bobdole = new TestDraw();
    // THE SQUARE DRAWINGS THREAD (SHOULD DRAW RANDOM SIZED AND COLOURED SQUARES IN RANDOM PLACES)
         public void run() {
              System.out.println("Thread running if this prints");
                   while(true) {
                        int int_1 = random.nextInt(n_1);     // chooses random int for X co'ord
                        int int_2 = random.nextInt(n_2)+70;     // chooses random int for Y co'ord
                        int int_3 = random.nextInt(n_3)+10;     // chooses random int for X dimension
                        int int_4 = random.nextInt(n_3)+10;     // chooses random int for Y dimension
                        CoordX = int_1;
                        CoordY = int_2;
                        SizeX  = int_3;
                        SizeY  = int_4;
                        repaint();
                        try {
                             squares.sleep(500);
                        catch (InterruptedException e) {
                             System.out.println(e);
    // THE PAINT METHOD ATTATCHED TO THE SQUARES THREAD
         public void paint( Graphics g ) {
              System.out.print("Colour" + Colour);
              g.setColor(Color.blue);
              g.fillRect(CoordX, CoordY, SizeX, SizeY);
    // END OF PROGRAM

    I don't see any problem when I run the program but.. In general you shouldn't paint directly on a frame by overloading the paint method. You should rather create a custom component on which you draw.
    But if you do overload paint, make sure you call super.paint before doing anything else.
    More information in this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

  • I can't don't understand code in netbean and it's about Jframe.

    i use netbean to design 2 jframe with some buttons on both frame.
    frame1 is login form, frame2 is mainform. i want to show loginform then click the button1 to show 2nd jframe.
    then i click exit on 2nd jframe and it come back to loginform(frame1).
    i do alot of search on the google and here. i know the basic to show a jframe using
    setVisible or .show() .hide(), etc..
    the problem is what is my jframe variable name in netbean?
    i know i can create an jframe object
    such as: JFrame frame1 = new JFrame(); etc.. (it's ok if the syntax is wrong for now).
    When i use netbean, i drag the Gui components to the Jframe. The jframe is generated by netbean automatically.
    When the main program runs, it calls main() method, follow by :
    public void run() {
    new LoginForm().setVisible(true);
    new LoginForm().setVisible <--- setVisible(true) means show the form.
    and is new LoginForm() create an object from LoginForm class.
    public LoginForm() {
    initComponents();
    When it create a new object, it runs default constructor and calls iniComponoents and finally show the jframe.
    my question is when you create object, you usually declare variable and use variable to hold reference to the object.
    that's why i don't understand how it works here.
    it only create news object, bu no variable to holding it. how do i control this Jframe to show and hide without a reference variable????????????
    Edited by: roadorange on Feb 29, 2008 10:08 PM

    roadorange wrote:
    Encephalopathic . thank your reply so much. your reply is fast. i love it and love this forum.. LOLyou're welcome
    i tried hand-written code, and it looks just fine when design few buttons, labels and textfields.
    The adjustment of buttons(labels) are not that good on the frame.
    However, when you use IDE, you can drag the button on any spot you like in the jframe.... and in the process not learn how Swing works, and lose flexibility and power. Sorry to sound conceited, but I'll match any of your netbeans-created GUI's with one of my own, and mine will likely be better -- and I'm not all that good at this just yet.
    Much luck.

  • Problem with JFrame and JPanel

    Okay, well I'm busy doing a lodge management program for a project and I have programmed this JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FinalTest extends JFrame
         public JPanel contentPane;
         public JImagePanel imgPanel;
         private JLabel[] cottageIcon;
         private boolean keepMoving;
         private int selectedCottage;
         public FinalTest()
              super();
              initializeComponent();
              addActionListeners();
              this.setVisible(true);
         private void initializeComponent()
              contentPane = (JPanel)getContentPane();
              contentPane.setLayout(null);
              imgPanel = new JImagePanel("back.png");
               imgPanel.setLayout(null);
              imgPanel.setBackground(new Color(1, 0, 0));
                   addComponent(contentPane, imgPanel, 10,10,imgPanel.getImageWidth(),imgPanel.getImageHeight());
              cottageIcon = new JLabel[6];
              keepMoving = true;
              selectedCottage = 0;
              cottageIcon[0] =  new JLabel();
              //This component will never be added or shown, but needs to be there to cover for no cottage selected
              for(int a = 1; a < cottageIcon.length; a++)
                   cottageIcon[a] = new JLabel("C" + (a));
                   cottageIcon[a].setBackground(new Color(255, 0, 0));
                    cottageIcon[a].setHorizontalAlignment(SwingConstants.CENTER);
                    cottageIcon[a].setHorizontalTextPosition(SwingConstants.LEADING);
                    cottageIcon[a].setForeground(new Color(255, 255, 255));
                    cottageIcon[a].setOpaque(true);
                    addComponent(imgPanel,cottageIcon[a],12,(a-1)*35 + 12,30,30);
                this.setTitle("Cottage Chooser");
                this.setLocationRelativeTo(null);
              this.setSize(new Dimension(540, 430));
         private void addActionListeners()
              imgPanel.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        imgPanel_mousePressed(e);
                   public void mouseReleased(MouseEvent e)
                        imgPanel_mouseReleased(e);
                   public void mouseEntered(MouseEvent e)
                        imgPanel_mouseEntered(e);
              imgPanel.addMouseMotionListener(new MouseMotionAdapter()
                   public void mouseDragged(MouseEvent e)
                        imgPanel_mouseDragged(e);
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         private void imgPanel_mousePressed(MouseEvent e)
              for(int a = 1; a < cottageIcon.length; a++)
                   if(withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()))
                        System.out.println("B" + withinBounds(e.getX(),e.getY(),cottageIcon[a].getBounds()));
                        selectedCottage = a;
                        keepMoving = true;
         private void imgPanel_mouseReleased(MouseEvent e)
              System.out.println("called");
              selectedCottage = 0;
              keepMoving = false;
         private void imgPanel_mouseDragged(MouseEvent e)
               System.out.println("XXX" + Math.random() * 100);
              if(keepMoving)
                   int x = e.getX();
                    int y = e.getY();
                    if(selectedCottage!= 0)
                         cottageIcon[selectedCottage].setBounds(x-(30/2),y-(30/2),30,30);
                    if(!legalBounds(imgPanel,cottageIcon[selectedCottage]))
                        keepMoving = false;
                        cottageIcon[selectedCottage].setBounds(imgPanel.getWidth()/2,imgPanel.getHeight()/2,30,30);
              System.out.println(cottageIcon[selectedCottage].getBounds());
         private void imgPanel_mouseEntered(MouseEvent e)
               System.out.println("entered");
         private void but1_actionPerformed(ActionEvent e)
              String input = JOptionPane.showInputDialog(null,"Enter selected cottage");
              selectedCottage = Integer.parseInt(input) - 1;
         public boolean legalBounds(Component containerComponent, Component subComponent)
              int contWidth = containerComponent.getWidth();
              int contHeight = containerComponent.getHeight();
              int subComponentX = subComponent.getX();
              int subComponentY = subComponent.getY();
              int subComponentWidth = subComponent.getWidth();
              int subComponentHeight = subComponent.getHeight();
              if((subComponentX < 0) || (subComponentY < 0) || (subComponentX > contWidth) || (subComponentY > contHeight))
                   return false;
              return true;
         public boolean withinBounds(int mouseX, int mouseY, Rectangle componentRectangle)
              int componentX = (int)componentRectangle.getX();
              int componentY = (int)componentRectangle.getY();
              int componentHeight = (int)componentRectangle.getHeight();
              int componentWidth = (int)componentRectangle.getWidth();
              if((mouseX >= componentX) && (mouseX <= (componentX + componentWidth)) && (mouseY >= componentY) && (mouseY <= (componentY + componentWidth)))
                   return true;
              return false;
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              FinalTest ft = new FinalTest();
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class JImagePanel extends JPanel
      private Image image;
      public JImagePanel(String imgFileName)
           image = new ImageIcon(imgFileName).getImage();
        setLayout(null);
      public void paintComponent(Graphics g)
        g.drawImage(image, 0, 0, null);
      public Dimension getImageSize()
                Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
             return size;
      public int getImageWidth()
                int width = image.getWidth(null);
                return width;
      public int getImageHeight()
              int height = image.getHeight(null);
              return height;
    }Now the problem I'm having is changing that class to a JFrame, it seems simple but I keep having problems like when it runs from another JFrame nothing pops up. I can do it like this:
    FinalTest ft = new FinalTest();
    ft.setVisible(false);
    JPanel example = ft.contentPanehowever I will probably be marked down on this for bad code. I'm not asking for the work to be done for me, but I'm really stuck on this and just need some pointers so I can carry on with the project. Thanks,
    Steve

    CeciNEstPasUnProgrammeur wrote:
    I'd actually consider your GUI being a JPanel instead of a JFrame quite good design - makes it easy to put the stuff into an applet when necessary...
    Anyway, you should set setVisible() to true to make it appear, not to false. Otherwise, I don't seem to understand your problem.That is actually my problem. I am trying to convert this JFrame to a JPanel

  • 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.

  • Problem with KeyAdapter and JButtons in a Jframe

    yes hi
    i have searched almost most of the threads here but nothing
    am trying to make my frame accepts keypress and also have some button on the frame here is the code and thank you for the all the help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPg extends JFrame implements ActionListener
                private int width;
                private int hight;
                public    JPanel north;
                public    JPanel se;
                public    JButton start;
                public    JButton quit;
                public    Screen s;//a Jpanel
                public    KeyStrokeHandler x;
        public RPg() {
               init();
               setTitle("RPG");
               setSize(width,hight);
               setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               setResizable(false);
               setVisible(true);
               x=new KeyStrokeHandler();
             addKeyListener(x);
             public void init() {
               north=new JPanel();
               Container cp = getContentPane();
               s=new Screen();
               this.width=s.width;
               this.hight=s.hight+60;
              start=new JButton("START");
                  start.addActionListener(this);
              quit=new JButton("QUIT");
                  quit.addActionListener(this);
              north.setBackground(Color.DARK_GRAY);
              north.setLayout(new FlowLayout());
              north.add(start);
              north.add(quit);
              cp.add(north, BorderLayout.NORTH);
              cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPg rpg = new RPg();
       public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
       class KeyStrokeHandler extends KeyAdapter {
               public void keyTyped(KeyEvent ke) {}
               public void keyPressed(KeyEvent ke){
                  int keyCode = ke.getKeyCode();
                  if ((keyCode == KeyEvent.VK_M)){
                     System.out.println("it works");
               public void keyReleased(KeyEvent ke){}

    Use the 'tab' key to navigate through 'contentPane > start > quit' focus cycle. 'M' key works when focus is on contentPane (which it is on first showing). See tutorial pages on 'Using Key Bindings' and 'Focus Subsystem' for more.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPG extends JFrame implements ActionListener {
        private int width;
        private int hight;
        public JPanel north;
        public JPanel se;
        public JButton start;
        public JButton quit;
        public Screen s;    //a Jpanel
        public RPG() {
            init();
            setTitle("RPG");
            setSize(width,hight);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
            setVisible(true);
        public void init() {
            north=new JPanel();
            Container cp = getContentPane();
            registerKeys((JComponent)cp);
            s=new Screen();
            this.width=s.width;
            this.hight=s.hight+60;
            start=new JButton("START");
                start.addActionListener(this);
            quit=new JButton("QUIT");
                quit.addActionListener(this);
            north.setBackground(Color.DARK_GRAY);
            north.setLayout(new FlowLayout());
            north.add(start);
            north.add(quit);
            cp.add(north, BorderLayout.NORTH);
            cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPG rpg = new RPG();
        public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
        private void registerKeys(JComponent jc)
            jc.getInputMap().put(KeyStroke.getKeyStroke("M"), "M");
            jc.getActionMap().put("M", mAction);
        Action mAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("it works");
    class Screen extends JPanel {
        int width, hight;
        public Screen() {
            width = 300;
            hight = 300;
            setBackground(Color.pink);
    }

  • Problem with insets and placement within a JFrame.

    I have written some code that actively renders (at about 100 fps) to a JPanel contained within a JFrame. The size of the frame and the size of the panel are both set to 1000 by 700 (odd i know..)
    Everything seems to work fine and I have encountered insets before so when I am rendering I have been adjusting accordingly. However I have started to try and draw my own menu bar at the bottom of the panel and this is where I am having problems. Whatever I draw seems to be too low and disappears off the bottom. To solve this I tried getting the insets from the JFrame:
    Insets insets = getInsets();
    xAdjustmentLeft = insets.left;
    xAdjustmentRight = insets.right;
    yAdjustmentTop = insets.top;
    yAdjustmentBottom = insets.bottom;When I do this on my vista machine I get insets of 3, 3, 23, 3 accordingly. When I print out the coordinates of mouse clicks I find that at the top left corner i get 3, 23 as you would expect. When I click in the bottom right corner of my screen I get 996 (ish), 716.
    The 996 can be explained by the left inset and my bad clicking however the 716 bears no relation to the top inset of 23 or the bottom inset of 3 in any way .... I am doing something wrong or have I missed something such as by adding the JPanel to the JFrame I have added or subtracted a distance somehow?
    I ran the program on my xp machine and got similar insets of 3,3,29,3. However when I click in the bottom right of the page I get exactly the same coordinates as on the vista machine .. this just doesn't seem to make sense?
    I should probably also mention how the rendering works just incase ... I'm drawing to a VolatileImage which I then draw onto the JPanel using its own graphical context. Interestingly anything I render on the image at y coord of 0 appears correctly at the top of the screen .... which it shouldn't because of the inset ... I'm so confused.
    I hope someone can help / understand my babblings. If you need more code I can post it.. just there's rather alot of it.

    Sorry, my bad I realised I was doing some rather stupid calculations elsewhere in the program. I have now managed to get my drawn bar where I need it to be on both machines.
    However, if I am rendering a picture of 1000 by 700 and the actual screen you are seeing is something along the lines of 993 by 674 (values minus the insets) this means I am wasting time rendering a picture larger than I am actually displaying, how to be normally interpret the sizes, do they go to the very outside of the panel or the visual element inside it? I could easily just increase the JFrame itself to be larger say 1006 by 726 and have the image the exact size within that.
    Whichever way I have solved my original problem so no worries.

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Problem with jframe has jtextfield and jpanel

    hi all
    i ve a jframe with some components on it
    of these components a jpanel that i repaint each time i want
    and a textfield for chatting between players
    the problem is as follows
    some times when i click the textfield after repaining the panel
    it can not be activated and the caret does not appear
    when i click any other component out or in the frame
    and return i get it active and in a good state
    i use single buffer for repapint
    thanks for reading
    i'm waiting for response

    Your best bet here is to show us your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    [http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
    Again, if the code is compilable and runnable more people will be able to help you.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]

  • Problem with JFrame, JInternalFrame and JDialog

    problem solved..sorry

    I have just found this post:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302473
    And the first way seems to be the only way to solve the problem... :(
    Now the question is, does it exist a way to refresh a JFrame after that I have uset setVisible(true)?
    If it does exist I could have something like this:
    setVisible(true)
    new panel(getInsets(););
    contpan.add(panel);
    REFRESH();

  • Problem with JFrame, JPanel and getInsets()...

    hi, this is my problem:
    I have a JFrame and I want add a JPanel to its ContentPan, I need to know the JFrame's getInsets values to set (with setBounds()) the right dimensions of the JPanel, but if I call getInsets() before of setVisible(true) I obtain all 0 values, if I call setVisible(true) before of add() I obtain the right values, but the JPanel is not showed.
    By now I have solved with this sequence:
    new panel();
    contpan.add(panel);
    getInsets();
    panel.setBounds();but I would pass the bounds values to my panel constructor, something like this:
    new panel(getInsets(););
    contpan.add(panel);Could someone help me?

    I have just found this post:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302473
    And the first way seems to be the only way to solve the problem... :(
    Now the question is, does it exist a way to refresh a JFrame after that I have uset setVisible(true)?
    If it does exist I could have something like this:
    setVisible(true)
    new panel(getInsets(););
    contpan.add(panel);
    REFRESH();

  • Swing layout/size problem with JFrame and JApplet.

    I have a class that extends a JFrame, the classes layout is BorderLayout. I then have a class that extend JApplet, this classes layout is GridBagLayout (this class has a JTabbedPane - which contains JPanels). The problem I'm having is no matter how big I make the size of the applet or frame (using setSize), the applet/frame stays the same size - no matter how large I make it.
    Can anyone please help?
    Thanks,
    dosteov

    Here is the basic code:
    Thanks in advance,
    dosteov
    public class EADAdm extends JApplet
    EADAdmFrame theFrame = new EADAdmFrame(this);
         public void init()
              // Take out this line if you don't use symantec.itools.net.RelativeURL or symantec.itools.awt.util.StatusScroller
    //          symantec.itools.lang.Context.setApplet(this);
              // This line prevents the "Swing: checked access to system event queue" message seen in some browsers.
              getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
              // This code is automatically generated by Visual Cafe when you add
              // components to the visual environment. It instantiates and initializes
              // the components. To modify the code, only use code syntax that matches
              // what Visual Cafe can generate, or Visual Cafe may be unable to back
              // parse your Java file into its visual environment.
              //{{INIT_CONTROLS
              getContentPane().setLayout(new GridBagLayout());
              setEnabled(false);
              getContentPane().setBackground(java.awt.Color.lightGray);
              setSize(800,800);
              getContentPane().add(AdmTab, new com.symantec.itools.awt.GridBagConstraintsD(0,1,2,1,0.5,0.5,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.HORIZONTAL,new Insets(3,12,4,14),120,120));
              AdmTab.setFont(new Font("Dialog", Font.PLAIN, 12));
              titleLbl.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
              titleLbl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
              titleLbl.setText("EAD Administration");
              getContentPane().add(titleLbl, new com.symantec.itools.awt.GridBagConstraintsD(0,0,1,1,0.0,0.0,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.NONE,new Insets(12,36,0,0),307,15));
              titleLbl.setForeground(java.awt.Color.blue);
              titleLbl.setFont(new Font("Dialog", Font.BOLD, 15));
              exitBtn.setText("Exit EAD Administration");
              exitBtn.setActionCommand("Exit EAD Administration");
              getContentPane().add(exitBtn, new com.symantec.itools.awt.GridBagConstraintsD(0,2,2,1,0.0,0.0,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.NONE,new Insets(6,371,10,14),66,8));
              exitBtn.setFont(new Font("Dialog", Font.PLAIN, 12));
         //theFrame.setVisible(false);
         login();
         AdmTab.addTab("Administration", new LogoPanel() );
         userPanel = createUserPanel();
         AdmTab.addTab("Edit Users", userPanel );
         fpoPanel = createFPOPanel();
         AdmTab.addTab("Edit FPO", fpoPanel );
         regulationPanel = createRegulationPanel();
         AdmTab.addTab("Edit Regulations", regulationPanel );
         rolloverPanel = createRolloverPanel();
         AdmTab.addTab("Rollover", rolloverPanel );           
              //{{REGISTER_LISTENERS
         SymMouse aSymMouse = new SymMouse();
              this.addMouseListener(aSymMouse);
              SymAction lSymAction = new SymAction();
              exitBtn.addActionListener(lSymAction);
              SymKey aSymKey = new SymKey();
              this.addKeyListener(aSymKey);
         theFrame.getContentPane().add(this);
    public class EADAdmFrame extends JFrame
    EADAdm theApplet;
    public EADAdmFrame(EADAdm theMainApplet)
              //{{INIT_CONTROLS
         //     theApplet = theMainApplet;
         //     this.getContentPane().add(theApplet);
              getContentPane().setLayout(new BorderLayout(0,0));
              getContentPane().setBackground(java.awt.Color.lightGray);
              setSize(1000,1000);
              setVisible(false);
         theApplet = theMainApplet;
              //{{REGISTER_LISTENERS
              SymWindow aSymWindow = new SymWindow();
              this.addWindowListener(aSymWindow);
              SymComponent aSymComponent = new SymComponent();
              this.addComponentListener(aSymComponent);

  • 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.

Maybe you are looking for