I am trying to add an image to a Java canvas. I am using "ImageIO.read" to get the image source. The problem I am facing is that I do not know how to display it on the canvas after reading the image space. Also, I will need to load a different image later (like after pressing the button) how can I do this. The update (canvas.update) method requires a "graphics" parameter instead of an image. Below you will be able to simplify your code (I have left all the codes that are not relevant to issuing a canvas.)
public class MainWindow {public static zero main (string [] args) {EventQueue InvokeLater (public void run) {{window = new mainwindow ()); Window.frame.setVisible (true);} catch (exception e) {e.printStackTrace ();}}}); } / ** * create an application * / public key window () {start (); } / ** * Start the contents of the frame * / start private zeros () {canvas CSSTATUSMAGE = new canvas (); CsStatusImage.setBounds (393, 36, 200, 200); . Add frame.getContentPane () (csStatusImage); Image IMG; Try {iMg = ImageIO.read (new file ("Images / Error_Status_1.png")); CsStatusImage.imageUpdate (IMG, 10, 2, 2, 9, 10); CsStatusImage.checkImage (iMg, (ImageObserver this); CsStatusImage.createImage (ImageProducer IMG); } Hold (IOException e1) {e1.printStackTrace (); }}}}
First of all, you need some way to paint the image . To get this, you can override paint method to java.awt.Canvas class
java.awt.Canvas Can; Import java.awt.Dimension; Import java.awt.Frame; Import java.awt.Graphics; Import java.awt.event.WindowAdapter; Import java.awt.event.WindowEvent; Import java.awt.image.BufferedImage; Import java.io.file; Import java.io.IOException; Import javax.imageio.ImageIO; Import javax.swing.JFrame; Public class test {public static zero main (string [] args) {new test (); } Public Test () {frame frame = new frame ("test"); Frame.addWindowListener (New WindowAdapter () {@ Override Public Wide Window Closing (Window Event E) {System.exit (0);}}); Frame.add (new ImageCanvas ()); Frame.pack (); Frame.setLocationRelativeTo (zero); Frame.setVisible (true); } Public Square ImageCanvas Extended Canvas {Private BufferedImage img; Public ImageCanvas () {try {img = ImageIO.read (New file ("Images / Error_Status_1.png")); } Hold (IOException pre) {ex.printStackTrace (); }} @ Override Public Dimensions getPreferredSize () {back IMG == is empty? New Dimension (200, 200): New Dimension (img.getWidth), img.getHeight ()); } @ Override Public Wide Paint (Graphics G) {SuperPaper (G); If (IMG! = Null) {int x = (getWidth () - img.getWidth ()) / 2; Int y = (getHyight () - img.getHeight ()) / 2; G.drawImage (IMG, X, Y, this); }}}} I have to tell you, the ADT is older than the 15-year old, has been replaced by swing. You may find it difficult to get additional support with this API. If you can, you would be better off using Swing or Java Fx
No comments:
Post a Comment