Problem with JFrame class.

To risolve my problem i need for few diferent frame
( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
Help me.....

Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.

Similar Messages

  • Problem with JFrame's dispose();

    Hello everyone,
    I'm having a problem with JFrame's dispose() method. In my program I have 2 classes which go into full screen. On each screen there is a button to switch to the other screen. The first time I push the button on both of them the other screen closes, which is what I want. However, if I push the same button more than twice - like by going from Screen1 to Screen2 and Screen2 to Screen1 and then Screen1 to Screen2 - I get 2 screens. If I keep doing that I eventually get 10+ screens up, which is bad. How do I prevent that?

    There's a lot of code, so I'll just post up the part that does it.
    backButton.addActionListener(new ActionListener()
                  public void actionPerformed(ActionEvent e)
                      soundManagerM.close();
                        new MenuScreen().setVisible(true);
                        dispose();
             });I don't think it opens up 2 at once, because it would play multiple music right?

  • Getting problem with DOMImplementation classes method getFeature() method

    hi
    getting problem with DOMImplementation classes method getFeature() method
    Error is cannot find symbol getFeature()
    code snippet is like...
    private void saveXml(Document document, String path) throws IOException {
    DOMImplementation implementation = document.getImplementation();
    DOMImplementationLS implementationLS = (DOMImplementationLS) (implementation.getFeature("LS", "3.0"));
    LSSerializer serializer = implementationLS.createLSSerializer();
    LSOutput output = implementationLS.createLSOutput();
    FileOutputStream stream = new FileOutputStream(path);
    output.setByteStream(stream);
    serializer.write(document, output);
    stream.close();
    problem with getFeature() method

    You are probably using an implementation of DOM which does not implement DOM level-3.

  • Problems with inner classes in JasminXT

    I hava problems with inner classes in JasminXT.
    I wrote:
    ;This is outer class
    .source Outer.j
    .class Outer
    .super SomeSuperClass
    .method public createrInnerClass()V
         .limit stack 10
         .limit locals 10
         ;create a Inner object
         new Outer$Inner
         dup
         invokenonvirtual Outer$Inner/<init>(LOuter;)V
         ;test function must print a Outer class name
         invokevirtual Outer$Inner/testFunction ()V
    .end method
    ;This is inner class
    .source Outer$Inner.j
    .class Outer$Inner
    .super java/lang/Object
    .field final this$0 LOuter;
    ;contructor
    .method pubilc <init>(LOuter;)V
         .limit stack 10
         .limit locals 10
         aload_0
         invokenonvirtual Object/<init>()V
         aload_0
         aload_1
         putfield Inner$Outer/this$0 LOuter;
         return
    .end method
    ;test
    .method public testFunction ()V
         .limit stack 10
         .limit locals 10
         ;get out object
         getstatic java/io/PrintStream/out  java/io/PrintStream;
         aload_0
         invokevirtual java/lang/Object/getClass()java/lang/Class;
         ;now in stack Outer$Inner class
         invokevirtual java/Class/getDeclaringClass()java/lang/Class;
         ;but now in stack null
         invokevirtual java/io/PrintStream/print (Ljava/lang/Object;)V
    .end methodI used dejasmin. Code was equal.
    What I have to do? Why getDeclatingClass () returns null, but in dejasmin code
    it returns Outer class?

    Outer$Inner naming convention is not used by JVM to get declaring class.
    You need to have proper InnerClasses attribute (refer to http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#79996)
    in the generated classes. Did you check using jclasslib or another class file viewer and verified that your .class files have proper InnerClasses attribute?

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

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

  • Problem with JFrame code

    Can anyone say the problem with the attached code. When I run the program, only, maximize, minimize and close options are viewable and nothing else.
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;
    * Created on Mar 24, 2008
    * @author Anand
    public class JBackGroundImageDemo extends JFrame
        Container con = null;
        JPanel panelBgImg;
        public JBackGroundImageDemo()
            setTitle("JBackGroundImageDemo");
            con = getContentPane();
            con.setLayout(null);
            ImageIcon imh = new ImageIcon("aditi.jpg");
            setSize(imh.getIconWidth(), imh.getIconHeight());
            panelBgImg = new JPanel()
                public void paintComponent(Graphics g)
                    Image img = new ImageIcon("aditi.jpg").getImage();
                    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                    setPreferredSize(size);
                    setMinimumSize(size);
                    setMaximumSize(size);
                    setSize(size);
                    setLayout(null);
                    g.drawImage(img, 0, 0, null);
            con.add(panelBgImg);
            panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());
            GridBagLayout layout = new GridBagLayout();
            JPanel panelContent = new JPanel(layout);
            GridBagConstraints gc = new GridBagConstraints();
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 1;
            JLabel label = new JLabel("UserName: ", JLabel.LEFT);                       
            panelContent.add(label, gc);
            gc.gridx = 2;
            gc.gridy = 1;
            JTextField txtName = new JTextField(10);
            panelContent.add(txtName, gc);
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 2;
            gc.gridwidth = 2;
            JButton btn = new JButton("Login");
            panelContent.add(btn, gc);
            panelContent.setBackground(Color.GRAY);
            panelContent.setBorder(new LineBorder(Color.WHITE));
            panelBgImg.add(panelContent);
            panelBgImg.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 200));
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args)
            new JBackGroundImageDemo().setVisible(true);
         Please help.
    Regards,
    Anees

    Here's you a little code example, it works, so take a look at it.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Junk{
      public Junk(){
      public void makeFrame(){
        JFrame j = new JFrame("Junk");
        Toolkit t = Toolkit.getDefaultToolkit();
        MediaTracker mt = new MediaTracker(j);
        Image img = t.getImage("junk.jpg");
        mt.addImage(img, 0);
        try{
          mt.waitForID(0);
        }catch(InterruptedException e){
          System.out.println("Hey, we were too impatient!");
        myPanel p = new myPanel(img);
        p.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
        j.add(p);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args){
        new Junk().makeFrame();
      class myPanel extends JPanel{
        Image img;
        myPanel(Image img){
          this.img = img;
        public void paintComponent(Graphics g){
          g.drawImage(img, 0, 0, this);
    }BTW: your image should be in your project folder.

  • Problem with JFrame, it goes blank

    i
    My problem is with JFrame, when it's carrying operation which takes a bit of time, if somethhing goes on
    top of the frame the frame goes blank, all the components vanished and when the operation is completed the components bacome visible. I dont know why this is happening,. The code is below, since my code is very complicated I am sending some code whcih shows the problem I have, when you press the button it execute's a for loop, whcih takes some time. If you minimize the frame and maximize again, you'll see what I mean.
    Please help!!!
    Many Thanks
    Lilylay
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
    JPanel contentPane;
    JButton jButton2 = new JButton();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(null);
    this.setSize(new Dimension(407, 289));
    this.setTitle("Frame Title");
    contentPane.setBackground(SystemColor.text);
    contentPane.setForeground(Color.lightGray);
    jButton2.setText("Press me!");
    jButton2.setBounds(new Rectangle(107, 111, 143, 48));
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    jButton2_mousePressed(e);
    contentPane.add(jButton2, null);
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton2_mousePressed(MouseEvent e) {
    for(int i=0; i<256898; i++){
    for(int j=0; j<5656585; j++){
    System.out.println("hello");
    public static void main(String [] args){
    Frame1 frame=new Frame1();
    frame.show();
    }

    The reason this is happening is because your loop is so intensive that your program doesn't have time to refresh its JFrame. There is no great way to get past this stumbling block without decreasing the efficiency of your code. One possible solution is to call repaint() from within your loop, but of course this slows down your loop.
    Hope that helps

  • Is there a problem with JFrame and window listeners?

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

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

  • Problem with JFrame resizing at runtime

    Hi All,
    I have a problem with resizing the JFrame at runtime. Even if i resize the JPanel. It is not affection on all the components over the frame. How can i solve that I am using AbsoluteLayout(jre1.6) and here i am going to provide you code snippet. My requirement is to resizt the form. If form is small in size then all the component should also be according tothe size of the form.
    public void initComponents(int size) {
    if(size >= 50) {
    x_co_or = 300;
    y_co_or = 300;
    } else if(size < 50) {
    x_co_or = 200;
    y_co_or = 200;
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jButton1.setText("jButton1");
    jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 110, 40));
    getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, x_co_or, y_co_or));
    pack();
    Can anybody suggest any idea/solution.
    Any idea/solution are most welcome.
    Regards,
    Pradeep Dubey

    How can i solve that I am using AbsoluteLayout(jre1.6)
    and here i am going to provide you code snippet.no need for the snippet, you're using absolute positioning, which means you're responsible for location and size on every single change.
    start coding now, take about a week, or you could use a layout manager, take maybe, 5 minutes

  • Problems with importing classes in Java

    Hello,
    i have some problems with a simple project.
    The structure is like this:
    web-inf/classes/databeans/loginexistinguserform.java
    web-inf/classes/formactions/loginexistinguseraction.java
    loginexistinguserform.java :
    package databeans;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionMapping;
    import javax.servlet.http.HttpServletRequest;
    public class LoginExistingUserForm extends ActionForm
         String userid;
         String password;
         public String getUserid(){return userid;}
         public void setUserid(String newUserid){userid=newUserid;}
         public String getPassword(){return password;}
         public void setPassword(String newPassword) {password=newPassword;}
         public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
              ActionErrors errors=new ActionErrors();
              if(this.userid==null||this.userid.equals(""))
                   errors.add("user",new ActionError("error.userid.required"));
              if(this.password==null||this.password.equals(""))
                   errors.add("pass",new ActionError("error.password.required"));
              return errors;
    }loginexistinguseraction.java
    package formactions;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import databeans.LoginExistingUserForm;
    public class LoginExistingUserAction extends Action
         public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
         throws IOException, ServletException
              LoginExistingUserForm loginData=(LoginExistingUserForm)form;
              if(loginData.getUserid().equals("Admin")&&loginData.getPassword().equals("Parola"))
                   return mapping.findForward("successLogin");
              else
                   return mapping.findForward("failureLogin");
    }I can complie succesfully loginexisitinguserform.java but problems appears when i want to compile the second file, loginexistinguseraction.java with command: javac loginexistinguseraction.java
    C:\ApacheGroup\Tomcat\webapps\PersonalWeb\WEB-INF\classes\formactions>javac loginexistinguseraction.java
    loginexistinguseraction.java:10: package databeans does not exist
    import databeans.LoginExistingUserForm;
    ^
    loginexistinguseraction.java:17: cannot find symbol
    symbol : class LoginExistingUserForm
    location: class formactions.LoginExistingUserAction
    LoginExistingUserForm loginData=(LoginExistingUserForm)form;
    ^
    loginexistinguseraction.java:17: cannot find symbol
    symbol : class LoginExistingUserForm
    location: class formactions.LoginExistingUserAction
    LoginExistingUserForm loginData=(LoginExistingUserForm)form;
    ^
    3 errors
    I have the CLASSPATH variable setup tu C:/Sun/Appserver/lib/j2ee.jar
    Can someone help me ? Thank you in advance !

    Thank you very much ! It worked. I'm really new in Jav a programming.
    Now i have encoutered another problem. When i want to login, and enter user name and password i am redirected to a login.do page, instead of Welcome.jsp
    Here is Login.jsp:
    <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@page contentType="text/html; charset=ISO-8859-1"%>
    <html>
    <head><title>Login Form</title></head>
    <body>
    <html:errors/>
    <html:form action="/login">
    <table border="0" width="200">
    <tr>
         <td>User Name:</td>
         <td><html:text property="userid" maxlength="13"/></td>
    </tr>
    <tr>
         <td>Password:</td>
         <td><html:password property="password" maxlength="13"/></td>
    </tr>
    </table>
    <br />
    <html:submit value="Login"/>
    </html:form>
    </body>
    </html>and here is struts-config.xml :
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE struts-config PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
              "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
    <struts-config>
    <!--========================beans for HTML form data=======================-->
    <form-beans>
         <form-bean name="loginBean" type="databeans.LoginExistingUserForm"/>
    </form-beans>
    <!--========================Action Mappings================================-->
    <action-mappings>
         <action path="/login" type="formactions.LoginExistingUserAction" name="loginBean" input="/Login.jsp" scope="session">
              <forward name="succesLogin" path="/pages/Welcome.jsp" redirect="true"/>
              <forward name="failureLogin" path="/pages/Diverse.jsp" redirect="true"/>
         </action>
    </action-mappings>
        <message-resources parameter="MessageResources" />
    </struts-config>

  • Problems with loading Classes from a Directory of a jar file.

    Hi Guys,
    i have a problem with my programm. It works greatly in my eclipse platform. but there are all classes in my default folder. I want to add a plugin function now. My Abstract classes are in in my default folder and my doughter classes are in my plugin-folder called plugin.
    I look what is in the pluginfolder -> all my doughter classes. but i every time get a Class Cast Exception and an ClassNotFoundException.
    How can i do that ? Current i do it with Class.forName(frames.substring(0,frames[i].indexOf(".class")));
    best regards flo

    http://java.sun.com/j2se/1.3/docs/tooldocs/win32/classpath.html

  • Inheritance problem with parent class calling child class

    I have a problem with inheritance with a parent class calling a child class method. Below is the example pseudocode code and my problem:
    public abstract class A {
        protected void function1 ( ) { }
        protected void function2 () {
             //calls function1();
             function1();
    public abstract class B extends A {
        protected void function1 ()  {
             // do stuff
    public class C extends B {
        protected void function1 ()  {
            // do stuff
            super.function1 ();
    }I have an object instance of class C created and its function2() is invoked.
    My problem is, while in function2(), which belongs to abstract class A and the method call to function 1() is called, the call invokes the function1() of class B. Shouldn't the call invoke function 1() of class C instead? And then function1() of class B will be called after due to the super.function1(). It's not behaving like I thought it would.
    Edited by: crono77 on Jan 10, 2008 8:13 PM

    Nevermind, i found my error :)

  • Problem with loading classes!!!

    I am loading classes using
    // Open File
    InputStream jarFile = new BufferedInputStream(new FileInputStream(
    pluginPath));
    // Get Manifest and properties
    Attributes attrs = new JarInputStream(jarFile).getManifest().
    getMainAttributes();
    jarFile.close();
    // Read Main Class
    String mainClass = attrs.getValue("Protocol-Class");
    // Load all classes from jar file without giving classpath
    URL url = new URL("jar:file:" + pluginPath + "!/");
    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
    URL[] urls = new URL[] {
    url};
    ClassLoader classLoader = new URLClassLoader(urls);
    // Create new instance of protocol
    Protocol protocol = (Protocol) classLoader.loadClass(mainClass).
    newInstance();
    I am loading classes one by one say a order A, B, C. In my case class c extends class A. So I am loading class A first and later B and finally C. But I am getting exceptions when loading class C that Class A is unknown.The following exception is thrown
    java.lang.NoClassDefFoundError: com/a/A at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
    Please give me a solution to make it run.

    You create a new class loader for each class. The class loaders are independent, and so the class hierarchies they load are independent. Class A loader by classLoaderOne doesn't see class B loader by classLoaderTwo - they are loaded into their own sandboxes.
    Either load everything with one class loader or create the class loaders in a hierarchy. To create a hierarchy use the class loader constructor that takes a parent class loader as a parameter. One class loader may be easier because then you don't need to worry about loading order.

  • 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

Maybe you are looking for

  • Populating the field description on the screen

    Hi Group, In the program after executing on the screen I have 3 screen fields. After entering the two fields when user hit the enter it needs to retrieve third field value from the table and have to display on the screen,and again I will click execut

  • Find the technical name of a report in Crystal 2008(XI R/3)

    Hi, I know the report technical name(system genetared) is availble at properties tab in CMC in crystal XI R/2, but I am unable to find the same in XI R/3. Also let me know how to create a open document or generate URL for XI R/3 reports. Thank you, R

  • How do I switch Itunes Libraries without losing my music?

    The majority of my music is on my old, slow computer and this is where I initially synced my Iphone 5s, but my primary computer (laptop) has some music and I would like to download music from this computer in the future. I can't get the music from my

  • Problem adding elements to a group after removing everything...

    Hi everyone, I would really appreciate some help on something. I have a Group that has some Buttons in it. This Group is in one of fours States, and there is a componant for each State. After the user goes through the rest of the program and comes ba

  • Populate videos in a circle

    Hey I have a bit of a question, I've done som images in Illustrator (see picture below), which im now trying to do with moving images in after effects. I've go a bit of green screen footage, keyed out the background, and chopped of anything unwanted.