I am a beginner with this Java GUI (comp sci has taught only basic basic things) and I am trying to get mouseclick to work on a panel but when the mouseclick method is called the drawings I make in them are not repainted to the panel. How would I go about doing this? And I do know that the mousepressed is working since I have tried doing a System.close(0) with it and it has worked, it is just the graphics that are screwy. Please help!
posted 5 years ago
Your problem is that to do proper graphics programming in Swing you (we) first have to shed many assumptions. For instance you should not extract a JPanel's Graphic object as you're doing it and assuming that it will persist because it won't. Read a tutorial or two on Swing graphics and you'll see that you should do all of your drawing in the JPanel's paintComponent method only and use the Graphics object that has been passed as a parameter (but don't try to save it as again it won't persist).
Some other things you might want to check out: I'd set the preferred size (not the size -- your current JPanel is size 10 x 10) of the drawing panel, and leave the JFrame size alone -- let it decide what is the best size based on its components. I'd pack and set the JFrame visible after adding components not before. I wouldn't set the background color of the JFrame but rather its components or its content pane.