Invoke a panel object in a class which extends JFrame

I have a class LoginUI which extends JFrame and another class NewUserUI which extends JPanel. The LoginUI contains a button which when clicked should display the NewUserUI panel in a separate window. How should I invoke the NewUserUI object in the LoginUI class?

One possibility would be the use of a JOptionPane containing the JPanel.
Cheers
DB

Similar Messages

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

  • Retrieve method from class which extends JFrame

    hi, i need some help with my program.
    I have two class which both extends JFrame. The first class called security class and second class is available class.
    In the SECURITY class, i create a button to operate the AVAILABLE class and it generate a result in method Count(). I want to view the result in Frame SECURITY by calling method count() but i could manage to do it. Could somebody help me how to manage this problem?
    Thanks.

    may be you could create a instance of the class you wanted to access method from or pass the instance from one class to another.
    like this:
    public class A extends JFrame
    public B newB= new B();
    public A(){}
    public void someMethod()
    newB.someOtherMethod();
    public class B extends JFrame
    public B(){}
    public void someOtherMethod()
    i hope it is what you are looking for

  • Japplet is not able to call a class that extends JFrame in internet Explore

    Hi
    I am doing an application on Japplet.The Japplet class calls anathor class which extends JFrame.When I am running this appication on Applet Viewer it works fine.but when I am running this aplication in internet Explorer the Frame window doesn't come.What might be the problem.
    Thanks
    Srikants

    There is no error or exceptio comming when i am running that application on Internet Explorer.Convert the html page to use the object tag instead of the applet tag.
    The IE build in jre (called msjvm) cannot display JFrame since the version is
    1.1.2 and it has no javax classes.
    Still problems?
    A Full trace might help us out:
    http://forum.java.sun.com/thread.jspa?threadID=656028

  • Creating array of objects of class which extends Thread

    getting NullPointerException
    can i not create thread array this way?
    class sample extends Thread
    { int i,id;
      public sample(int c)
       { id=c;
      public void run()
      { for(i=0;i<6;i++)
         System.out.println("Thread "+id+" "+i);
    public class thread extends Frame implements ActionListener
    {  Button b1;
       sample s[];
       thread()
       { for(int i=0;i<2;i++)
              s=new sample(i);
         setLayout(new FlowLayout());
         b1=new Button("OK");
         add(b1);
         b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
         {   b1.setEnabled(false);
              for(int i=0;i<2;i++)
              { s[i]=new sample(i);
              s[i].start();
         public static void main(String args[])
         { thread t1=new thread(); 
         t1.setVisible(true);
         t1.setSize(150,150);

    You need:
    sample [] s = new sample[2];However
    1) You should get into the habit that class names start with capital letters, variable and field names with lower case.
    2) It's not a good idea to extend Thread, make a class which implements the Runnable interface and hook a standard Thread object to that.

  • LoadClass    (error loading a class which extends other class  at run-time)

    Hey!
    I'm using the Reflection API
    I load a class called 'SubClass' which exists in a directory called 'subdir' at run-time from my program
    CustomClassLoader loader = new CustomClassLoader();
    Class classRef = loader.loadClass("SubClass");
    class CustomClassLoader extends ClassLoader. I have defined 'findClass(String className)' method in CustomClassLoader.
    This is what 'findClass(String className)' returns:
    defineClass (className,byteArray,0,byteArray.length);
    'byteArray' is of type byte[] and has the contents of subdir/SubClass.
    the problem:
    The program runs fine if SubClass does not extend any class.
    If however, SubClass extends another class, the program throws a NoClassDefFoundError. How is it conceptually different?
    Help appreciated in Advance..
    Thanks!

    Because i'm a newbie to the Reflection thing, i'm notI don't see reflection anywhere. All I see is class loading.
    sure what role does the superclass play when i'm
    trying to load the derived class and how to get away
    with the errorWell... hint: all the superclass's stuff is not copied into the subclass.
    I am quite sure it fails to load the superclass because of classpath issues.

  • Create a new class which extends DataGrid

    Can someone give me a simple example on how to create a new
    class that extends DataGrid. Still having a little trouble
    understanding classes.
    Thanks for any help.
    Jeremy

    import mx.controls.DataGrid
    public class MyGrid extends DataGrid {
    It is pretty much as you would extend a class in Java

  • Getting grid layout to work with a class that extends JFrame

    In my code, I have a class extending JFrame and setting the layout to grid works and the code to add with three parameters compiles just fine but when I run it I get this:
    java.lang.IllegalArgumentException: illegal component position
         at java.awt.Container.addImpl(Container.java:999)
         at java.awt.Container.add(Container.java:928)
         at javax.swing.JFrame.addImpl(JFrame.java:479)
         at java.awt.Container.add(Container.java:928)
    on the add(myLabel, 1, 1); line

    I see on these from
    http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#add(java.awt.Component)
    1.public Component add(Component comp)
    2.public Component add(String name, Component comp)
    3.public Component add(Component comp, int index)
    you should use method add(...) of JPanel instead

  • How to register a regular rmi object in the class which is not setted as startup classes?

    hi:
    it seems the rmi object can only be registed in a startup class,
    is there any way to do this in an nostartup class?
    Thanks for any clue.
    Reno hu
    TCSI

    Yes.
    It is possible to export an RMI object from a servlet's init() method. You
    will have to specify a <load-on-startup> tag in the web.xml deployment
    descriptor, but otherwise, it's pretty straightforward to bind/unbind an RMI
    object when an application is deployed/undeployed.
    -Don
    Andy Piper wrote:
    "Reno hu" <[email protected]> writes:
    No
    hi:
    it seems the rmi object can only be registed in a startup class,
    is there any way to do this in an nostartup class?
    Thanks for any clue.
    Reno hu
    TCSI
    " .sigs are like your face - rarely seen by you and uglier than you think"
    mail: [email protected]

  • Writing a pause method in a class which extends TimerTask

    I run my method using this code:
    synchronized public void run() {
                  MainClass.myMethod();
             }and I want to run my method every 10 seconds so I do like this:
    public void start() {
                  try {
                      timer.scheduleAtFixedRate(getTimeOutControler(), new Date(), 10000);
                   } catch (Exception e) {
                        e.printStackTrace();
              }Now I want to push 2 buttons on a frame so when I click on "start" button the scheduled task begin and when I click on "pause" button the scheduled task pauses. how I can do this?

    I can see two solutions to this.
    1. You could add a volatile boolean paused flag which you could check in your run method (before it calls the MainClass.myMethod(). This won't actually pause the timer, but it will prevent the method from running. The major drawback I see with this is that if you un-pause then the timer could fire instantly, which may or may not be the desired behaviour.
    2. You could cancel the timer, and recreate it when you un-pause. This has the benefit of allowing the full time after you un-pause it (but again, it depends on the behaviour you require).

  • Instantiate an AS2 class which is a MovieClip?

    I have a simple class which extends MovieClip and requires
    one constructor argument, we'll call Box. This class is associated
    to a MovieClip in the library. I can't for the life of me figure
    out how to actually instantiate it at runtime:
    new Box('hello world'); // doesn't work, the MovieClip is
    never attached on stage
    attachMovie('Box',getNextHighestDepth()); // attaches, but
    doesn't pass constructor argument
    How should this be done?

    When you extend MovieClip you either instantiate an instance
    by placing the associated movieclip from the library on the stage
    or by using MovieClip.attachMovie() or
    MovieClip.duplicateMovieClip();
    Using a constructor - as you have noticed - doesn't work in
    this scenario. The class can have a constructor (but it is not
    adviced) but you cannot pass any arguments.
    One way to solve this is by passing arguments in the
    initObject parameter of MovieClip.attachMovie().
    this.attachMovie("myMovieClip","example",10,{txt:"hello
    world"}); //linkage identifier set to 'myMovieClip'
    or with
    this.attachMovie("myMovieClip","example",10);
    example.txt="hello world";

  • Very Basic Question on Threads and Object Manipulation between classes

    I have a feeling this is on the virge of being a stupid question but hey, its the right forum.
    Lets assume I have a class that extends Jframe : Jframe1
    In that frame there is only one Jlabel : Jlabel1
    I want to create a thread that will affect Jlabel1
    The thread will run an endless loop that will.. for example change the color of the label to a random color and then the thread will sleep for a given time. There is no use in this program. Its only meant to help me understand
    I have looked up info and examples on threads. Unfortunately none were useful. Most examples try to illustrate the use of threads with the example of an applet digital clock. But it does not help with my problem, not to mention I dont want to delve into applets at this time.
    I know I have to make a class that extends thread. Does it have to be an inner class?
    How do I get to affect the frame's Jlabel1 from it? It says it doesn't know anything about it.

    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Jframe1 extends JFrame implements Runnable{
      Container con;
      JLabel Jlabel1;
      Random rand;
      Color c;
      public Jframe1(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        con = getContentPane();
        rand = new Random();
        Jlabel1 = new JLabel("bspus", JLabel.CENTER);
        Jlabel1.setOpaque(true);
        con.add(Jlabel1, BorderLayout.NORTH);
        setSize(300, 300);
        setVisible(true);
      public void run(){
        while (true){
          try{
            Thread.sleep(1000);
          catch (InterruptedException e){
            break;
          int n = rand.nextInt(16777216);
          c = new Color(n);
          SwingUtilities.invokeLater(new Runnable(){
            public void run(){
              Jlabel1.setBackground(c);
      public static void main(String[] args){
        Jframe1 jf = new Jframe1();
        new Thread(jf).start(); // you don't need to create a new thread
      }                         // because this Main thread is just
                                // another thread.
                                // here, only for demonstration purpose,
    }                           // we make a new separate thread.

  • Variable textArea not found in class javax.swing.JFrame...

    Making progress on this issue -- but still stuck. Again trying to get the text from a JTextArea on exit:
            frame.addWindowListener
           (new WindowAdapter() {
             public void windowClosing(WindowEvent e)
                System.out.println("Why me???" + frame.textArea.getText());
            });User MARSIAN helped me understand the scope fo the variables and now that has been fixed. Unfortunately I cannot access my variable textArea in the above code. If get this error:
    Error: variable textArea not found in class javax.swing.JFrame
    What am I doing wrong?
    import  java.net.*;
    import  javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import FragImpl.*;
    public class Framework extends WindowAdapter {
        public int numWindows = 0;
        private Point lastLocation = null;
        private int maxX = 500;
        private int maxY = 500;
        JFrame frame;
        public Framework() {
            newFrag();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            maxX = screenSize.width - 50;
            maxY = screenSize.height - 50;
            makeNewWindow();
        public void makeNewWindow() {
            frame = new MyFrame(this);  //*
            numWindows++;
            System.out.println("Number of windows: " + numWindows);
            if (lastLocation != null) {
                //Move the window over and down 40 pixels.
                lastLocation.translate(40, 40);
                if ((lastLocation.x > maxX) || (lastLocation.y > maxY)) {
                    lastLocation.setLocation(0, 0);
                frame.setLocation(lastLocation);
            } else {
                lastLocation = frame.getLocation();
            System.out.println("Frame location: " + lastLocation);
            frame.setVisible(true);
            frame.addWindowListener
           (new WindowAdapter() {
             public void windowClosing(WindowEvent e)
                System.out.println("Why me???" + frame.textArea.getText());
        //This method must be evoked from the event-dispatching thread.
        public void quit(JFrame frame) {
            if (quitConfirmed(frame)) {
                System.exit(0);
            System.out.println("Quit operation not confirmed; staying alive.");
        private boolean quitConfirmed(JFrame frame) {
            String s1 = "Quit";
            String s2 = "Cancel";
            Object[] options = {s1, s2};
            int n = JOptionPane.showOptionDialog(frame,
                    "Windows are still open.\nDo you really want to quit?",
                    "Quit Confirmation",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    s1);
            if (n == JOptionPane.YES_OPTION) {
                return true;
            } else {
                return false;
         private void newFrag()
              Frag frag = new FragImpl();
        public static void main(String[] args) {
            Framework framework = new Framework();
    class MyFrame extends JFrame {
        protected Dimension defaultSize = new Dimension(200, 200);
        protected Framework framework = null;
        private Color color = Color.yellow;
        private Container c;
        JTextArea textArea;
        public MyFrame(Framework controller) {
            super("New Frame");
            framework = controller;
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setSize(defaultSize);
            //Create a text area.
            textArea = new JTextArea(
                    "This is an editable JTextArea " +
                    "that has been initialized with the setText method. " +
                    "A text area is a \"plain\" text component, " +
                    "which means that although it can display text " +
                    "in any font, all of the text is in the same font."
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setBackground ( Color.yellow );
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            //Create the status area.
            JPanel statusPane = new JPanel(new GridLayout(1, 1));
            ImageIcon icoOpen = null;
            URL url = null;
            try
                icoOpen = new ImageIcon("post_it0a.gif"); //("doc04d.gif");
            catch(Exception ex)
                ex.printStackTrace();
                System.exit(1);
            setIconImage(icoOpen.getImage());
            c = getContentPane();
            c.setBackground ( Color.yellow );
            c.add ( areaScrollPane, BorderLayout.CENTER )  ;
            c.add ( statusPane, BorderLayout.SOUTH );
            c.repaint ();
    }

    Yeah!!! It works. Turned out to be a combination of DrKlap's and Martisan's suggestions -- had to change var frame's declaration from JFrame to MyFrame:
        MyFrame frame;Next, created the external class -- but again changed JFrame references to MyFrame:
    public class ShowOnExit extends WindowAdapter {
    //   JFrame aFrame;
       MyFrame aFrame;
       public ShowOnExit(MyFrame f) {
          aFrame = f;
       public void windowClosing(WindowEvent e)
          System.out.println("Why me???" + aFrame.textArea.getText()); // aFrame here not frame !!!
    }This worked. So looks like even though the original code added a WindowListener to 'frame', the listener didn't couldn't access frame's methods unless it was explicitly passed in as a parameter. Let me know if that's wrong.
    Thanks again, all.

  • Why we extends JFrame class in java

    Hello Java Developers,
    I am new to Java & Currently I am trying my hands on Java Swings.
    I wrote a very simple program in Java to display a JFrame on screen. My code is as follows:
    import javax.swing.*;
    public class JavaFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    I saw some examples on internet & they are extending "JFrame" in their every example. I want to know what is the benefit of this ??? here is code:
    import javax.swing.*;
    public class JavaFrame extends JFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    My second question is what is the meaning of line "frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);"
    frame - This object of class created by me.
    setDefaultCloseOperation() - This is predefined method in JFrame class.
    JFrame.EXIT_ON_CLOSE - what is the meaning of this ??

    I saw in JFrame API as you suggested & I found that
    EXIT_ON_CLOSE is an "public static final" method.Look again. It's not a method.
    final: this mehod must be executed
    am I right ???No. final means that the value cannot be reassigned.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • Decorate window of class extending JFrame

    Hello,
    I have a class that extends JFrame and I'd like to set it's look decorated the same way that it does when a new JFrame is built inside the code. Currently it's got the regular Java look (if I create a JFrame somewhere in the code it has the look I want), the following code didn't help, it only sets the subsequently created JFrames decorated:
        GUI frame = new GUI(); //GUI extends JFrame
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        frame.setDefaultLookAndFeelDecorated(true);

    Thanks for your reply. I already read that, in fact the section "Programmatically Setting the Look and Feel " instructs to write the code I posted on the previous post. I also tried:
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    SwingUtilities.updateComponentTreeUI(this);And it didn't work. The main frame has the regular LNF and subsequently created JFrames will have the javax.swing.plaf.metal.MetalLookAndFeel
    Also, after the code I posted on my previous post, GUI.isDefaultLookAndFeelDecorated() returns true.
    Thanx in advance! :)

Maybe you are looking for

  • Dwm 5.9 Compilation issues

    Ok guys, I really need your help. I am currently with dwm 5.8.2 (everything's fine) and I downloaded 5.9 via ABS. I launched a makepkg under ~/dwm. And next, I tried to apply this patch called pertag2. diff: https://github.com/simongmzlj/dwmhacks/ …

  • Passing data to another page loaded in the same window

    How to pass data from a page to another when new page loading takes place ? I use : window.htmlLoader.load( new air.URLRequest("app:/" + htmlfilename)); I tried : window.htmlLoader.addEventListener(air.Event.CHANGE, passmonitor) but it doesn't work !

  • How to change an iPhone

    Hi I am from Argentina, I have an iphone 5s and wanted to change it to a iPhone6. I am traveling to miami, make this change?

  • PO Failure notification not triggering via Outlook

    Hello Experts, We are using SRM 7.O SP05, When PO is created and by mistake user Input the wrong Email address in Header --> Out put. The user is not getting the failure notification Via Out Look. I can able to find the Error message entry in SOST. I

  • How to use online store?  Always tries to use program

    Like a lot of people, I can't access the iTunes store through iTunes. A lot of posts I've read say to use the online store, but whenever I try to do that, it tries to use the iTunes program. I can search for artists and songs online, but as soon as I