HOWTO: Draw on top of a JPanel without it beeing repainted?
Hey,
I have made a JPanel which draws some graphics with the use of the paintComponent() method. What I want now is a layer on top of this JPanel where I can draw a filled circle where the mousepointer is. How can this be achieved without the underlying JPanel beeing redrawn?
- KHM
Reminds me of The Glass Pane example
http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html
Similar Messages
-
How can I draw on top of an image?
I'm using a JApplet with three JPanel's inside of it.
Inside one of those JPanel's I would like to place an image and a button. When the button is clicked, I want to draw an oval on top of the image . Each subsequent time the button is clicked, the oval will move to a different location.
So here are my questions:
1) What should I use to draw the image? (a JLabel with an ImageIcon on it?)
2) Could I simply use g.drawOval() in paintComponent() to directly draw on top of the image/JLabel?
Any help will be greatly appriciated.Here's a sample to study;-import java.awt.*;
import java.awt.event.*;
public class DrawOnImage extends java.applet.Applet{
int xPos, yPos;
Image img;
public void init() {
add(new Label("Hello World") );
Button press = new Button("press");
add(press);
press.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
xPos = (int)(Math.random()*270);
yPos = (int)(Math.random()*170)+30;
repaint();
img = getImage(getDocumentBase(), "anImage.JPG");
public void paint(Graphics g){
g.drawImage(img,0,30,this);
if(yPos>=30)g.fillOval(xPos, yPos, 45, 45);
} -
Photo editor: fade a photo and draw on top of it?
I want to "fade" JPG pictures of people and then draw on top of them with a brush tool to emphasize posture (for instructional purposes) and save as a JPG. By "fade" I mean lighten the pic so that my drawn lines will stand out.
It appears that GIMP will do this. Can you also do that with SeaShore? In their documentation it is not clear to me; I get bogged down with tech lingo about layers and transparent colors and so on. My goal is to find a tool to do the above without getting something way more sophisticated than I need. Thanks for any help.
FranI'm not familar with GIMP, but I can shed some light onto the layers and transparency you would need to use.
Layers are quite simple. They are like a stack of papers, you can see the page on top, and the page below if it sticks out beyond the edges of the top sheet. The same is true in photo programs. You will see the top layer, and things behind it will be obscured by the objects or images on the top layer.
Transparency is the "fade" you are looking for. Note that Opacity is the opposite of transparency (as in 100% opaque is 0% transparent). My reducing transparency on a layer, you allow the layers behind it to become partially visible, IE you allow them to sneak through.
To accomplish your goal, should should take the images, and fade them by reducing their opacity. I would start with reducing it to 70%, but you'll have to play with it to get things just right.
After doing this, create a new layer, and be sure the new layer is on top off the image layer. In this new layer, take a brush tool and draw whatever you like. You should see you drawing ontop of the photo. If not, I suspect you have actually placed your line layer behind your photo layer, and you should simply trade their locations.
Hope this helps, -
Is it possible to layer a see through pane on top of my contents pane so that i can effectively draw on top of my current image without having to call paintComponent().
how can i do it?from the desciption of panes glasspane seems to be what you want but i never have done anything with theese panes so don't count on it.
-
Display image in JPanel without saving any file to disk
Hi,
I am fetching images from database. I am saving this image, display in JPanel and delete it. But this is not actually I want.
I wish to fetch this image as stream , store in memory and display in JPanel without saving any fiel in disk.
I wonder if it is Possible or any used implementation that I can use in my project. Any idea or experienced knowledge is enough.
ThanksIn what format is the image coming to you from the database? If it's an InputStream subclass, just use javax.imageio.ImageIO:
InputStream in = getImageInputStream();
BufferedImage image = null;
try {
image = ImageIO.read(in);
} finally {
in.close();
// ... Display image in your JPanel as you have beenIf you receive the image as an array of bytes, use the same method as above, but with a ByteArrayInputStream:
byte[] imageData = getImageData();
ByteArrayInputStream in = new ByteArrayInputStream(imageData);
BufferedImage image = null;
try {
image = ImageIO.read(in);
} finally {
in.close();
// ... Display image in your JPanel as you have been -
Draw on top of the system's Window Chrome?
We'd like to use the system chrome for our desktop app, but we'd also like to be able to draw on top of it. We would like to show a button that prompts them to purchase the trial version of our software for example, or notify them that there is an update available. I don't want to use custom Chrome because we want whatever is there by default. We simply want to draw on top of it. Is that an option? My Googling and experiments have not yielded much!
Many thanks for any help you can offer!You can uninstall your current Persona and revert to the Default theme (Tools > Add-ons > Themes).
See [[Personas]] and http://kb.mozillazine.org/Themes (Lightweight theme) -
How do I make text sit on top of an image without it disappearing.
I am currently copying and pasting images with captions from quark express files to indesign cs6 files.
Everytime I copy and paste these images the captions which are on top of the image disappear behind
the image. How do I put the text back on top of the image? and in general how do you put text on top
of an image without it disappearing?text.on.image.question wrote:
I am currently copying and pasting images with captions from quark express files to indesign cs6 files.
This is probably a really bad workflow that will end up biting you. I've not actually been able to copy a an image box from Quark and paste it into ID to test, so I don't know waht youare doing, exactly, but odds are you are not pasting a link to the image (doe sit show a link in ID's Links panel?). If not, you should be building this from scratch or opening the Quark file directly in ID (up to version 4 with out a plugin, later than that requires the Q2ID plugin from Markzware). -
Drawing anime on Adobe Photoshop cs4 without a tablet?
i'm seriously losing my patience with Photoshop bc i can't even draw the outline of an eye without having it all broken and curved. i use the mouse pad thing so its harder for me to focus it. Are there any tutorials or tips that you can share with me?
Use the selection tools rather than trying to draw freehand. The pen tool would be a good choice because you can edit the lines after creating them, but the eliptical marquee tool would produce a realistic eye shape, and you can use Select > Transform selection to fine tune. Then there are Shapes, and if the shape you want it is not already available, Google Photoshop Shapes eye would no doubt find what you are after. Then there is the grid that you can use with Snap to grid, or custom brushes..... I bet even the best Photoshop experts use aids and shortcuts to speed up the process, and to help them create cleaner lines.
But you asked for a tutorial, and Google seems to have lots to chose from
http://gas13.ru/v3/tutorials/drawing_human_eye.php
http://www.youtube.com/watch?v=DkeF7gfyM-U -
How to draw an Image on a JPanel?
Hi all,
Can any one give code for drawing an image on a JPanel?
thanks,
amarThat's for the JLabel right? ... For a JPanel on a JFrame, you could do something like this:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.URL;
public class TestImagePaint extends JFrame {
private BjPanel bjp;
public TestImagePaint( String imageName ) throws IllegalArgumentException {
if ( imageName == null || !( new File( imageName ).isFile() ) ) {
throw new IllegalArgumentException( "\nIn TestImagePaint constuctor"
+"\t IllegalArgumentException:" );
bjp = new BjPanel( imageName );
getContentPane().add( bjp );
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setBounds( 100, 100, 400, 300 );
setVisible( true );
public static void main( String[] argv ) {
new TestImagePaint( argv[0] );
public class BjPanel extends JPanel {
private URL url;
private Image image;
public BjPanel( String imageName ) {
try {
url = BjPanel.class.getResource( imageName );
image = Toolkit.getDefaultToolkit().getImage( url );
repaint();
catch( Exception e ) {
System.out.println( "Can't get Image: "+imageName+"\n\t"+e );
System.exit( -1 );
public void paint(Graphics g) {
g.drawImage( image, 0, 0, this );
} -
Can I physically stack Mac Minis on top of each other without heat problems?
Can I stack mac Minis on top of each other without encountering heat probs and such or do I need some sort of "rack" system?
yes, no problem, but make a spacer for them out of rubber feet. etc. of about 1/2 inch
-
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 PMjibbylala 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. -
Hi there.
if I have JPanel that contains a JLabel that contains is a 600x800 image, how can i draw a shape like circle on top of the image? I would like to be able to see the image with the circle on it. How can i make this possible?
Right now i can draw the circle on its own JPanel, but that is not what i want.
ThanksNotably, that you have a inner class referencing
image variables defined in the class it's nested in.Inner classes can access all members of the declaring class,
even private members. In fact, the inner class itself is said to be
a member of the class; therefore, following the rules of
object-oriented engineering, it should have access to all
members of the class.
The inner class does nothing to set it's own size,
, since as far as that JLabel instance knows, it
contains nothing.
But this is not corrected, it's
only relying on the BorderLayout to fill the frame
with the label.
While your sample works fine as is, it's not very
portable. As the OP posted after, he attempted to
use your code adding a JPanel in between the content
pane and the label, and it wouldn't work because of
the layout issues. To solve that, one might tend
towards defining a null layout and setting the bounds
explicitly, or one might add a setMinimumSize or
setPreferredSize call to get a size.
But that's adding more code to fix a problem that has
a much simpler solution. Which is to just give the
label the image directly, let the label size itself
automatically based on that image, let the label draw
the image itself and only override paint to get the
custom drawing done on top.
Myself, I understand what you were saying in your
code. But clearly the OP did not, and I suspect was
heading to starting patching what wasn't working by
applying more code when one could more cleanly use
less code and take advantage of what JLabel will
already do for you.Agreed. But this problem can also be easily solved with "setPreferredSize(new Dimension(200,200));" in the constructor of "Picture". -
Drawing on top of a gif image.
I need to be able to have a JPanel that holds a .gif image, have another JPanel over top of it that can be drawn upon. An example of this is placing a map on a table and laying a piece of clear plastic over top of it, then drawing on the plastic the route you want to take. Just as in this example, I want to be able to erase lines on the top image, but I can probably figure that part out OK, I just need the code to layer the drawing panel on top on the image.
How can this be done?
Thanks.Exactly what problem are you having with getting a layered pane? The Java Tutorial on this site can give you all the basics regarding setting one up.
-
Hello!
I am trying to create a Panel on which I can draw stuff using the mouse. I have managed to get it working, apart from one small part. I want to have an image (jpg) as a background, and as soon as I try to add an image either the image does not show or the drawing stuff stops working.
Here is my working drawing code (i.e. without image):
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null || image.getWidth(null) != getWidth()
|| image.getHeight(null) != getHeight()) {
image = (BufferedImage) createImage(getWidth(), getHeight());
graph = (Graphics2D) image.getGraphics();
graph.fillRect(0, 0, getWidth(), getHeight());
graph.setColor( Color.white );
graph.setStroke(new BasicStroke(3));
graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
Rectangle r = g.getClipBounds();
g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
r.x + r.width, r.y + r.height, null);
if (endPoint != null) {
g.setColor(currentColor);
if (shapeType == 0)
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
if (shapeType == 1)
g.drawOval(pn.x, pn.y, pn.width, pn.height);
if (shapeType == 2)
g.drawRect(pn.x, pn.y, pn.width, pn.height);
public void mouseDragged( MouseEvent m ) {
if (shapeType > 3 && shapeType != 8)
return;
if (endPoint == null)
endPoint = new Point();
repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
pn.x = Math.min(startPoint.x, m.getX());
pn.y = Math.min(startPoint.y, m.getY());
pn.width = Math.abs(m.getX() - startPoint.x);
pn.height = Math.abs(m.getY() - startPoint.y);
if (shapeType == 0) {
endPoint.setLocation(m.getPoint().getLocation());
if (shapeType == 3) {
graph.setColor(currentColor);
graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
startPoint = m.getPoint();
repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
public void mouseReleased(MouseEvent m) {
if (endPoint != null)
draw();
endPoint = null;
public void mousePressed(MouseEvent m) {
startPoint = m.getPoint();
public void draw() {
graph.setColor(currentColor);
if (shapeType == 0)
graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
if (shapeType == 1)
graph.drawOval(pn.x, pn.y, pn.width, pn.height);
if (shapeType == 2)
graph.draw(pn);
repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
}To me it seemed logical to add:
graph.drawImage(my_gif, 0, 0, this);at the end of the if statement, but that did not work.
Where and how should I add the image?
Thanks!Thanks for answering!
Here is the entire code:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class ImageExample extends JApplet {
private static final Dimension DRAWING_AREA_SIZE = new Dimension(300,300);
private static final Point DRAWING_AREA_UPPER_LEFT = new Point(100,50);
private static final Color BACKGROUND_COLOR = Color.black;
private Image my_gif;
private Color currentColor = Color.white;
private JLabel currentColorIndicator;
private JPanel pane = new JPanel(null);
Point startPoint, endPoint;
Rectangle pn = new Rectangle();
BufferedImage image;
Graphics2D graph;
int shapeType = 3;
public void init() {
setContentPane(pane);
my_gif = getImage( getDocumentBase(), "fractal.gif" );
pane.setOpaque(true);
pane.setBackground(BACKGROUND_COLOR);
createColorMap();
DrawingPanel drawingPanel = new DrawingPanel();
drawingPanel.setBounds(DRAWING_AREA_UPPER_LEFT.x, DRAWING_AREA_UPPER_LEFT.y, DRAWING_AREA_SIZE.width,
DRAWING_AREA_SIZE.height);
pane.add(drawingPanel);
// Private methods
private void createColorMap() {
ColorPickerListener listener = new ColorPickerListener();
JLabel colorText = new JLabel("Color");
colorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y-20, 50, 25);
colorText.setForeground(Color.white);
pane.add(colorText);
JLabel redColor = new JLabel("");
redColor.addMouseListener(listener);
redColor.setBackground(Color.RED);
redColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+10, 50, 30);
redColor.setOpaque(true);
pane.add(redColor);
JLabel blueColor = new JLabel("");
blueColor.addMouseListener(listener);
blueColor.setBackground(Color.blue);
blueColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+40, 50, 30);
blueColor.setOpaque(true);
pane.add(blueColor);
JLabel whiteColor = new JLabel("");
whiteColor.addMouseListener(listener);
whiteColor.setBackground(Color.white);
whiteColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+70, 50, 30);
whiteColor.setOpaque(true);
pane.add(whiteColor);
JLabel greenColor = new JLabel("");
greenColor.addMouseListener(listener);
greenColor.setBackground(Color.green);
greenColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+100, 50, 30);
greenColor.setOpaque(true);
pane.add(greenColor);
JLabel blackColor = new JLabel("");
blackColor.addMouseListener(listener);
blackColor.setBackground(Color.black);
blackColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+130, 50, 30);
blackColor.setOpaque(true);
pane.add(blackColor);
JLabel grayColor = new JLabel("");
grayColor.addMouseListener(listener);
grayColor.setBackground(Color.gray);
grayColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+160, 50, 30);
grayColor.setOpaque(true);
pane.add(grayColor);
JLabel yellowColor = new JLabel("");
yellowColor.addMouseListener(listener);
yellowColor.setBackground(Color.yellow);
yellowColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+190, 50, 30);
yellowColor.setOpaque(true);
pane.add(yellowColor);
// Display currently chosen color
JLabel currentColorText = new JLabel("Current");
currentColorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+230, 50, 25);
currentColorText.setForeground(Color.white);
pane.add(currentColorText);
currentColorIndicator = new JLabel("");
currentColorIndicator.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+260, 50, 30);
updateCurrentColorLabel();
currentColorIndicator.setOpaque(true);
pane.add(currentColorIndicator);
private void updateCurrentColorLabel() {
currentColorIndicator.setBackground(currentColor);
currentColorIndicator.setForeground(new Color(255 - currentColor.getRed(), 255 - currentColor.getGreen(),
255 - currentColor.getBlue()));
// Private classes
private class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener {
BufferedImage image;
public DrawingPanel() {
addMouseMotionListener(this);
addMouseListener(this);
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null || image.getWidth(null) != getWidth()
|| image.getHeight(null) != getHeight()) {
image = (BufferedImage) createImage(getWidth(), getHeight());
graph = (Graphics2D) image.getGraphics();
graph.fillRect(0, 0, getWidth(), getHeight());
graph.setColor( Color.white );
graph.setStroke(new BasicStroke(3));
graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
graph.drawImage(my_gif, 0, 0, this);
System.out.println(my_gif + " <- my_gif");
System.out.println(my_gif.getWidth(this) + " <- my_gif.getWidth(this)");
System.out.println(my_gif.getHeight(this) + " <- my_gif.getheight(this)");
Rectangle r = g.getClipBounds();
g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
r.x + r.width, r.y + r.height, null);
if (endPoint != null) {
g.setColor(currentColor);
if (shapeType == 0)
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
if (shapeType == 1)
g.drawOval(pn.x, pn.y, pn.width, pn.height);
if (shapeType == 2)
g.drawRect(pn.x, pn.y, pn.width, pn.height);
public void mouseDragged( MouseEvent m ) {
if (shapeType > 3 && shapeType != 8)
return;
if (endPoint == null)
endPoint = new Point();
repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
pn.x = Math.min(startPoint.x, m.getX());
pn.y = Math.min(startPoint.y, m.getY());
pn.width = Math.abs(m.getX() - startPoint.x);
pn.height = Math.abs(m.getY() - startPoint.y);
if (shapeType == 0) {
endPoint.setLocation(m.getPoint().getLocation());
if (shapeType == 3) {
graph.setColor(currentColor);
graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
startPoint = m.getPoint();
repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
public void mouseReleased(MouseEvent m) {
if (endPoint != null)
draw();
endPoint = null;
public void mousePressed(MouseEvent m) {
startPoint = m.getPoint();
public void draw() {
graph.setColor(currentColor);
if (shapeType == 0)
graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
if (shapeType == 1)
graph.drawOval(pn.x, pn.y, pn.width, pn.height);
if (shapeType == 2)
graph.draw(pn);
repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) { }
public void mouseExited(MouseEvent arg0) { }
public void mouseMoved(MouseEvent arg0) { }
//Listeners
private class ColorPickerListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JLabel color = (JLabel) e.getSource();
currentColor = color.getBackground();
updateCurrentColorLabel();
}So the problem might be that the system.outs in there put out:
sun.awt.image.ToolkitImage@1a0c10f <- my_gif
-1 <- my_gif.getWidth(this)
-1 <- my_gif.getheight(this)I don't know how to fix so that the height and width are set. Isn't it enough to do the:
my_gif = getImage( getDocumentBase(), "fractal.gif" );before initializing the drawing panel?
Thanks again! -
How to draw a 3Drect in a JPanel.
Hi, I'd like to draw a 3D rectangle in a panal to make some components looks grouped. e.g. if I have a name(JLabel: JTextField) and address(JLabel:JTextField) in a panel and want to draw a 3D rectangle around these two fields, how can I do that? Looks that the paint(Graphics g) doesn't work here.
The following is my test program, it has two files, an applet as program entrance and a Panel to draw on:
// TestApplet.java
import javax.swing.*;
public class TestApplet extends JApplet {
public void init() {
TopPanel tp = new TopPanel();
add(tp);
// TopPanel.java
import javax.swing.*;
public class TopPanel extends JPanel {
public TopPanel() {
JLabel lb = new JLabel("test");
add(lb);
Choice c = new Choice();
c.add("1");
c.add("2");
add(c);
public void paint(Graphics g) {
g.draw3DRect(5, 5, 40, 40, false);
super.paint(g);
}sorry for the messy code.
I've tried switching the two lines, but it doesn't
work. :(
Here is the repost of the code, I don't know why I
can't edit the original post....
// TestApplet.java
import javax.swing.*;
public class TestApplet extends JApplet {
public void init() {
TopPanel tp = new TopPanel();
add(tp);
// TopPanel.java
import javax.swing.*;
import java.awt.*;
public class TopPanel extends JPanel {
public TopPanel() {
JLabel lb = new JLabel("test");
add(lb);
Choice c = new Choice();
c.add("1");
c.add("2");
add(c);
public void paint(Graphics g) {
super.paint(g);
g.draw3DRect(5, 5, 40, 40, false);
1. You can only edit posts that have not been replied to.
2. Your code worked for me? (What is the problem).
3. Suggestions use a JComboBox instead of Choice. (It is not good to mix AWT and Swing.) Also you should be overiding paintComponentinstead of paint.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.draw3DRect(5, 5, 40, 40, false);
}
Maybe you are looking for
-
How do you watch a Final cut pro movie on TV
Hi i'm new to FCP I have just put together a holiday movie using my Mac book pro and FCP ver. 10.1.3 using both stills and movie clips i'm struggling with the following can anyone help I'm trying to save the movie on my portable Toshiba hard drive wi
-
I am trying to assign a device (HP OfficeJet Pro 8500 printer/fax/Scanner) to Image Capture. Using browse the device is listed, however I do not seem to be able to get it assigned so that Image Capture will use it. What am I doing wrong. Thanks! JB
-
How do I erase an icloud account if I don't have the previous persons password
-
Minimun requirements to see a 3D model in a PC and mobile devices
What are the minimum requirements to see a 3D model in a PC? CPU, RAM, Graphics Card... And other question about this matter. I have tried to see a 3dpdf in a ipad but nothing is displayed at the 3d window. Is it posible to display 3d pdf in Tablets,
-
How to create dynamic strcture for a interrnal table
first i created one internal table . with five fields . suppose i want add two more fields in internal table. what is the code for the this . if any one konow