Drawing onto multiple JFrames

i'm writing code to make a JFrame that a moving image in it, using timers, but I keep getting runtime errors. I need a new way to draw onto a JFrame.
here is some code:
public void paint(Graphics g) {
super.paint(g);
     g.drawImage( target, 10, 30, this );
     speedFrame.getGraphics().drawImage( bg, 0, 0, this );
     speedFrame.getGraphics().drawImage( hbar, 5, y, this );
     spotFrame.getGraphics().drawImage( bg2, 0, 0, this );
spotFrame.getGraphics().drawImage( vbar, x, 20, this );
     if( playing == true )
          g.drawImage( ball, maxx, by, this );
the part that I need help with is speedFrame.getGraphics().drawImage()

Swing related questions should be posted in the Swing forum.
This posting, from the Swing forum, contains a couple of examples on animation:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

Similar Messages

  • Multiple JFrames

    Hi. I have a situation where I need to display multiple JFrames. I have an application with a control panel that has the ability to launch another application (via a JButton). The only problem is, the only handle I have to that other application is another JButton, so I end up with something that looks like:
    JButton launchButton = new JButton();
    launchButton.setAction(new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            //SomeOtherApp extends JFrame
            SomeOtherApp app = new SomeOtherApp();
            app.setVisible(true); 
    });This works, but I run into all sorts of repainting problems. Since SomeOtherApp is so large, it seems to be hogging the Event-Dispatching Thread, and the app never repaints my control panel JFrame correctly. Any thoughts on how to improve this performance?
    Thanks,
    Jeff

    Only one frame ever has focus at a time and therefore only one frame ever responds to events at a time. So neither frame should be affecting the other.

  • Creating multiple JFrames in one program

    What kind of trouble should I look for when creating multiple JFrames in one application. These JFrames will talk to each other via drag and drop. Is this ok?

    What kind of trouble would you like? I'm sure you can engineer all kinds. As long as you have a place to hold the frame references, you should be okay. If you need them.
    You can do drag and drop between components in different frames, no problem. Better read up on drag and drop first though.

  • Separating a database onto multiple servers

    We are working on a product that uses a set of SQL Server databases that are currently all in one instance and on one server. Now that we are growing, we need more processing power/space. So we want to move the databases onto multiple servers.
    So we would not need to "shard", we created separate databases (with the same schema) for each company that purchased the product. We could readily put different company databases onto the different servers.
    The question is this, how to we handle the routing to the different servers?
    If we would have "sharded" the data in one database with different keys, SQL Server tools would have handled the routing for us. Because we actually separated the databases, do we have to do the routing manually? (That is, do we need to figure
    out that when company A logs in that they need to go to database server aa.aa.aa while compay B needs to go to server bb.bb.bb?) Or is there a product that can help us with the routing?
    Thanks!
    www.insteptech.com ;
    msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!

    Hello,
    Based on your description, it seems that you want to copy all schema from a "Shared" database into other servers and separate data into the tables based on the company name.
    If I understand correctly, you can try to use the
    SQL Server Import and Export Data Wizard to copy data from table or view to destination server and specify query to restrict data  for copy. Or you can use linked server and
    SELECT INTO statement with condition to move the data.
    As per my understanding about the "Handling routing", balancing capability. In order to meet your requirement, you have to load balance through your application's design.
    Regards,
    Fanny Liu
    If you have any feedback on our support, please click here.
    Fanny Liu
    TechNet Community Support

  • Multiple jFrames in Application

    Hello,
    I am having problems finding documentation or an example on how to make multiple jFrames work.
    In my application I have my main jFrame and would like something very simple to where the user can open a second jFrame while the main jFrame is still visible (the second jFrame would have focus) the user can use the functionality of the second jFrame and then close it returning the focus back to the main jFrame.
    Can you point me into the right direction for doing this?
    Thanks,
    Tim

    Your question is too general. There are many ways to do this. First, what action do you want the user to take to open the second JFrame. Select a menu item? Click a button? Enter a value into a text input field? <continueAdNauseum/>
    Secondly, does the second JFrame prevent your user from continuing to work in the first JFrame. Then, Encephalopathic is correct ... JDialog is a top level container that can block input from other top level containers and their contents (using the [Modality API|http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/modality/]). A JFrame is another top level container, and you can open as many as you like.
    It's always good to start with the [Java Tutorial|http://java.sun.com/docs/books/tutorial/]. Pay special attention to the [Swing Tutorial|http://java.sun.com/docs/books/tutorial/ui/index.html] . It may seem like a lot to wade through, but you will learn alot. Then, as specific questions come up. you can ask them here.
    ¦ {Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • An App to allow drawing onto a photograph?

    Does anyone know if there is an App for the iPad that lets you draw onto a photograph? I do a lot of digital map work and it would be great to be able to draw onto the screen and save.

    I highly recommend Skitch.  It is one of the better apps out there and it is free.
    http://itunes.apple.com/us/app/skitch-for-ipad/id490505997?ls=1&mt=8

  • IPhone3 - can I sync onto multiple PCs running iTunes ? or is this a one-one relationship ?

    Can I sync onto multiple PCs running iTunes ? or is this a one-one relationship ?
    My situation - use home computer for music etc., boat computer for weather file downloads,officecomputer for email / pictures ...
    Thank you

    There is an App called Weathertrack, which pulls from the web GRIB files (weather information), that I would like to download onto the laptop we have on the boat, that runs some routing software (SeaTrack), that in turn integrates weather, tide, GPS etc to help with vessel navigation.
    I can obviously do this from my home computer (this is the one that has the 1-1 sync relationship), but I don't want to empty the IPhone content whilst on the boat ...
    If you can think of a way of making this happen, I would be very appreciative. Both PCs are windows based, home is Vista, boat is XP.
    Kind regards

  • Downloading Logic Pro X onto multiple macs

    Will I be able to install (download) Logic Pro X onto multiple macs like I did with Logic 8? (Only one used at a time).

    Yes you can. (Sorry. The other post with the answer popped up as soon as I posted.
    Thx

  • Backup itunes onto multiple DVDs

    I am wanting to backup my itunes to multiple DVDs and not sure how to do it. I have copied all of the files to a 'burn file', and have tried to start burning...but am told that all of the files need to fit on 1 DVD. Surely there is a way to burn onto multiple DVDs? I will need about 4.
    If this isn't an option, what are some other suggestions about backing up my music. I don't want to regret not backing up later!!
    thanks!
    ibookG4   Mac OS X (10.4.2)  

    This isn't really the forum to post this in, as 'Feedback about DIscussions' means posts related to the Apple Discussions Forums, eg 'why can't I log in on Mondays?' 'this poster is shouting at me' etc.
    Are you a member of .mac? If so you could use the iLife plan (or create a new iTunes plan) to backup your music across multiple DVDs.
    Matt

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

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • Java Graphics -- Drawing Strings on JFrame

    Hello and thank you. I'm relatively young and I apologize for asking noob questions. The problem I am having is that I realized after 3 hours of research and then writing this code that when multiple JPanels are added to a JFrame, they overlap (I think) over each other. As a result, the output of this program below is at the bottom right of the frame, the number 841 appears (the last number in my array) and everything else is blank.
    And I could not at all understand how to create graphics objects. It kept giving me an error of not being able to be instantiated. And to be honest, I don't even really understand whats going on when I add the text to my JPanel. I never call paintComponents. And definately I could never even make a graphics object to provide it the parameter required. Anyway, I resolved to use Jpanels because they can be removed using the remove function of the JFrame. And It is vitally important that I can delete the strings off my frame. Here is my code:
    package main;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class VisualFrame extends JFrame{
        ArrayList<JPanel> numbers = new ArrayList<JPanel>();
        public VisualFrame(){
            setSize(1000, 500);
            setTitle("Binary Search");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        public void createPanels(int[] array){
            int x = 10;
            int y = 20;
            int xOffset = 50;
            int yOffset = 50;
            for(int i=0; i<array.length; i++){
                String num = Integer.toString(array);
    numPanel panel = new numPanel(num, x, y);
    numbers.add(panel);
    add(panel);
    x = x+xOffset;
    if(x>this.getWidth()){
    x = 10;
    y = y+yOffset;
    class numPanel extends JPanel{
    String num;
    int x;
    int y;
    public numPanel(String str, int x, int y){
    num = str;
    this.x = x;
    this.y = y;
    public void paintComponent(Graphics g){
    g.setColor(Color.black);
    g.setFont(new Font("Times", Font.BOLD, 12));
    g.drawString(num, x, y);
    My main method is inside of a different class:
        public static void main(String[] args){
            VisualFrame frame = new VisualFrame();
            frame.createPanels(array);
        }Firstly, do I even have the problem I'm having right? If so,
    Is there a way to restrict the size of the panels to the length and width of what it contains?
    Or can someone give me a good, very detailed link to how to use Graphics? Or perhaps someone could prove to me a good method.
    Edited by: 989946 on Mar 8, 2013 6:45 PM

    Why don't you start by learning from the experts?
    The Java Tutorial has sections that show how to use Java functionality.
    http://docs.oracle.com/javase/tutorial/
    The Graphiics section covers GUI and Swing
    http://docs.oracle.com/javase/tutorial/uiswing/index.html
    >
    Creating Graphical User Interfaces
    Creating a GUI with Swing — A comprehensive introduction to GUI creation on the Java platform.
    >
    And that section has links for trails such as how to use ALL of the different swing components including frames and panels
    http://docs.oracle.com/javase/tutorial/uiswing/components/index.html
    >
    Using Swing Components tells you how to use each of the Swing components — buttons, tables, text components, and all the rest. It also tells you how to use borders and icons.

  • How do you print one large image onto multiple smaller sheets?

    For example, I want to print one 17x22-inch image onto 2, 8.5x11-inch sheets.

    I think you have your calculations wrong. It would take four sheets of paper to have the same size image because you have to double in both directions. I think printing an image on multiple pages is a function of the printer. If your printer has that capability then the options will be in the printer driver. Otherwise, I guess you could try to create virtual copies and crop each one individually and print them and hope they match up.
    My printer does not have that capability, so I'm not familiar with how it would work. But it might be necessary to print outside of Lightroom in order to me that feature function properly. If it sounds like I don't know what I'm talking about, that's probably because I don't, really.

  • Backing up multiple HDs onto Multiple HDs

    I have 4 1TB hard drives that I am trying to backup onto 8 500GB hard drives. I have done this in the past manually, but its been a major headache, as I ususally have to split up folders across multiple drives to make it fit properly.
    Can anyone recommend and application that would assist in this kind of backup procedure...in particular, one that would also allow me to synchronize/update the backup to reflect changes made to the source drives?
    Thanks!

    THanks for the suggestion...I've thought about doing that, but the problem is that when you do configure two 500GB hard drives together using disk utility, it somehow consumes a relatively small amount of hard drive space to pull-off the raid configuration...this leaves my two 500Gb drives with something like 900GB of disk space, and that won't cut it for my backup, as the source drive is completely maxed out...Plus there are performace issues, as well as reliability issues involved when creating a RAID using two independant drives by using Disk Utility...
    Thanks for the suggestions though...Anyone else know of an application out there that can assist me in accomplishing my goal here? Thanks!

  • Netbeans and Multiple jFrames

    Hey,
    Does anyone know how to make an application have multiple windows/jFrames with Netbeans 5.5's GUI builder?
    I created another jFrame in my application by right-clicking on my source package in the Projects window and selecting New... --> jFrame Form...
    How do you make the new jFrame form I created become visible from the first jFrame form I have?
    Once I have that new form visible, how do I make it do stuff to the first jFrame form?

    Here's a little example:
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    class Frame1 extends JFrame {
         private JButton button;
         public Frame1() {
              initComponents();
         private void initComponents() {
              button = new JButton("New Frame");
              button.setSize(100, 20);
              button.setLocation(5, 5);
              this.getContentPane().setLayout(null);
              this.getContentPane().add(button);
              this.pack();
              this.setSize(400, 400);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setTitle("Demo");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        new Frame2().setVisible(true);
         public static void main(String[] argv) {
              new Frame1().setVisible(true);
    class Frame2 extends JFrame {
         private JMenuBar jmb;
         private JMenu menu;
         private JMenuItem exitItem;
         public Frame2() {
              initComponents();
         private void initComponents() {
              jmb = new JMenuBar();
              menu = new JMenu("File");
              menu.setMnemonic((int)'F');
              exitItem = new JMenuItem("Exit");
              exitItem.setMnemonic((int)'X');
              jmb.add(menu);
              menu.add(exitItem);
              this.setJMenuBar(jmb);
              this.pack();
              this.setSize(100, 100);
              this.setTitle("Demo 2");
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setResizable(false);
              this.setLocationRelativeTo(null);
              exitItem.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        System.exit(0);
    }

Maybe you are looking for