Search Results

Search found 108 results on 5 pages for 'graphics2d'.

Page 3/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • How to make a character jump, both on objects and just normal jump.

    - by haxerflaxer
    Hi, I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects? Here's my code so far: Part one package Sprites; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; public class jumper { private String jump = "oka.png"; private int dx; private int dy; private int x; private int y; private Image image; public jumper() { ImageIcon ii = new ImageIcon(this.getClass().getResource(jump)); image = ii.getImage(); x = 50; y = 100; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png")); image = ii.getImage(); } if (key == KeyEvent.VK_RIGHT){ dx = 5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png")); image = ii.getImage(); } if (key == KeyEvent.VK_SPACE) { dy = -5; } if (key == KeyEvent.VK_DOWN) { dy = 5; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT){ dx = 0; } if (key == KeyEvent.VK_SPACE) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } Part two package Sprites; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; import javax.swing.Timer; public class board extends JPanel implements ActionListener { private Timer klocka; private jumper jumper; public board() { addKeyListener(new TAdapter()); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); jumper = new jumper(); klocka = new Timer(5, this); klocka.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { jumper.move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyReleased(KeyEvent e) { jumper.keyReleased(e); } public void keyPressed(KeyEvent e) { jumper.keyPressed(e); } } } Part three package Sprites; import javax.swing.JFrame; public class RType extends JFrame { public RType() { add(new board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setTitle("R - type"); setResizable(false); setVisible(true); } public static void main(String[] args) { new RType(); } } I really appreciate all the help I can get!

    Read the article

  • How do you make a character jump, both on objects and just normal jump?

    - by haxerflaxer
    Hi, I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects? Here's my code so far: Part one package Sprites; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; public class jumper { private String jump = "oka.png"; private int dx; private int dy; private int x; private int y; private Image image; public jumper() { ImageIcon ii = new ImageIcon(this.getClass().getResource(jump)); image = ii.getImage(); x = 50; y = 100; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png")); image = ii.getImage(); } if (key == KeyEvent.VK_RIGHT){ dx = 5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png")); image = ii.getImage(); } if (key == KeyEvent.VK_SPACE) { dy = -5; } if (key == KeyEvent.VK_DOWN) { dy = 5; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT){ dx = 0; } if (key == KeyEvent.VK_SPACE) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } Part two package Sprites; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; import javax.swing.Timer; public class board extends JPanel implements ActionListener { private Timer klocka; private jumper jumper; public board() { addKeyListener(new TAdapter()); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); jumper = new jumper(); klocka = new Timer(5, this); klocka.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { jumper.move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyReleased(KeyEvent e) { jumper.keyReleased(e); } public void keyPressed(KeyEvent e) { jumper.keyPressed(e); } } } Part three package Sprites; import javax.swing.JFrame; public class RType extends JFrame { public RType() { add(new board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setTitle("R - type"); setResizable(false); setVisible(true); } public static void main(String[] args) { new RType(); } } I really appreciate all the help I can get!

    Read the article

  • Rotating a NetBeans Visual Library Widget

    - by Geertjan
    Trying to create a widget which, when clicked, rotates slightly further on each subsequent click: Above, the bird where the mouse is visible has been clicked a few times and so has rotated a bit further on each click. The code isn't quite right yet and I'm hoping someone will take this code, try it out, and help with a nice solution! public class BirdScene extends Scene {     public BirdScene() {         addChild(new LayerWidget(this));         getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() {             public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) {                 Image dragImage = getImageFromTransferable(transferable);                 if (dragImage != null) {                     JComponent view = getView();                     Graphics2D g2 = (Graphics2D) view.getGraphics();                     Rectangle visRect = view.getVisibleRect();                     view.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);                     g2.drawImage(dragImage,                             AffineTransform.getTranslateInstance(point.getLocation().getX(),                             point.getLocation().getY()),                             null);                     return ConnectorState.ACCEPT;                 } else {                     return ConnectorState.REJECT;                 }             }             public void accept(Widget widget, final Point point, Transferable transferable) {                 addChild(new BirdWidget(getScene(), getImageFromTransferable(transferable), point));             }         }));     }     private Image getImageFromTransferable(Transferable transferable) {         Object o = null;         try {             o = transferable.getTransferData(DataFlavor.imageFlavor);         } catch (IOException ex) {         } catch (UnsupportedFlavorException ex) {         }         return o instanceof Image ? (Image) o : null;     }     private class BirdWidget extends IconNodeWidget {         private int theta = 0;         public BirdWidget(Scene scene, Image imageFromTransferable, Point point) {             super(scene);             setImage(imageFromTransferable);             setPreferredLocation(point);             setCheckClipping(true);             getActions().addAction(ActionFactory.createMoveAction());             getActions().addAction(ActionFactory.createSelectAction(new SelectProvider() {                 public boolean isAimingAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public boolean isSelectionAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public void select(final Widget widget, Point localLocation, boolean invertSelection) {                     theta = (theta + 100) % 360;                     repaint();                     getScene().validate();                 }             }));         }         @Override         public void paintWidget() {             final Image image = getImageWidget().getImage();             Graphics2D g = getGraphics();             g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             Rectangle bounds = getClientArea();             AffineTransform newXform = g.getTransform();             int xRot = image.getWidth(null) / 2;             int yRot = image.getWidth(null) / 2;             newXform.rotate(theta * Math.PI / 180, xRot, yRot);             g.setTransform(newXform);             g.drawImage(image, bounds.x, bounds.y, null);         }     } } The problem relates to refreshing the scene after the rotation. But it would help if someone would just take the code above, add it to their own application, try it out, see the problem for yourself, and develop it a bit further!

    Read the article

  • Rotate a Swing JLabel

    - by Johannes Rössel
    I am currently trying to implement a Swing component, inheriting from JLabel which should simply represent a label that can be oriented vertically. Beginning with this: public class RotatedLabel extends JLabel { public enum Direction { HORIZONTAL, VERTICAL_UP, VERTICAL_DOWN } private Direction direction; I thought it's be a nice idea to just alter the results from getPreferredSize(): @Override public Dimension getPreferredSize() { // swap size for vertical alignments switch (getDirection()) { case VERTICAL_UP: case VERTICAL_DOWN: return new Dimension(super.getPreferredSize().height, super .getPreferredSize().width); default: return super.getPreferredSize(); } } and then simply transform the Graphics object before I offload painting to the original JLabel: @Override protected void paintComponent(Graphics g) { Graphics2D gr = (Graphics2D) g.create(); switch (getDirection()) { case VERTICAL_UP: gr.translate0, getPreferredSize().getHeight()); gr.transform(AffineTransform.getQuadrantRotateInstance(-1)); break; case VERTICAL_DOWN: // TODO break; default: } super.paintComponent(gr); } } It seems to work—somehow—in that the text is now displayed vertically. However, placement and size are off: Actually, the width of the background (orange in this case) is identical with the height of the surrounding JFrame which is ... not quite what I had in mind. Any ideas how to solve that in a proper way? Is delegating rendering to superclasses even encouraged?

    Read the article

  • How to draw a circle in java with a radius and points around the edge

    - by windopal
    Hi, I'm really stuck on how to go about programming this. I need to draw a circle within a JFrame with a radius and points around the circumference. i can mathematically calculate how to find the coordinates of the point around the edge but i cant seem to be able to program the circle. I am currently using a Ellipse2D method but that doesn't seem to work and doesn't return a radius, as under my understanding, it doesn't draw the circle from the center rather from a starting coordinate using a height and width. My current code is on a separate frame but i need to add it to my existing frame. import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class circle extends JFrame { public circle() { super("circle"); setSize(410, 435); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Panel sp = new Panel(); Container content = getContentPane(); content.add(sp); setContentPane(content); setVisible(true); } public static void main (String args[]){ circle sign = new circle(); } } class Panel extends JPanel { public void paintComponent(Graphics comp) { super.paintComponent(comp); Graphics2D comp2D = (Graphics2D) comp; comp2D.setColor(Color.red); Ellipse2D.Float sign1 = new Ellipse2D.Float(0F, 0F, 350F, 350F); comp2D.fill(sign1); } }

    Read the article

  • How to display panels with component in frame

    - by terence6
    Why my JFrame 'frame' is diplaying empty window, when it should give me 3 menu buttons and my own painted JComponent below ? What am I missing here ? import java.awt.*; import javax.swing.*; public class Eyes extends JFrame { public static void main(String[] args) { final JFrame frame = new JFrame("Eyes"); frame.setPreferredSize(new Dimension(450, 300)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel players = new JPanel(new GridLayout(1, 3)); players.add(new JButton("Eyes color")); players.add(new JButton("Eye pupil")); players.add(new JButton("Background color")); JPanel eyes = new JPanel(); eyes.add(new MyComponent()); JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); content.add(players); content.add(eyes); frame.getContentPane(); frame.pack(); frame.setVisible(true); } } class MyComponent extends JComponent { public MyComponent(){ } @Override public void paint(Graphics g) { int height = 120; int width = 120; Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); BasicStroke bs = new BasicStroke(3.0f); g2d.setStroke(bs); g2d.setColor(Color.yellow); g2d.fillOval(200, 200, height, width); g2d.setColor(Color.black); g2d.drawOval(60, 60, height, width); } }

    Read the article

  • How to move point on arc?

    - by bbZ
    I am writing an app that is simulating RobotArm movement. What I want to achieve, and where I have couple of problems is moving a Point on arc (180degree) that is arm range of movement. I am moving an arm by grabbing with mouse end of arm (Elbow, the Point I was talking about), robot can have multiple arms with diffrent arm lenghts. If u can help me with this part, I'd be grateful. This is what I have so far, drawing function: public void draw(Graphics graph) { Graphics2D g2d = (Graphics2D) graph.create(); graph.setColor(color); graph.fillOval(location.x - 4, location.y - 4, point.width, point.height); //Draws elbow if (parentLocation != null) { graph.setColor(Color.black); graph.drawLine(location.x, location.y, parentLocation.x, parentLocation.y); //Connects to parent if (arc == null) { angle = new Double(90 - getAngle(parentInitLocation)); arc = new Arc2D.Double(parentLocation.x - (parentDistance * 2 / 2), parentLocation.y - (parentDistance * 2 / 2), parentDistance * 2, parentDistance * 2, 90 - getAngle(parentInitLocation), 180, Arc2D.OPEN); //Draws an arc if not drawed yet. } else if (angle != null) //if parent is moved, angle is moved also { arc = new Arc2D.Double(parentLocation.x - (parentDistance * 2 / 2), parentLocation.y - (parentDistance * 2 / 2), parentDistance * 2, parentDistance * 2, angle, 180, Arc2D.OPEN); } g2d.draw(arc); } if (spacePanel.getElbows().size() > level + 1) {//updates all childElbows position updateChild(graph); } } I just do not know how to prevent moving Point moving outside of arc line. It can not be inside or outside arc, just on it. Here I wanted to put a screenshot, sadly I don't have enough rep. Am I allowed to put link to this? Maybe you got other ways how to achieve this kind of thing. Here is the image: Red circle is actual state, and green one is what I want to do. EDIT2: As requested, repo link: https://github.com/dspoko/RobotArm

    Read the article

  • How to proceed jpeg Image file size after read--rotate-write operations in Java?

    - by zamska
    Im trying to read a JPEG image as BufferedImage, rotate and save it as another jpeg image from file system. But there is a problem : after these operations I cannot proceed same file size. Here the code //read Image BufferedImage img = ImageIO.read(new File(path)); //rotate Image BufferedImage rotatedImage = new BufferedImage(image.getHeight(), image.getWidth(), BufferedImage.TYPE_3BYTE_BGR); Graphics2D g2d = (Graphics2D) rotatedImage.getGraphics(); g2d.rotate(Math.toRadians(PhotoConstants.ROTATE_LEFT)); int height=-rotatedImage.getHeight(null); g2d.drawImage(image, height, 0, null); g2d.dispose(); //Write Image Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = (ImageWriter)iter.next(); // instantiate an ImageWriteParam object with default compression options ImageWriteParam iwp = writer.getDefaultWriteParam(); try { FileImageOutputStream output = null; iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(0.98f); // an integer between 0 and 1 // 1 specifies minimum compression and maximum quality File file = new File(path); output = new FileImageOutputStream(file); writer.setOutput(output); IIOImage iioImage = new IIOImage(image, null, null); writer.write(null, iioImage, iwp); output.flush(); output.close(); writer.dispose(); Is it possible to access compressionQuality parameter of original jpeg image in the beginning. when I set 1 to compression quality, the image gets bigger size. Otherwise I set 0.9 or less the image gets smaller size. How can i proceed the image size after these operations? Thank you,

    Read the article

  • JTable cells not rendering shapes properly

    - by Andrew
    I'm trying to render my JTable cells with a subclassed JPanel and the cells should appear as coloured rectangles with a circle drawn on them. When the table displays initially everything looks OK but then when a dialog or something is displayed over the cells when it is removed the cells that have been covered do not rendered properly and the circles are broken up etc. I then have to move the scroll bar or extend the window to get them to redraw properly. The paintComponent method of the component I'm using to render the cells is below: protected void paintComponent(Graphics g) { setOpaque(true); super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; GradientPaint gradientPaint = new GradientPaint(new Point2D.Double(0, 0), Color.WHITE, new Point2D.Double(0, getHeight()), paintRatingColour); g2d.setPaint(gradientPaint); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Rectangle clipBounds = g2d.getClipBounds(); int x = new Double(clipBounds.getWidth()).intValue() - 15; int y = (new Double(clipBounds.getHeight()).intValue() / 2) - 6; if (level != null) { g2d.setColor(iconColour); g2d.drawOval(x, y, width, height); g2d.fillOval(x, y, width, height); } }

    Read the article

  • What is the error in this java code ? What changes should I do to remove it ?

    - by mekasperasky
    import javax.swing.*; // For JPanel, etc. import java.awt.*; // For Graphics, etc. import java.awt.geom.*; // For Ellipse2D, etc. public class ShapeExample extends JPanel { private Ellipse2D.Double circle = new Ellipse2D.Double(10, 10, 350, 350); private Rectangle2D.Double square = new Rectangle2D.Double(10, 10, 350, 350); public void paintComponent(Graphics g) { clear(g); Graphics2D g2d = (Graphics2D)g; g2d.fill(circle); g2d.draw(square); } // super.paintComponent clears offscreen pixmap, // since we're using double buffering by default. protected void clear(Graphics g) { super.paintComponent(g); } protected Ellipse2D.Double getCircle() { return(circle); } public static void main(String[] args) { WindowUtilities.openInJFrame(new ShapeExample(), 100, 100); } } The error I am getting is this . symbol : variable WindowUtilities location: class ShapeExample WindowUtilities.openInJFrame(new ShapeExample(), 100, 100); ^ 1 error What is wrong in the code? r

    Read the article

  • Zoom in Java Swing application

    - by Shirky
    Hi there, I am looking for ways to zoom in a Java Swing application. That means that I would like to resize all components in a given JPanel by a given factor as if I would take an screenshot of the UI and just applied an "Image scale" operation. The font size as well as the size of checkboxes, textboxes, cursors etc. has to be adjusted. It is possible to scale a component by applying transforms to a graphics object: protected Graphics getComponentGraphics(Graphics g) { Graphics2D g2d=(Graphics2D)g; g2d.scale(2, 2); return super.getComponentGraphics(g2d); } That works as long as you don't care about self-updating components. If you have a textbox in your application this approach ceases to work since the textbox updates itself every second to show the (blinking) cursor. And since it doesn't use the modified graphics object this time the component appears at the old location. Is there a possibility to change a components graphics object permanently? There is also a problem with the mouse click event handlers. The other possibility would be to resize all child components of the JPanel (setPreferredSize) to a new size. That doesn't work for checkboxes since the displayed picture of the checkbox doesn't change its size. I also thought of programming my own layout manager but I don't think that this will work since layout managers only change the position (and size) of objects but are not able to zoom into checkboxes (see previous paragraph). Or am I wrong with this hypothesis? Do you have any ideas how one could achieve a zoomable Swing GUI without programming custom components? I looked for rotatable user interfaces because the problem seems familiar but I also didn't find any satisfying solution to this problem. Thanks for your help, Chris

    Read the article

  • How should I do 3D games through Java on a mac?

    - by Steven Rogers
    I have been self-teaching myself Java on the mac mostly because the language is cross-platform. Recently, I have been only able to develop 2D games using the Graphics2D class. Now, I want to learn how to make 3D games in Java. I used to model and animate stuff in 3D, so my knowledge of 3-Dimensional stuff is okay. I have spent the last 3 hours using google to look up ways of making 3D games in java. Apparently the best one to use is OpenGL, so i looked up a tutorial on it and i cannot find a tutorial that shows how to (if there is a way) install JOGL on the Mac platform. Should i continue to use Java? How can i make 3D games using Java? What is the best way to make 3D games on a mac?

    Read the article

  • How do I make a dialog box? [on hold]

    - by bill
    By dialog box I mean when player talks to someone, a box shows up with text on it. I haven't found much about this topic online, so I created a basic dialog box: //in dialog box i have only two methods public void createBox(int x, int y, int width, int height, String txt) { this.x = x; this.y = y; this.width = width; this.height = height; this.txt = txt; } //draw dialog box public void draw(Graphics2D g) { if (txt != null) { g.setColor(Color.red); g.drawRect(x,y,width,height); g.setColor(Color.black); g.fillRect(x, y, width, height); g.setColor(Color.white); g.drawString(txt, x + 10, y + 10); } } I wanted to now can I make this better?

    Read the article

  • Plot points instead of lines? JFreeChart PolarChart

    - by billynomates
    Currently, the PolarChart joins all the coordinates with lines creating a polygon. I just want it to plot each point with a dot and NOT join them together. Is this possible? I have tried using translateValueThetaRadiusToJava2D() and Graphics2D to draw circles but it's very clunky and contrived. Any suggestions welcome!

    Read the article

  • why PaintComponent event in Java happen everytime I use its Graphics Event?

    - by Pooya
    Consider this code: public class StateChartPanel extends JPanel { private LightContext LC; public StateChartPanel(LightContext lc){ LC=lc; } public void paintComponent( Graphics G ){ super.paintComponent( G ); LC.DrawStateChart((Graphics2D)G); } } StateChartPanel is a panel to draw something (a state chart). It sends its Graphics object to LC which use it to draw shapes but whenever it draws something the PaintComponent event of StateChartPanel happens again and it causes my application to hang.

    Read the article

  • Resized image degrades in quality.

    - by Venkats
    I resized an image using Java2D Graphics class. But it doesn't look right. BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); g.dispose(); Is it possible to scale an image without introducing artifacts?

    Read the article

  • Is there any way to add a MouseListener to a Graphic object ?

    - by Fahad
    Hi, Is there any way to add a MouseListener to a Graphic object. I have this simple GUI that draw an oval. What I want is handling the event when the user clicks on the oval import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public class Gui2 extends JFrame { JFrame frame = new JFrame(); MyDrawPanel drawpanel = new MyDrawPanel(); public static void main(String[] args) { Gui2 gui = new Gui2(); gui.go(); } public void go() { frame.getContentPane().add(drawpanel); // frame.addMouseListener(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } } class MyDrawPanel extends JComponent implements MouseListener { public void paintComponent(Graphics g) { int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); Color startrandomColor = new Color(red, green, blue); red = (int) (Math.random() * 255); green = (int) (Math.random() * 255); blue = (int) (Math.random() * 255); Color endrandomColor = new Color(red, green, blue); Graphics2D g2d = (Graphics2D) g; this.addMouseListener(this); GradientPaint gradient = new GradientPaint(70, 70, startrandomColor, 150, 150, endrandomColor); g2d.setPaint(gradient); g2d.fillOval(70, 70, 100, 100); } @Override public void mouseClicked(MouseEvent e) { if ((e.getButton() == 1) && (e.getX() >= 70 && e.getX() <= 170 && e.getY() >= 70 && e .getY() <= 170)) { this.repaint(); // JOptionPane.showMessageDialog(null,e.getX()+ "\n" + e.getY()); } } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } } This Works Except it fires when the click is within a virtual box around the oval. Could anyone help me to have it fire when the click is EXACTLY on the oval. Thanks in advance.

    Read the article

  • JFrame does not refresh after deleting an image

    - by dajackal
    Hi! I'm working for the first time with images in a JFrame, and I have some problems. I succeeded in putting an image on my JFrame, and now i want after 2 seconds to remove my image from the JFrame. But after 2 seconds, the image does not disappear, unless I resize the frame or i minimize and after that maximize the frame. Help me if you can. Thanks. Here is the code: File f = new File("2.jpg"); System.out.println("Picture " + f.getAbsolutePath()); BufferedImage image = ImageIO.read(f); MyBufferedImage img = new MyBufferedImage(image); img.resize(400, 300); img.setSize(400, 300); img.setLocation(50, 50); getContentPane().add(img); this.setSize(600, 400); this.setLocationRelativeTo(null); this.setVisible(true); Thread.sleep(2000); System.out.println("2 seconds over"); getContentPane().remove(img); Here is the MyBufferedImage class: public class MyBufferedImage extends JComponent{ private BufferedImage image; private int nPaint; private int avgTime; private long previousSecondsTime; public MyBufferedImage(BufferedImage b) { super(); this.image = b; this.nPaint = 0; this.avgTime = 0; this.previousSecondsTime = System.currentTimeMillis(); } @Override public void paintComponent(Graphics g) { Graphics2D g2D = (Graphics2D) g; g2D.setColor(Color.BLACK); g2D.fillRect(0, 0, this.getWidth(), this.getHeight()); long currentTimeA = System.currentTimeMillis(); //g2D.drawImage(this.image, 320, 0, 0, 240, 0, 0, 640, 480, null); g2D.drawImage(image, 0,0, null); long currentTimeB = System.currentTimeMillis(); this.avgTime += currentTimeB - currentTimeA; this.nPaint++; if (currentTimeB - this.previousSecondsTime > 1000) { System.out.format("Drawn FPS: %d\n", nPaint++); System.out.format("Average time of drawings in the last sec.: %.1f ms\n", (double) this.avgTime / this.nPaint++); this.previousSecondsTime = currentTimeB; this.avgTime = 0; this.nPaint = 0; } } }

    Read the article

  • Drawing performance in Java 6 updates 19,20 versus Java 6 update 3 ?

    - by Pesho
    I'm getting twice the frame rate with the earlier Java 6 u 3, than with the new ones. Very weird. Can anyone give some explanation? On Core 2 Duo 1.83ghz, integrated video (only one core is used) - 1500 (older java) vs 700 fps On Athlon 64 3500+, discrete video - 120 (older java) vs 55 fps The app is a simple game with a moving rectangle. I'm using Graphics2D to draw from a loop.

    Read the article

  • Java monospace draw string

    - by javaAmator
    Hello! How can I draw a String in Java (using Graphics2d) in monospace mode? I have a font that looks like LCD screen font, and I want to draw something like LCD label. I am using Digital 7 Mono font. Do you know where I can find another font that will be monospace and lcd (I wan to type only digitals)?

    Read the article

  • Help with simple frame, and graphics in Java

    - by Crystal
    For hw, I'm trying to create a "CustomButton" that has a frame and in that frame, I draw two triangles, and a square over it. It's supposed to give the user the effect of a button press once it is depressed. So for starters, I am trying to set up the beginning graphics, drawing two triangles, and a square. The problem I have is although I set my frame to 200, 200, and the triangles I have drawn I think to the correct ends of my frame size, when I run the program, I have to extend my window to make the whole artwork, my "CustomButton," viewable. Is that normal? Thanks. Code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CustomButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CustomButtonFrame frame = new CustomButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class CustomButtonFrame extends JFrame { // constructor for CustomButtonFrame public CustomButtonFrame() { setTitle("Custom Button"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); CustomButtonSetup buttonSetup = new CustomButtonSetup(); this.add(buttonSetup); } private static final int DEFAULT_WIDTH = 200; private static final int DEFAULT_HEIGHT = 200; } class CustomButtonSetup extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // first triangle coords int x[] = new int[TRIANGLE_SIDES]; int y[] = new int[TRIANGLE_SIDES]; x[0] = 0; y[0] = 0; x[1] = 200; y[1] = 0; x[2] = 0; y[2] = 200; Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); // second triangle coords x[0] = 0; y[0] = 200; x[1] = 200; y[1] = 200; x[2] = 200; y[2] = 0; Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); g2.drawPolygon(firstTriangle); g2.setColor(Color.WHITE); g2.fillPolygon(firstTriangle); g2.drawPolygon(secondTriangle); g2.setColor(Color.GRAY); g2.fillPolygon(secondTriangle); // draw rectangle 10 pixels off border g2.drawRect(10, 10, 180, 180); } public static final int TRIANGLE_SIDES = 3; }

    Read the article

  • Painting component inside another component

    - by mike_hornbeck
    I've got a task to display painted 'eyes' with menu buttons to change their colors, and background color. Next animate them. But currently I'm stuck at painting, sinc in my JFrame I've Created JPanel containing panels with drawn eyes and buttons. Buttons are rendered properly but my eyes canvas is not shown. I've tried changing paint to paintComponent, setting contentPane differently but still nothing works. import java.awt.*; import javax.swing.*; public class Main extends JFrame { public static void main(String[] args) { final JFrame frame = new JFrame("Eyes"); frame.setPreferredSize(new Dimension(600, 450)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel players = new JPanel(new GridLayout(1, 3)); players.add(new JButton("Eyes color")); players.add(new JButton("Eye pupil")); players.add(new JButton("Background color")); JPanel eyes = new JPanel(); Eyes e = new Eyes(); eyes.add(e); eyes.setPreferredSize(new Dimension(600, 400)); JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); frame.setContentPane(content); content.add(players); content.add(eyes); // frame.getContentPane().add(content); frame.pack(); frame.setVisible(true); } } class Eyes extends JPanel { public Eyes(){ } public void paint(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); BasicStroke bs = new BasicStroke(3.0f); g2d.setBackground(Color.green); g2d.setStroke(bs); g2d.setColor(Color.yellow); g2d.fillOval(50, 150, 200, 200); g2d.fillOval( 350, 150, 200, 200); g2d.setColor(Color.BLACK); g2d.drawOval(49, 149, 201, 201); g2d.drawOval(349, 149, 201, 201); g2d.fillOval(125, 225, 50, 50); g2d.fillOval(425, 225, 50, 50); } } This is what I should get : This is what I have : When I've tried painting it directly in JFrame it works almost perfect, apart of background not being set. Why setBackgroundColor doesn't influence my drawing in any way ?

    Read the article

  • Modifying and Manipulating a interactive bezier curve

    - by rachel
    This is a homework question and I'm having a lot of trouble with it - I've managed to do some of it but still cant finish it - can i Please get some help. Q1. Bezier Curves The following example allows you to interactively control a bezier curve by dragging the control points Cubic.java Replace the call to draw the cubic shape (big.draw(cubic)), by your own function to draw a bezier by the recursive split method. Finally, add the ability to create a longer Bezier curve by adding more control points to create a second curve. Cubic.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.applet.Applet; import java.awt.geom.*; import java.awt.image.BufferedImage; public class Cubic extends JApplet{ static protected JLabel label; CubicPanel cubicPanel; public void init(){ //Initialize the layout. getContentPane().setLayout(new BorderLayout()); cubicPanel = new CubicPanel(); cubicPanel.setBackground(Color.white); getContentPane().add(cubicPanel); label = new JLabel("Drag the points to adjust the curve."); getContentPane().add("South", label); } public static void main(String s[]) { JFrame f = new JFrame("Cubic"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); JApplet applet = new Cubic(); f.getContentPane().add(applet, BorderLayout.CENTER); applet.init(); f.setSize(new Dimension(350,250)); f.setVisible(true); } } class CubicPanel extends JPanel implements MouseListener, MouseMotionListener{ BufferedImage bi; Graphics2D big; int x, y; Rectangle area, startpt, endpt, onept, twopt, rect; CubicCurve2D.Double cubic = new CubicCurve2D.Double(); Point2D.Double start, end, one, two, point; boolean firstTime = true; boolean pressOut = false; public CubicPanel(){ setBackground(Color.white); addMouseMotionListener(this); addMouseListener(this); start = new Point2D.Double(); one = new Point2D.Double(); two = new Point2D.Double(); end = new Point2D.Double(); cubic.setCurve(start, one, two, end); startpt = new Rectangle(0, 0, 8, 8); endpt = new Rectangle(0, 0, 8, 8); onept = new Rectangle(0, 0, 8, 8); twopt = new Rectangle(0, 0, 8, 8); } public void mousePressed(MouseEvent e){ x = e.getX(); y = e.getY(); if(startpt.contains(x, y)){ rect = startpt; point = start; x = startpt.x - e.getX(); y = startpt.y - e.getY(); updateLocation(e); } else if(endpt.contains(x, y)){ rect = endpt; point = end; x = endpt.x - e.getX(); y = endpt.y - e.getY(); updateLocation(e); } else if(onept.contains(x, y)){ rect = onept; point = one; x = onept.x - e.getX(); y = onept.y - e.getY(); updateLocation(e); } else if(twopt.contains(x, y)){ rect = twopt; point = two; x = twopt.x - e.getX(); y = twopt.y - e.getY(); updateLocation(e); } else { pressOut = true; } } public void mouseDragged(MouseEvent e){ if(!pressOut) { updateLocation(e); } } public void mouseReleased(MouseEvent e){ if(startpt.contains(e.getX(), e.getY())){ rect = startpt; point = start; updateLocation(e); } else if(endpt.contains(e.getX(), e.getY())){ rect = endpt; point = end; updateLocation(e); } else if(onept.contains(e.getX(), e.getY())){ rect = onept; point = one; updateLocation(e); } else if(twopt.contains(e.getX(), e.getY())){ rect = twopt; point = two; updateLocation(e); } else { pressOut = false; } } public void mouseMoved(MouseEvent e){} public void mouseClicked(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void updateLocation(MouseEvent e){ rect.setLocation((x + e.getX())-4, (y + e.getY())-4); point.setLocation(x + e.getX(), y + e.getY()); checkPoint(); cubic.setCurve(start, one, two, end); repaint(); } public void paintComponent(Graphics g){ super.paintComponent(g); update(g); } public void update(Graphics g){ Graphics2D g2 = (Graphics2D)g; Dimension dim = getSize(); int w = dim.width; int h = dim.height; if(firstTime){ // Create the offsecren graphics to render to bi = (BufferedImage)createImage(w, h); big = bi.createGraphics(); // Get some initial positions for the control points start.setLocation(w/2-50, h/2); end.setLocation(w/2+50, h/2); one.setLocation((int)(start.x)+25, (int)(start.y)-25); two.setLocation((int)(end.x)-25, (int)(end.y)+25); // Set the initial positions of the squares that are // drawn at the control points startpt.setLocation((int)((start.x)-4), (int)((start.y)-4)); endpt.setLocation((int)((end.x)-4), (int)((end.y)-4)); onept.setLocation((int)((one.x)-4), (int)((one.y)-4)); twopt.setLocation((int)((two.x)-4), (int)((two.y)-4)); // Initialise the CubicCurve2D cubic.setCurve(start, one, two, end); // Set some defaults for Java2D big.setColor(Color.black); big.setStroke(new BasicStroke(5.0f)); big.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); area = new Rectangle(dim); firstTime = false; } // Clears the rectangle that was previously drawn. big.setColor(Color.white); big.clearRect(0, 0, area.width, area.height); // Set the colour for the bezier big.setPaint(Color.black); // Replace the following line by your own function to // draw the bezier specified by start, one, two, end big.draw(cubic); // Draw the control points big.setPaint(Color.red); big.fill(startpt); big.setPaint(Color.magenta); big.fill(endpt); big.setPaint(Color.blue); big.fill(onept); big.setPaint(new Color(0, 200, 0)); big.fill(twopt); // Draws the buffered image to the screen. g2.drawImage(bi, 0, 0, this); } /* Checks if the rectangle is contained within the applet * window. If the rectangle is not contained withing the * applet window, it is redrawn so that it is adjacent to the * edge of the window and just inside the window. */ void checkPoint(){ if (area == null) { return; } if((area.contains(rect)) && (area.contains(point))){ return; } int new_x = rect.x; int new_y = rect.y; double new_px = point.x; double new_py = point.y; if((rect.x+rect.width)>area.getWidth()){ new_x = (int)area.getWidth()-(rect.width-1); } if(point.x > area.getWidth()){ new_px = (int)area.getWidth()-1; } if(rect.x < 0){ new_x = -1; } if(point.x < 0){ new_px = -1; } if((rect.y+rect.width)>area.getHeight()){ new_y = (int)area.getHeight()-(rect.height-1); } if(point.y > area.getHeight()){ new_py = (int)area.getHeight()-1; } if(rect.y < 0){ new_y = -1; } if(point.y < 0){ new_py = -1; } rect.setLocation(new_x, new_y); point.setLocation(new_px, new_py); } }

    Read the article

  • Can't find the source of an exception in Java

    - by Invader Zim
    Basically an exception is being thrown and I can't find the reason. Here is what I get on the console: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 at org.apache.batik.gvt.renderer.StrokingTextPainter.computeTextRuns(Unknown Source) at org.apache.batik.gvt.renderer.StrokingTextPainter.getTextRuns(Unknown Source) at org.apache.batik.gvt.renderer.StrokingTextPainter.getOutline(Unknown Source) at org.apache.batik.gvt.renderer.BasicTextPainter.getGeometryBounds(Unknown Source) at org.apache.batik.gvt.TextNode.getGeometryBounds(Unknown Source) at org.apache.batik.gvt.TextNode.getSensitiveBounds(Unknown Source) at org.apache.batik.gvt.AbstractGraphicsNode.getTransformedSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getTransformedSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getTransformedSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getTransformedSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.getSensitiveBounds(Unknown Source) at org.apache.batik.gvt.CompositeGraphicsNode.nodeHitAt(Unknown Source) at org.apache.batik.gvt.event.AbstractAWTEventDispatcher.dispatchMouseEvent(Unknown Source) at org.apache.batik.gvt.event.AbstractAWTEventDispatcher.dispatchEvent(Unknown Source) at org.apache.batik.gvt.event.AWTEventDispatcher.dispatchEvent(Unknown Source) at org.apache.batik.gvt.event.AbstractAWTEventDispatcher.mouseEntered(Unknown Source) at org.apache.batik.swing.gvt.AbstractJGVTComponent$Listener.dispatchMouseEntered(Unknown Source) at org.apache.batik.swing.svg.AbstractJSVGComponent$SVGListener.dispatchMouseEntered(Unknown Source) at org.apache.batik.swing.gvt.AbstractJGVTComponent$Listener.mouseEntered(Unknown Source) at java.awt.AWTEventMulticaster.mouseEntered(Unknown Source) at java.awt.AWTEventMulticaster.mouseEntered(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.trackMouseEnterExit(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$400(Unknown Source) at java.awt.EventQueue$2.run(Unknown Source) at java.awt.EventQueue$2.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source) at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) It is obviously from a batik lib that I use to paint SVG files, but I made sure that nothing is painted until the document is loaded, ready and showing on screen. When thrown nothing is painted. Another interesting thing is the timing of the throwing. I am unable to find any logical patern, as sometimes it is thrown as soon as I initiate the class and sometimes it needs more then five minutes. In addition to this, as far as I tested there is no single action that calls repaint() that triggers it or rather all do. I am new to Java and all the other exceptions had the class and row number of where they were thrown so I don't know what to do here. Any suggestions would be greatly appreciated. The code is enormous so I'll put just the paint method and if anything additional is needed please say so. @Override public void paint(Graphics g) { if(documentLoaded && showingOnScreen){ try{ rad = (int)(radInit+zoom*faktorRad); //max rad = 20 super.paint(g); Graphics2D g2d = (Graphics2D) g; paintElements(g2d); } catch(NullPointerException nulle){ } } } edit: There is no array in my class so i can't check any index. I think that this exception is thrown from a library I use, but it's a .jar file and I don't know how to open it.

    Read the article

  • zoom a JPanel and all of its components

    - by user253530
    I have a big JPanel which holds many TileMapping objects (TileMapping extends JPanel). I want to zoom the big JPanel and all of its components to be scaled aswell. A TileMapping has an image which of course has to be zoomed as well. here is my TileMapping class public class TileMapping extends JPanel { private double zoom = 1.0; private Mapping mapping; private int height; private int width; private int xCoord; private int yCoord; TileMapping(Mapping m, int w, int h, int x, int y) { super(); mapping = m; height = h; width = w; this.xCoord = x; this.yCoord = y; this.setPreferredSize(new Dimension(w, h)); } public int getXcoord() { return xCoord; } public int getYcoord() { return yCoord; } public Mapping getMapping() { return mapping; } public void setMapping(Mapping m) { mapping = m; } public void originalSize() { zoom = 1; } public void zoomIn() { zoom += 0.2; } public void zoomOut() { zoom -= 0.2; } @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; if (mapping.getImage() != null) { BufferedImage bg = mapping.getImage(); g2d.scale(zoom, zoom); g2d.drawImage(bg, 0, 0, width, height, this); } else { g2d.scale(zoom, zoom); this.setBackground(Color.white); } } } I need to know how i should continue this on the main JPanel which is populated using this code: This is part of a MapWindow class. if you carefully read the code you will understand what i'm talking about. Basically this is a Tile MapEditor and I am simulating a Tile as a JPanel which holds the mapping object (mapping is a binding between an ASCII character and an image) you place. private void populateMapPanel(Map map) { GridBagConstraints c = new GridBagConstraints(); mapPanel.setLayout(new GridBagLayout()); for (int i = 0; i < map.getMapGrid().getRows(); i++) { for (int j = 0; j < map.getMapGrid().getColumns(); j++) { tile = new TileMapping(map.getMapItem(i, j), cellSize, cellSize, i, j); tile.setBorder(new LineBorder(Color.black)); tile.addMouseListener(this); tile.addMouseMotionListener(this); c.gridx = i; c.gridy = j; mapPanel.add(tile, c); } } mapPanel.validate(); mapPanel.repaint(); } I need to know how to do the following: 1. When the user presses Zoom In the mapPanel should zoom in and also all the images in the smaller panels. 2. when the user click and drag over the TileMappings an image should be painted on them and this image should get scaled of course if the mapPanel is zoomed. Pseudo code, ideas, hints, java code ...anything would be helpful. Thank you

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >