Launching a JFrame from another JFrame

Hi,
I have a JFrame containing a menu(buttons). When I click on a button, I want that it launches another JFrame.
I tried making use of the code
Process p = Runtime.getRuntime().exec("java CreateStudentRecord");
where CreateStudentRecord is the JFrame I want to launch. however this did not work.
Can anyone help me find out how I can launch another JFrame when I click on a button within another JFrame.
Thanks,
Rahul.

How about just using the following:
private CreateStudentRecord csr;
JButton b1 = new JButton("New Student Record");
b1.addActionListener( new ActionListener() {
     public void actionPerformed(ActionEvent e){
          csr = new CreateStudentRecord().show();
Rick

Similar Messages

  • How sholud we call one jframe class from another jframe class

    Hi
    In my application i am calling one jframe class from another jframe clas.
    how sholud we make previous jframe inactve when another jframe is invoked?(user sholud not able to make any changes on on parent jframe window when another jframe is invoked)
    Pls reply.

    Sorry for me it is not possible to change existing code,
    pls suggest me any other solution so that i can inactive parent jframe when child jframe execution is going on.

  • How to embed and launch ipa file from another ipa package created using Air for iOS

    Hi Guys,
    Anybody out there knowing how to embed and launch ipa file from another ipa package created using Air for iOS ?
    I am having 1 ipa file created using Xcode, Now i need to include that file in my ipa Package which is created using Flash CS 5.5 and Air for iOS. Also i need to know how to open my 1st ipa file from AS3 ?
    Thanks,

    Hi Sir,
    Thanks for your reply.
    But in that case user need to download 2 applications right. I need user to download my parent application created using Flash and that package contain one more ipa created using Xcode, so from my parent app only user should able to open my 2nd app. Is there any way to do that?
    Ps:  I am not talking about in-app but 2 individual apps inside one package.

  • Launch a midlet from another midlet

    I need to launch a midlet from another midlet that is running, is it posible and would it be?
    regards in advance

    [rpalomino],
    You are out of luck here. The current CLDC/MIDP specification permits one only MIDlet jar file to be run at a given point in time. You can package as many class files as you wish but only one MIDlet can be launched by the kVM.
    If your purpose is to write MIDlet applications that access the same data resource, then instead of launching multiple MIDlets (which is not possible), you can use the RMS data store for persistent information across the different MIDlet class file application.
    Allen Lai
    Developer Technical Support
    SUN Microsystems
    http://www.sun.com/developers/support/

  • Please help - JFrame, menu, another JFrame, setBackground

    I am trying to make a simple program that draws a JFrame with a menu. The menu has one item, which when selected draws another JFrame. That JFrame has a button, which when pressed changes the background color. Many hours have gone into this, despite the fact that I made a similar program a few weeks ago.
    The compiler complains about the method getContentPane, when I remove that, it runs and draws the first window, but the menu item does not make the second window. Also, the setDefaultCloseOperation confuses the compiler as well.
    Please help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MenuAction2
    public static void main(String[] args) 
         MainWindow window = new MainWindow("Menu action example");
      //window.setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
         window.setVisible(true);      
    class MainWindow extends JFrame
         MainWindow(String title)
         super(title);
         getContentPane.setLayout(new BorderLayout());
         Toolkit theKit = getToolkit();          
         Dimension wndSize = theKit.getScreenSize();  
         setBounds(0, 0,wndSize.width, wndSize.height);
         setJMenuBar(menuBar);
         fileMenu = new JMenu("File");
         connectItem = new JMenuItem();
         connectItem = fileMenu.add("Connect...");
         connectItem.addActionListener(menuHandler = new Handler());
         menuBar.add(fileMenu);
         getContentPane.add(toolBar, BorderLayout.NORTH);  
    class Handler implements ActionListener
         public void actionPerformed(ActionEvent e)
          win = new ConnectWindow("Connect to Database");
          getContentPane().add(win, BorderLayout.NORTH);
          setVisible(true);
      private JMenu fileMenu;
      private JMenuItem connectItem;
      private JMenuBar menuBar = new JMenuBar(); 
      private JToolBar toolBar = new JToolBar();
      private Handler menuHandler;
      private ConnectWindow win;
    class ConnectWindow extends JFrame
         ConnectWindow(String title)
              super(title);
              setSize(200,200);
              setLayout(new BorderLayout());
              JButton connectB = new JButton("Connect");
              connectB.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        setBackground(Color.red);
              add(connectB,BorderLayout.SOUTH);
              setVisible(true);
    }

    getContentPane is a method so you should use it that way:
    getContentPane().setLayout(new BorderLayout());
    getContentPane.add(new Button("Ok"));

  • Open a jFrame on another jFrames close

    New to java
    I have 2 jFrames, frame1.java & frame2.java
    frame1 has a button which makes frame1 invisible and opens frame2.
    I can do the above.
    but when I close frame2 I want to re-open frame1.
    I do not want to use a button on frame2, I want to use the X at the top right of the jFrame.
    I'm using NetBeans 6.1
    Please help
    Thanks

    Recommended: don't use 2 JFrames, use one JFrame and make the second a modal JDialog.
    But if you must do it this way, take a look at WindowListener#windowClosing.
    In future (not this time), Swing related questions should be posted in the [Swing forum|http://forums.sun.com/forum.jspa?forumID=57]
    db

  • JFrame calling another JFrame

    Hello,
    I have a simple question:
    2 java files with 2 JFrames in them
    JFrame1(Cars.java) calls JFrame2(AddCar.java) from actionlistener.
    What I think is wrong is JFrame1 actionListener:
    if(ae.getSource() == CarEdit_btn){
    AddCar objEditAddCar = new AddCar();
    objEditAddCar.EditCar();
    And JFrame2's EditCar() method:
    public void EditCar(){
    AddCar windowAddCar1 = new AddCar();
    windowAddCar1.setTitle("Add Car");
    windowAddCar1.pack();
    windowAddCar1.show();
    AddCarMilage_txt.setText("544");
    The problem is that AddCarMilage_txt.setText("544"); doesnt update the value of the JTextField of JFrame2.
    Any ideas? Thanks
    Or another way to go around for me is, how do I use args[] from main inside the constructor?

    read this:
    http://forum.java.sun.com/thread.jspa?threadID=5199666&messageID=9792440#9792440
    it has also 2 classes and updates the textfield of the other class just copy and paste the code.

  • Launching a MIDlet from another

    Hi All!
    I need to create a menu.When one selects a particular option they should be redirected to another midlet .Need basics of creating forms .
    Desperately need for a project whose deadline is on our head .
    How do i go abt this ?
    Thanks .

    jhd
    i, this is not big problem and u can meet ur deadline easily if i m not late to answer u.
    if u want to create a main menu when u are launching and first screan appear with your midlet name then there is way to create different Midlet
    and then if u are using wireless toolkit you have to goto
    Settings>Midlet where u find options for that and u can set ur midlet classpath there.
    you can see the game demo given in wtk23's apps folder.
    and if u are suppose to wanting that ur application start with main menu and after selecting one u r agin going to nested menu and from there u want to call other midlet then u can use this code
    class midlet1 extends Midlet
    which u want to call from
    class midlet2 extends Midlet
    //here u have to destroy midlet2
    //create object of midlet1
    midlet1 m = midlet1();
    this will simplycall to midlet1 and new object were created for that
    with new display........
    but for standard coding u have to use any displayable item(Form,List..)
    and when u are selecting menu u just setCurrent display to this new displayble item and will work fine.
    Regards,
    jasmit vala

  • A JFrame calling another JFrame running a Thread

    Hi,
    here is my problem: I have an instance of Frame1 (extending JFrame) containing a button. When this button is clicked, a new instance of Frame2 (extending JFrame too) is created. The constructor of this Frame2 then calls the run method of an implementation of Runnable (called MyThread). For the purpose of this example I put a simple incrementation of a counter in the run method of the thread.
    The goal is to stop the incrementation by clicking anytime on the stop button of Frame2, hence ending the thread.
    When I create a new instance of Frame2, it works fine and I am able to end the thread, but when I create an instance of Frame1, the application freezes and I don't get any control on Frame2.
    The code for those classes is:
    public class Frame1 extends JFrame implements ActionListener{
         public static void main(String[] args) {
              new Frame1();
         public Frame1(){
              getContentPane().setLayout(new GridLayout(1,1));
              JButton b = new JButton("Run");
              b.addActionListener(this);
              getContentPane().add(b);
              setVisible(true);
              setSize(400,400);          
         public void actionPerformed(ActionEvent e) {
              Frame2 f= new Frame2();
    public class Frame2 extends JFrame implements ActionListener{
         MyThread t;
         boolean running = true;
         public Frame2(){
              getContentPane().setLayout(new GridLayout(1,1));
              JButton b = new JButton("Stop");
              b.addActionListener(this);
              getContentPane().add(b);
              setVisible(true);
              setSize(200,200);          
              t = new MyThread();
              t.run();
         public void actionPerformed(ActionEvent e) {
              t.setRunning(false);
    public class MyThread implements Runnable{
         boolean running = true;
         public void run(){
              int count = 0;
              while(isRunning())
                   count++;
              System.out.println("Last count: "+count);
         public boolean isRunning() {
              return running;
         public void setRunning(boolean running) {
              this.running = running;
    One thing I have tried is to make Frame2 implementing Runnable, but it didn't work. Any idea how to get the control on Frame2?
    Thanks

    You are calling t.run() and you really should be using t.start(). The code inside run() in MyThread is not running in a separate thread, so the call that you make to t.run() never returns.

  • How to go one jFrame to another JFrame after click on button?

    I am having two frames loginFrame.java and UserinfoFrame.java.
    In loginFrame.java to click on login button i want to goto UserinfoFrame
    (LogInSuccessPanel).
    private void bnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    int loginCounter=0;
    this.remove(jPanel2);
    LogInSuccessPanel login = new LogInSuccessPanel();
    this.add(login);
    update();
    //if(evt.getSource()=="login")
    // while(loginCounter <= 5)
    if(!login(jTextField1.getText(), new String(jPasswordField1.getPassword()))) {
    loginCounter++;
    System.out.println("UserName : "+jTextField1.getText()) ;
    System.out.println("Password : "+jPasswordField1.getPassword());
    if(loginCounter >= 6) {
    System.out.println("Unable to Login");
    connectToDB();
    if(jTextField1.equals("UserName"))
    //Check Whether username is existing in DB
    private void connectToDB() {
    try{
         Class.forName("com.mysql.jdbc.Driver");
    Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    Statement stmt = con.createStatement();
    ResultSet rset = stmt.executeQuery("SELECT UserName from login table");
    jTextField1.setText("Connected to the Database. Fetching Values from login Tables.\n");
    StringBuffer allRowValues = new StringBuffer();
    int counter=1;
    if (rset.next())
    //allRowValues.append("ROW " + counter + ": Username = " + rset.getString(1) + " & Password = " + rset.getString(2) + "\n");
    //counter++;
    System.out.println(" LOGIN SUCCESSFUL ");
    System.out.println("Username : " + rset.getString("username"));
    System.out.println("Password " + rset.getString("password"));
    System.out.println(" LOGIN SUCCESSFUL ");
    else
    System.out.println(" LOGIN FAILED ");
    // .setText(allRowValues.toString());
    rset.close();
    stmt.close();
    con.close();
    } catch (SQLException ex) {
    System.out.println("Connection Error = " + ex.toString());
    ex.printStackTrace();
    }catch(ClassNotFoundException e){
         System.out.println("Error in loading class" + e);
    private boolean login(String name, String pwd) {
    int count=0;
    if(count<=5)
    count++;
    return true;
    else return false;
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Login().setVisible(true);
    Thanks and regards

    search results for
    login
    http://onesearch.sun.com/search/onesearch/index.jsp?charset=UTF-8&qt=login&rf=0&rt=1&site=dev&nh=10&cs=0&col=developer-forums&dftab=siteforumid%3Ajava57&chooseCat=javaall&subCat=siteforumid%3Ajava57

  • Disposing JFrame from JPanel

    Right, I suspect this has an easy solution, or maybe I have already happened on it, but I thought I'd best ask just in case.
    I have an application that creates a JFrame from another JFrame, with a JPanel internal to it. What I want to happen is for the JPanel to do its business in its paintComponent method, and then dispose of its parent JFrame (that's dispose - no System.exit(0)'s here please :) ).
    The only way I can see to do it is to pass a reference to the JFrame when the JPanel is created. But this seems to be a bit messy encapsulation-wise.
    Any comers?

    you could make the parent JFrame have a thread that checked the status of the child JFrame's JPanel every second or so and then close itself when the JPanel is finished doing whatever it is doing.

  • How to call a view from another

    Hello Experts,
            I have embedded a view (let us call this view 'A') in standard homepage. This works fine. Now on click of a button on this embedded view I want to launch another view that is also created by me, in the same component in which I had created view A. But I do not know how to launch this second view
         Could you please tell me how to call/launch a view from another on click of a button?
    Regards,
    Prafful

    Hello Prafful,
    I guess by launching you mean substituting one view by another. It can be achieved by declaring a navigational link in the runtime repository from one view to another. You have to create an event handler on the button and outbound plug in your view using the wizard. Then, on the event handler you call an outbound plug where you trigger a navigation using this navigational link and the view A will be replaced by view B.
    A code which needs to be done in outbound plug:
    me->view_manager->navigate(
    source_rep_view = me->rep_view
    outbound_plug   = 'NAVLINKNAME'
    data_collection = iv_data_collection ).
    Best Regards,
    Yevgen

  • How do I convert this Applet to launch from a JFrame instead??

       A simple program where the user can sketch curves and shapes in a
       variety of colors on a variety of background colors.  The user selects
       a drawing color form a pop-up menu at the top of the
       applet.  If the user clicks "Set Background", the background
       color is set to the current drawing color and the drawing
       area is filled with that color.  If the user clicks "Clear",
       the drawing area is just filled with the current background color.
       The user selects the shape to draw from another pop-up menu at the
       top of the applet.  The user can draw free-hand curves, straight
       lines, and one of six different types of shapes.
       The user's drawing is saved in an off-screen image, which is
       used to refresh the screen when repainting.  The picture is
       lost if the applet changes size, however.
       This file defines two classes, SimplePaint3,class, and
       class, SimplePaint3$Display.class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SimplePaint3 extends JApplet {
            // The main applet class simply sets up the applet.  Most of the
            // work is done in the Display class.
       JComboBox colorChoice, figureChoice;  // Pop-up menus, defined as instance
                                             // variables so that the Display
                                             // class can see them.
       public void init() {
          setBackground(Color.gray);
          getContentPane().setBackground(Color.gray);
          Display canvas = new Display();  // The drawing area.
          getContentPane().add(canvas,BorderLayout.CENTER);
          JPanel buttonBar = new JPanel();       // A panel to hold the buttons.
          buttonBar.setBackground(Color.gray);
          getContentPane().add(buttonBar, BorderLayout.SOUTH);
          JPanel choiceBar = new JPanel();       // A panel to hole the pop-up menus
          choiceBar.setBackground(Color.gray);
          getContentPane().add(choiceBar, BorderLayout.NORTH);
          JButton fill = new JButton("Set Background");  // The first button.
          fill.addActionListener(canvas);
          buttonBar.add(fill);
          JButton clear = new JButton("Clear");   // The second button.
          clear.addActionListener(canvas);
          buttonBar.add(clear);
          colorChoice = new JComboBox();  // The pop-up menu of colors.
          colorChoice.addItem("Black");
          colorChoice.addItem("Red");
          colorChoice.addItem("Green");
          colorChoice.addItem("Blue");
          colorChoice.addItem("Cyan");
          colorChoice.addItem("Magenta");
          colorChoice.addItem("Yellow");
          colorChoice.addItem("White");
          colorChoice.setBackground(Color.white);
          choiceBar.add(colorChoice);
          figureChoice = new JComboBox();  // The pop-up menu of shapes.
          figureChoice.addItem("Curve");
          figureChoice.addItem("Straight Line");
          figureChoice.addItem("Rectangle");
          figureChoice.addItem("Oval");
          figureChoice.addItem("RoundRect");
          figureChoice.addItem("Filled Rectangle");
          figureChoice.addItem("Filled Oval");
          figureChoice.addItem("Filled RoundRect");
          figureChoice.setBackground(Color.white);
          choiceBar.add(figureChoice);
       }  // end init()
       public Insets getInsets() {
              // Specify how wide a border to leave around the edges of the applet.
          return new Insets(3,3,3,3);
       private class Display extends JPanel
                  implements MouseListener, MouseMotionListener, ActionListener {
               // Nested class Display represents the drawing surface of the
               // applet.  It lets the user use the mouse to draw colored curves
               // and shapes.  The current color is specified by the pop-up menu
               // colorChoice.  The current shape is specified by another pop-up menu,
               // figureChoice.  (These are instance variables in the main class.)
               // The panel also listens for action events from buttons
               // named "Clear" and "Set Background".  The "Clear" button fills
               // the panel with the current background color.  The "Set Background"
               // button sets the background color to the current drawing color and
               // then clears.  These buttons are set up in the main class.
          private final static int
                      BLACK = 0,
                      RED = 1,            // Some constants to make
                      GREEN = 2,          // the code more readable.
                      BLUE = 3,           // These numbers code for
                      CYAN = 4,           // the different drawing colors.
                      MAGENTA = 5,
                      YELLOW = 6,
                      WHITE = 7;
          private final static int
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,               // Some constants that code
                     OVAL = 3,               // for the different types of
                     ROUNDRECT = 4,          // figure the program can draw.
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          /* Some variables used for backing up the contents of the panel. */
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOfOSI, heightOfOSI;  // Current width and height of OSI.  These
                                        // are checked against the size of the applet,
                                        // to detect any change in the panel's size.
                                        // If the size has changed, a new OSI is created.
                                        // The picture in the off-screen image is lost
                                        // when that happens.
          /* The following variables are used when the user is sketching a
             curve while dragging a mouse. */
          private int mouseX, mouseY;   // The location of the mouse.
          private int prevX, prevY;     // The previous location of the mouse.
          private int startX, startY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int figure;    // What type of figure is being drawn.  This is
                                 //    specified by the figureChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the figure that is
                                    // being drawn.
          Display() {
                 // Constructor.  When this component is first created, it is set to
                 // listen for mouse events and mouse motion events from
                 // itself.  The initial background color is white.
             addMouseListener(this);
             addMouseMotionListener(this);
             setBackground(Color.white);
          private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) {
                // This method is called to do ALL drawing in this applet!
                // Draws a shape in the graphics context g.
                // The shape paramter tells what kind of shape to draw.  This
                // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
                // FILLED_OVAL, or FILLED_ROUNDRECT.  (Note that a CURVE is
                // drawn by drawing multiple LINES, so the shape parameter is
                // never equal to CURVE.)  For a LINE, a line is drawn from
                // the point (x1,y1) to (x2,y2).  For other shapes,  the
                // points (x1,y1) and (x2,y2) give two corners of the shape
                // (or of a rectangle that contains the shape).
             if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
          private void repaintRect(int x1, int y1, int x2, int y2) {
                // Call repaint on a rectangle that contains the points (x1,y1)
                // and (x2,y2).  (Add a 1-pixel border along right and bottom
                // edges to allow for the pen overhang when drawing a line.)
             int x, y;  // top left corner of rectangle that contains the figure
             int w, h;  // width and height of rectangle that contains the figure
             if (x2 >= x1) {  // x1 is left edge
                x = x1;
                w = x2 - x1;
             else {          // x2 is left edge
                x = x2;
                w = x1 - x2;
             if (y2 >= y1) {  // y1 is top edge
                y = y1;
                h = y2 - y1;
             else {          // y2 is top edge.
                y = y2;
                h = y1 - y2;
             repaint(x,y,w+1,h+1);
          private void checkOSI() {
               // This method is responsible for creating the off-screen image.
               // It should be called before using the OSI.  It will make a new OSI if
               // the size of the panel changes.
             if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOfOSI = getSize().width;
                heightOfOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
                OSG.dispose();
          public void paintComponent(Graphics g) {
               // Copy the off-screen image to the screen,
               // after checking to make sure it exists.  Then,
               // if a shape other than CURVE is being drawn,
               // draw it on top of the image from the OSI.
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && figure != CURVE) {
                g.setColor(dragColor);
                drawFigure(g,figure,startX,startY,mouseX,mouseY);
          public void actionPerformed(ActionEvent evt) {
                  // Respond when the user clicks on a button.  The
                  // command must be either "Clear" or "Set Background".
             String command = evt.getActionCommand();
             checkOSI();
             if (command.equals("Set Background")) {
                    // Set background color before clearing.
                    // Change the selected color so it is different
                    // from the background color.
                setBackground(getCurrentColor());
                if (colorChoice.getSelectedIndex() == BLACK)
                   colorChoice.setSelectedIndex(WHITE);
                else
                   colorChoice.setSelectedIndex(BLACK);
             Graphics g = OSI.getGraphics();
             g.setColor(getBackground());
             g.fillRect(0,0,getSize().width,getSize().height);
             g.dispose();
             repaint();
          private Color getCurrentColor() {
                   // Check the colorChoice menu to find the currently
                   // selected color, and return the appropriate color
                   // object.
             int currentColor = colorChoice.getSelectedIndex();
             switch (currentColor) {
                case BLACK:
                   return Color.black;
                case RED:
                   return Color.red;
                case GREEN:
                   return Color.green;
                case BLUE:
                   return Color.blue;
                case CYAN:
                   return Color.cyan;
                case MAGENTA:
                   return Color.magenta;
                case YELLOW:
                   return Color.yellow;
                default:
                   return Color.white;
          public void mousePressed(MouseEvent evt) {
                  // This is called when the user presses the mouse on the
                  // panel.  This begins a draw operation in which the user
                  // sketches a curve or draws a shape.  (Note that curves
                  // are handled differently from other shapes.  For CURVE,
                  // a new segment of the curve is drawn each time the user
                  // moves the mouse.  For the other shapes, a "rubber band
                  // cursor" is used.  That is, the figure is drawn between
                  // the starting point and the current mouse location.)
             if (dragging == true)  // Ignore mouse presses that occur
                 return;            //    when user is already drawing a curve.
                                    //    (This can happen if the user presses
                                    //    two mouse buttons at the same time.)
             prevX = startX = evt.getX();  // Save mouse coordinates.
             prevY = startY = evt.getY();
             figure = figureChoice.getSelectedIndex();
             dragColor = getCurrentColor();        
             dragGraphics = OSI.getGraphics();
             dragGraphics.setColor(dragColor);
             dragging = true;  // Start drawing.
          } // end mousePressed()
          public void mouseReleased(MouseEvent evt) {
                  // Called whenever the user releases the mouse button.
                  // If the user was drawing a shape, we make the shape
                  // permanent by drawing it to the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              dragging = false;
              mouseX = evt.getX();
              mouseY = evt.getY();
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs
                  drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                  repaintRect(prevX,prevY,mouseX,mouseY);
              else if (figure == LINE) {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX || mouseY != startY) {
                       // Draw the line only if it has non-zero length.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              else {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX && mouseY != startY) {
                       // Draw the shape only if both its height
                       // and width are both non-zero.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              dragGraphics.dispose();
              dragGraphics = null;
          public void mouseDragged(MouseEvent evt) {
                   // Called whenever the user moves the mouse while a mouse button
                   // is down.  If the user is drawing a curve, draw a segment of
                   // the curve on the off-screen image, and repaint the part
                   // of the panel that contains the new line segment.  Otherwise,
                   // just call repaint and let paintComponent() draw the shape on
                   // top of the picture in the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              mouseX = evt.getX();   // x-coordinate of mouse.
              mouseY = evt.getY();   // y=coordinate of mouse.
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs.
                 drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                 repaintRect(prevX,prevY,mouseX,mouseY);
              else {
                    // Repaint two rectangles:  The one that contains the previous
                    // version of the figure, and the one that will contain the
                    // new version.  The first repaint is necessary to restore
                    // the picture from the off-screen image in that rectangle.
                 repaintRect(startX,startY,prevX,prevY);
                 repaintRect(startX,startY,mouseX,mouseY);
              prevX = mouseX;  // Save coords for the next call to mouseDragged or mouseReleased.
              prevY = mouseY;
          } // end mouseDragged.
          public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
          public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
          public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
          public void mouseMoved(MouseEvent evt) { }     //    interfaces).
       } // end nested class Display
    } // end class SimplePaint3

    Im quite the novice, how exactly do I go about doing that. What I did was to put both in diff files but I got errors saying that they cant find colorChoice, figureChoice in the Display class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Simple extends JFrame implements Display{
            // The main applet class simply sets up the applet.  Most of the
            // work is done in the Display class.
       JComboBox colorChoice, figureChoice;  // Pop-up menus, defined as instance
                                             // variables so that the Display
                                             // class can see them.
       public void init() {
          setBackground(Color.gray);
          getContentPane().setBackground(Color.gray);
          Display canvas = new Display();  // The drawing area.
          getContentPane().add(canvas,BorderLayout.CENTER);
          JPanel buttonBar = new JPanel();       // A panel to hold the buttons.
          buttonBar.setBackground(Color.gray);
          getContentPane().add(buttonBar, BorderLayout.SOUTH);
          JPanel choiceBar = new JPanel();       // A panel to hole the pop-up menus
          choiceBar.setBackground(Color.gray);
          getContentPane().add(choiceBar, BorderLayout.NORTH);
          JButton fill = new JButton("Set Background");  // The first button.
          fill.addActionListener(canvas);
          buttonBar.add(fill);
          JButton clear = new JButton("Clear");   // The second button.
          clear.addActionListener(canvas);
          buttonBar.add(clear);
          colorChoice = new JComboBox();  // The pop-up menu of colors.
          colorChoice.addItem("Black");
          colorChoice.addItem("Red");
          colorChoice.addItem("Green");
          colorChoice.addItem("Blue");
          colorChoice.addItem("Cyan");
          colorChoice.addItem("Magenta");
          colorChoice.addItem("Yellow");
          colorChoice.addItem("White");
          colorChoice.setBackground(Color.white);
          choiceBar.add(colorChoice);
          figureChoice = new JComboBox();  // The pop-up menu of shapes.
          figureChoice.addItem("Curve");
          figureChoice.addItem("Straight Line");
          figureChoice.addItem("Rectangle");
          figureChoice.addItem("Oval");
          figureChoice.addItem("RoundRect");
          figureChoice.addItem("Filled Rectangle");
          figureChoice.addItem("Filled Oval");
          figureChoice.addItem("Filled RoundRect");
          figureChoice.setBackground(Color.white);
          choiceBar.add(figureChoice);
       }  // end init()
    } // end class SimplePaint3
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Display extends JPanel
                  implements MouseListener, MouseMotionListener, ActionListener {
               // Nested class Display represents the drawing surface of the
               // applet.  It lets the user use the mouse to draw colored curves
               // and shapes.  The current color is specified by the pop-up menu
               // colorChoice.  The current shape is specified by another pop-up menu,
               // figureChoice.  (These are instance variables in the main class.)
               // The panel also listens for action events from buttons
               // named "Clear" and "Set Background".  The "Clear" button fills
               // the panel with the current background color.  The "Set Background"
               // button sets the background color to the current drawing color and
               // then clears.  These buttons are set up in the main class.
          private final static int
                      BLACK = 0,
                      RED = 1,            // Some constants to make
                      GREEN = 2,          // the code more readable.
                      BLUE = 3,           // These numbers code for
                      CYAN = 4,           // the different drawing colors.
                      MAGENTA = 5,
                      YELLOW = 6,
                      WHITE = 7;
          private final static int
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,               // Some constants that code
                     OVAL = 3,               // for the different types of
                     ROUNDRECT = 4,          // figure the program can draw.
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          /* Some variables used for backing up the contents of the panel. */
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOfOSI, heightOfOSI;  // Current width and height of OSI.  These
                                        // are checked against the size of the applet,
                                        // to detect any change in the panel's size.
                                        // If the size has changed, a new OSI is created.
                                        // The picture in the off-screen image is lost
                                        // when that happens.
          /* The following variables are used when the user is sketching a
             curve while dragging a mouse. */
          private int mouseX, mouseY;   // The location of the mouse.
          private int prevX, prevY;     // The previous location of the mouse.
          private int startX, startY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int figure;    // What type of figure is being drawn.  This is
                                 //    specified by the figureChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the figure that is
                                    // being drawn.
          Display() {
                 // Constructor.  When this component is first created, it is set to
                 // listen for mouse events and mouse motion events from
                 // itself.  The initial background color is white.
             addMouseListener(this);
             addMouseMotionListener(this);
             setBackground(Color.white);
          private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) {
                // This method is called to do ALL drawing in this applet!
                // Draws a shape in the graphics context g.
                // The shape paramter tells what kind of shape to draw.  This
                // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
                // FILLED_OVAL, or FILLED_ROUNDRECT.  (Note that a CURVE is
                // drawn by drawing multiple LINES, so the shape parameter is
                // never equal to CURVE.)  For a LINE, a line is drawn from
                // the point (x1,y1) to (x2,y2).  For other shapes,  the
                // points (x1,y1) and (x2,y2) give two corners of the shape
                // (or of a rectangle that contains the shape).
             if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
          private void repaintRect(int x1, int y1, int x2, int y2) {
                // Call repaint on a rectangle that contains the points (x1,y1)
                // and (x2,y2).  (Add a 1-pixel border along right and bottom
                // edges to allow for the pen overhang when drawing a line.)
             int x, y;  // top left corner of rectangle that contains the figure
             int w, h;  // width and height of rectangle that contains the figure
             if (x2 >= x1) {  // x1 is left edge
                x = x1;
                w = x2 - x1;
             else {          // x2 is left edge
                x = x2;
                w = x1 - x2;
             if (y2 >= y1) {  // y1 is top edge
                y = y1;
                h = y2 - y1;
             else {          // y2 is top edge.
                y = y2;
                h = y1 - y2;
             repaint(x,y,w+1,h+1);
          private void checkOSI() {
               // This method is responsible for creating the off-screen image.
               // It should be called before using the OSI.  It will make a new OSI if
               // the size of the panel changes.
             if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOfOSI = getSize().width;
                heightOfOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
                OSG.dispose();
          public void paintComponent(Graphics g) {
               // Copy the off-screen image to the screen,
               // after checking to make sure it exists.  Then,
               // if a shape other than CURVE is being drawn,
               // draw it on top of the image from the OSI.
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && figure != CURVE) {
                g.setColor(dragColor);
                drawFigure(g,figure,startX,startY,mouseX,mouseY);
          public void actionPerformed(ActionEvent evt) {
                  // Respond when the user clicks on a button.  The
                  // command must be either "Clear" or "Set Background".
             String command = evt.getActionCommand();
             checkOSI();
             if (command.equals("Set Background")) {
                    // Set background color before clearing.
                    // Change the selected color so it is different
                    // from the background color.
                setBackground(getCurrentColor());
                if (colorChoice.getSelectedIndex() == BLACK)
                   colorChoice.setSelectedIndex(WHITE);
                else
                   colorChoice.setSelectedIndex(BLACK);
             Graphics g = OSI.getGraphics();
             g.setColor(getBackground());
             g.fillRect(0,0,getSize().width,getSize().height);
             g.dispose();
             repaint();
          private Color getCurrentColor() {
                   // Check the colorChoice menu to find the currently
                   // selected color, and return the appropriate color
                   // object.
             int currentColor = colorChoice.getSelectedIndex();
             switch (currentColor) {
                case BLACK:
                   return Color.black;
                case RED:
                   return Color.red;
                case GREEN:
                   return Color.green;
                case BLUE:
                   return Color.blue;
                case CYAN:
                   return Color.cyan;
                case MAGENTA:
                   return Color.magenta;
                case YELLOW:
                   return Color.yellow;
                default:
                   return Color.white;
          public void mousePressed(MouseEvent evt) {
                  // This is called when the user presses the mouse on the
                  // panel.  This begins a draw operation in which the user
                  // sketches a curve or draws a shape.  (Note that curves
                  // are handled differently from other shapes.  For CURVE,
                  // a new segment of the curve is drawn each time the user
                  // moves the mouse.  For the other shapes, a "rubber band
                  // cursor" is used.  That is, the figure is drawn between
                  // the starting point and the current mouse location.)
             if (dragging == true)  // Ignore mouse presses that occur
                 return;            //    when user is already drawing a curve.
                                    //    (This can happen if the user presses
                                    //    two mouse buttons at the same time.)
             prevX = startX = evt.getX();  // Save mouse coordinates.
             prevY = startY = evt.getY();
             figure = figureChoice.getSelectedIndex();
             dragColor = getCurrentColor();        
             dragGraphics = OSI.getGraphics();
             dragGraphics.setColor(dragColor);
             dragging = true;  // Start drawing.
          } // end mousePressed()
          public void mouseReleased(MouseEvent evt) {
                  // Called whenever the user releases the mouse button.
                  // If the user was drawing a shape, we make the shape
                  // permanent by drawing it to the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              dragging = false;
              mouseX = evt.getX();
              mouseY = evt.getY();
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs
                  drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                  repaintRect(prevX,prevY,mouseX,mouseY);
              else if (figure == LINE) {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX || mouseY != startY) {
                       // Draw the line only if it has non-zero length.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              else {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX && mouseY != startY) {
                       // Draw the shape only if both its height
                       // and width are both non-zero.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              dragGraphics.dispose();
              dragGraphics = null;
          public void mouseDragged(MouseEvent evt) {
                   // Called whenever the user moves the mouse while a mouse button
                   // is down.  If the user is drawing a curve, draw a segment of
                   // the curve on the off-screen image, and repaint the part
                   // of the panel that contains the new line segment.  Otherwise,
                   // just call repaint and let paintComponent() draw the shape on
                   // top of the picture in the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              mouseX = evt.getX();   // x-coordinate of mouse.
              mouseY = evt.getY();   // y=coordinate of mouse.
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs.
                 drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                 repaintRect(prevX,prevY,mouseX,mouseY);
              else {
                    // Repaint two rectangles:  The one that contains the previous
                    // version of the figure, and the one that will contain the
                    // new version.  The first repaint is necessary to restore
                    // the picture from the off-screen image in that rectangle.
                 repaintRect(startX,startY,prevX,prevY);
                 repaintRect(startX,startY,mouseX,mouseY);
              prevX = mouseX;  // Save coords for the next call to mouseDragged or mouseReleased.
              prevY = mouseY;
          } // end mouseDragged.
          public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
          public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
          public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
          public void mouseMoved(MouseEvent evt) { }     //    interfaces).
       } // end nested class Display

  • Launching html file from JFrame

    I wish to launch an html file called "Help.html" when a user clicks on the help button on my toolbar in the GUI. I know how to open a simple program using the Runtime.exec( ) command but the problem is how would i open a specified file in a specified program...any help will be appreciated.
    PS: I do not know any C unfortunately, haven't done that yet at uni but would be glad to learn now :)

    I think you missed the question, opening a simple JFrame with a JTextArea won't have the same effect of opening a HTML file in which user can click on stuff and all that, even if I do open another JFrame imagine all the programming i have to do to get the URL's working for all the links in the help file and little search commands etc...I hope someone can tell me how to open the clients web-browser with the help.html file supplied by me!

  • Another JFrame from a Button Click

    Hi...
    I was just wondering how I could write a code where I could bring up another JFrame (let say JFrame2) from a button click on a main JFrame (let say JFrame1)......
    Could anyone show me an example......
    Thanks
    Ashley Q

    Thanks.........
    Btw, I am trying to output 2 different JFrame, by clicking 2 JButtons. On JFrame frame, there's 2 button, the Synthesizer Button which bring up the Synthesizer JFrame and the Recognizer Button which bring up the Recognizer JFrame. However, there's a some problems probably with my coding......Could someone help me...
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class VoicePronunciationSystem extends JFrame implements ActionListener
         public Component createComponents()
              JButton RecognizerButton = new JButton ("Recognizer");
              RecognizerButton.setMnemonic('r');
              RecognizerButton.addActionListener(this);
              JButton SynthesizerButton = new JButton ("Synthesizer");
              SynthesizerButton.setMnemonic('s');
              SynthesizerButton.addActionListener(this);
              JLabel label = new JLabel ("This is a Voice Pronunciation System");
              JPanel panel = new JPanel();
              panel.setBorder(BorderFactory.createEmptyBorder(120,120,120,120));
              panel.setLayout(new GridLayout(1, 1));
              panel.add(label);
              panel.setLayout(new GridLayout(2, 2));
              panel.add(RecognizerButton);
              panel.setLayout(new GridLayout(2, 3));
              panel.add(SynthesizerButton);
              return panel;
         public void actionPerformed(ActionEvent event)
              Object source = event.getSource();
              if( source == RecognizerButton) {
                   JFrame frame2 = new JFrame("Recognition");
                   frame2.getContentPane().add(new JTextField(20));
                   frame2.pack();
                   frame2.setVisible(true);
              if( source == SynthesizerButton) {
                   JFrame frame3 = new JFrame("Synthesizer");
                   frame3.getContentPane().add(new JTextField(20));
                   frame3.pack();
                   frame3.setVisible(true);
         public static void main(String[] args)
              try
                   UIManager.setLookAndFeel(
                   UIManager.getCrossPlatformLookAndFeelClassName());
              } catch (Exception e) { }
              JFrame frame = new JFrame("VoicePronunciationSystem");
              //JFrame frame2 = new JFrame ("Recognition");
              //JLabel label = new JLabel ("This is a Voice Pronunciation System");
              //frame.getContentPane().add(label);
              VoicePronunciationSystem sys = new VoicePronunciationSystem();
              Component contents = sys.createComponents();
              frame.getContentPane().add(contents, BorderLayout.CENTER);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    }

Maybe you are looking for

  • Why do I get this window on exiting CS5

    Hi all, Using Vista Ultimate SP2 x64. No problems with install and program functions perfectly until shut down. When finished working on photos and close CS5 either with the 'Big Red X' or 'Exit' from the drop down menu I get this window I know it st

  • Error in SAPscript pdf email attachment

    Hi All,          I have implemented the functionality in ABAP where I can send SAPscript output to user via pdf-email in its inbox.The functionality is working fine in Dev n Test system with no issues.As the form is moved into Prod system, the user i

  • Front Row Music Help

    The simple problem is, when I open Front Row it says that the track cannot be played. This only happens with some songs i.e. Dragonforce but works perfectly with others i.e. Muse. Just for the record I have just moved over from a PC and my iTunes son

  • Panel Switching

    I am having trouble switching panels. http://www.elovitz.net/help.zip Please reference myJFrame.java where the panelSwitch method is defined, welcomePanel where the method is called, and testPanel what should be displayed after. The panel switch meth

  • MIRO accounting entries

    Hi All,            i need to what are accounts those are hit when we post IR recipt in MIRO.  I got an idea GR/IR clearing accounting and vendor account should be hit. But there are so many entries when i am posting. Please provide me which transacti