Before I start know this: I am extremely new to Java and programming. How would I properly draw the "grass.jpg" to the screen?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import java.util.Random;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Game extends Canvas {
private static int Height = 300, Width = 600; //25x50
private Random generator = new Random();
private String[][] TerrainList = new String[12][12];
public void GameSetup() {
JFrame container = new JFrame("CARSSémon");
// get hold the content of the frame and set up the resolution of the game
JPanel panel = (JPanel) container.getContentPane();
panel.setPreferredSize(new Dimension(Width,Height));
//panel.setLayout(null);
//setBounds(0,0,800,600);
//panel.add(this);
// finally make the window visible
container.pack();
container.setResizable(false);
container.setVisible(true);
container.setLocationRelativeTo(null); //Centers screen
container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
PrepareTerrain();
PreparePlayer();
}
public void PrepareTerrain() {
for (int a=0; a<=11; a++){
for (int b=0; b<=11; b++){
TerrainList[a][b]="grass"; //Sets defult terrain of grass
}
}
int BushLocationx = generator.nextInt(12);
int BushLocationy = generator.nextInt(12);
BushCheck(BushLocationx,BushLocationy); //Checks to see if it can make bushs at the location
}
#Override
public void paint(Graphics g) {
super.paint(g);
// Draw an Image object
Image grass = new ImageIcon("grass.jpg").getImage();
Image bushes = Toolkit.getDefaultToolkit().getImage("bushes.jpg");
g.setColor(Color.BLACK);
g.drawImage(grass, 0, 0, null);
g.drawImage(grass, 0, 50, null);
g.drawImage(grass, 50, 0, null);
g.drawImage(grass, 200, 200, null);
}
public void DrawTerrain() {
for (int r=0; r<=11; r++){
for (int c=0; c<=11; c++){
}
}
}
private void BushCheck(int x, int y){
}
public void PreparePlayer() {
}
public static void main(String[] args) {
Game G =new Game();
G.GameSetup();
}
}
Now I obviously realize that this program has basically nothing implemented but I figured what's the point of starting to implement things if I could never even display any pictures?
My problem is that I can not figure out why the .jpgs aren't being displayed. Shouldn't the paint(); method be called when the JFrame and JPanel are created? The code is pretty messy, but I figured it would be best to include all of it.
In case this matters, this is eventually going to be a Pokemon like game, where the the run window is made up of many 16x16 pixel squares, that a player could move around on. Before starting any of that I wanted to experiment with outputting some images at random places. I've been reading similar questions and looking at examples, I just read a section of Java text on graphics but could only find information on loading images, not displaying through paint. If anyone could help by even pointing me in the right way, it would be greatly appreciated.
(I realize that I will most likely completely need to restart, and are going about things completely wrong but anything you could do would help.)
I just read a huge section of Java text on graphics but could only find information on loading images, not displaying through paint.
For a Pokemon style game, I don't think using JLabel for each icon/image would provide any benefit. Instead:
Create a BufferedImage of the desired size of the game area.
Get Image instances for each of the smaller icons that you might need to paint (characters, elements in the terrain etc.) & paint them to the Graphics instance of the main BufferedImage1.
To display the main 'game' image there are two good options:
Add the main image to a JLabel and add it to a JPanel, call label.repaint().
Paint the game image directly to the Graphics instance supplied to the paintComponent() method of a JComponent.
For the last part, I would recommend option 1.
1. E.G.
public void gameRenderLoop() {
Graphics2D g2 = gameImage.createGraphics();
g2.drawImage(playerImage, 22, 35, this);
...
g2.dispose();
}
Examples of dealing with BufferedImage & Graphics
Very simple example of painting an image.
More complicated example dealing with text & clips.
A slightly different tack (extending a JLabel) showing image painting with transparency.
Don't reinvent the wheel. Use a JLabel with an ImageIcon to paint your image for you. Just add it to a JPanel and you're all set.
Related
im trying to insert a gif as a background for my app. I cut all frames and renamed them f1/f2/f3/f4/f5/f6/..... I would use a timer to change the frame so it looks like an animation.
There is a total of 42 frames, so f42.png is the last frame. The code seems to be fine, but there is no result. Any help?
Global variables:
private String backgroundFile;
public JPanel backgroundPanel, areaImage;
private BufferedImage background;
private javax.swing.Timer timerBackground;
Constructor where the Timer is initialized:
public Game()
{
entryWindow();
this.setLayout(null);
timerBackground = new javax.swing.Timer(100,this);
timerBackground.stop();
}
Animation method code:
private void backgroundAnimation()
{
backgroundFile = "f"+backgroundNum+".png";
try{
background=ImageIO.read(new File(backgroundFile));
}
catch(IOException e)
{
}
backgroundPanel = new JPanel()
{
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, 1100,800,null);
}
};
backgroundPanel.setBackground(Color.BLACK);
backgroundPanel.setBounds(0, 0, 1100, 800);
if (backgroundNum>42)backgroundNum++;
else backgroundNum=1;
add(backgroundPanel);
backgroundPanel.setVisible(true);
}
Action Listener for timer:
if (ae.getSource() == timerBackground)
{
backgroundAnimation();
}
In order to show JPanel, you need to add it to something like JFrame with an BorderLayout for instance, then you need to show the JFrame. JFrame is a application window, the JPanel can be only added and drawn on Window, it can't be viewed without something on which it can draw (like app Window). Beside that you don't need to create new JPanel each time the animation changes, just make a setter for the current image to show, and after assigning the image call repaint(), the ImagePanel could be like this:
public class ImagePanel extends JPanel {
private volatile BufferedImage image;
public void showImage(BufferedImage image) {
this.image=image;
repaint();
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0,0,getWidth(),getHeight(),null);
}
}
add it to your JFrame at application start, also set the LayoutManager of JFrame to BorderLayout preferably, because without that your panel will have size(0,0) since you didn't set it, and it could be one of reasons why you don't see it (you can't see something which is 0 pixel in size, can you?).
Then in your timer just call the ImagePanel method public void showImage(BufferedImage image) with the image to show. If that's don't solve your problem, then post your entire code. As without that i'm just guessing, but those are common problems, so there's big chance you hit something from this.
I can see a few issues here
1. Assuming your Game class is extending JFrame, You need to add the JPanel to the ContentPane of the JFrame. Use one of the approaches setContentPane(backgroundPanel); or getContentPane().add(backgroundPanel)
You are not using a LayoutManager. So either use a LayoutManager or set the Size of the 'JFrame' and 'JPanel' explicitly using setBounds() method. I would recommend using a LayoutManager.
The JPanel or any Component for that matter does not automatically refresh itself. Once you change the image, you need to call repaint() on your JPanel.
You dont need to create a new JPanel every time you change the image. Just extend the JPanel and override the paintComponent()like you have done. Use the Timer to change the image of that single instance and call repaint() with every change.
The complete example, with hat output you are seeing will help understand the problem better and give you a solution. Please see How to create a Minimal, Complete, and Verifiable example
There are multiple problems here, but first let me answer your question:
You are creating a new JPanel and add it to the Game on every run through. That is wrong, since you add infinite panels to your Game
Also in your if/else you have a wrong condition. You increase the iterator when it is greater 42. You probably mean lesser than 42.
Here is how I would do it:
public class BackgroundPanel extends JPanel {
private int currImage = 0;
private BufferedImage[] backgroundImages;
public BackgroundPanel() {
int numberOfImages = 42;
backgroundImages = new BufferedImage[42];
for(int i = 1; i <= numberOfImages; i++) {
String backgroundFile = "f" + i + ".png";
backgroundImages[i] = ImageIO.read(new File(backgroundFile));
}
}
public void nextImage() {
/*if(currImage <= 42) currImage++;
else currImage = 1;*/
if(currImage++ > 42) currImage = 1;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImages[currImage], 0, 0, getWidth(), getHeight(), null);
}
}
You need to add this panel ONCE to your "Game":
//Somewhere in your Game
private BackgroundPanel backgroundPanel;
...
...
public Game() {
entryWindow();
this.setLayout(null);
backgroundPanel = new backgroundPanel();
backgroundPanel.setSize(getWidth(), getHeight());
add(backgroundPanel);
timerBackground = new javax.swing.Timer(100,this);
timerBackground.stop();
}
Your timer:
if (ae.getSource() == timerBackground) {
backgroundPanel.nextImage();
}
It's easier to put the background on JLabel. It requires only 3 lines of code and works fine! :) Hope it helps for anyone that will have the same problem :)
All you have to do is copy this code, change the name (i have all pictures in a folder called "Images") with any kind of Java supported picture/video/.... (just change the suffix .gif to your file format) and at last the size. Good luck! :)
public JLabel backgroundGIF;
backgroundGIF = new JLabel(new ImageIcon(getClass().getResource("Images/background.gif")));
backgroundGIF.setBounds(0,0,1100,800);
add(backgroundGIF);
Sorry about my English, and my ignorance in programming, its because I'm new at this , and I'm having problem with Buttons and JFrame, please help me ;)
I'll post the print of the problem, and the codes of my the two classes I have so far, Game and Menu, hope you guys can solve it, I want the buttons to paint inside the gray panel.
Thanks.
Print of my Problem
Print
(GAME CLASS)
package br.com.lexo.dagame;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import br.com.lexo.dagame.menu.Menu;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private static int width = 300;
private static int height = width / 16 * 9;
private static int scale = 3;
private static String title = "Da Game";
private Thread thread;
public JFrame janela;
private Menu menu;
private boolean running = false;
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
janela = new JFrame();
menu = new Menu(janela, this);
}
private synchronized void start() {
if (running) return;
running = true;
thread = new Thread(this, "Thread_01");
thread.start();
}
private synchronized void stop() {
if (!running) return;
running = false;
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public void update() {
}
public void run() {
while (running){
render();
update();
}
stop();
}
public static void main(String[] args) {
Game game = new Game();
game.janela.add(game);
game.janela.setTitle(title);
game.janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.janela.pack();
game.janela.setLocationRelativeTo(null);
game.janela.setResizable(false);
game.janela.setVisible(true);
game.start();
}
}
(MENU CLASS)
package br.com.lexo.dagame.menu;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import br.com.lexo.dagame.Game;
public class Menu extends Canvas {
private static final long serialVersionUID = 1L;
public boolean inMenu = false;
JButton startGame = new JButton("Começar Jogo");
JButton exitGame = new JButton("Sair do Jogo");
JButton howToPlay = new JButton("Como Jogar");
private Game game;
public Menu(JFrame janela, Game game){
this.inMenu = true;
this.game = game;
game.janela.setLayout(new GridBagLayout());
game.janela.add(startGame);
game.janela.add(exitGame);
game.janela.add(howToPlay);
howToPlay.setEnabled(false);
}
#Override
public void paint(Graphics g) {
super.paint(g);
}
}
I don't know what are you trying to accomplish but you are not adding the components correctly:
Look at:
game.janela.setLayout(new GridBagLayout());
game.janela.add(startGame);
game.janela.add(exitGame);
game.janela.add(howToPlay);
This is incorrect, the add method has two arguments, like this: container.add(component, constraints); your error is not specifying the constraints. The constraints contains all the details to know where in the panel you want to add that component.
For each LayoutManager the Object constraints is diferent. For the GridBagLayout the constraints is a GridBagConstraints object.
However GridBagLayout is a the most difficult layout to use and you don't really need it. I recommend you to look at this visual guide pick a layout and learn it properly. The tutorial for each LayoutManager explains what do you need to put in the constraints parameter.
The call container.add(component) exists because sometimes the LayoutManager does not need extra information (like the BoxLayout), in the other cases it just uses the "default" constraints for the LayoutManager in use, which may not be what you need.
For example the line in your main:
game.janela.add(game);
Is correct, but what it actually does is calling game.janela.add(game, defaultConstraints); where defaultConstraints is the default constraints value for the LayoutManager of the JFrame janela. Because you didn't explicitely specify a layout for the frame it is using the default layout for JFrames: BorderLayout, and the default constraints for the BorderLayout is the constant BorderLayout.CENTER.
So what that line actually does is:
game.janela.add(game, BorderLayout.CENTER);
Which incidentally is what you wanted to do.
To summarize:
Most calls to add must have two parameters: the component and the constraints. Each LayoutManager uses different constraints. You must be aware of what means to not specify the constraints for your LayoutManager. Do not start learning about how to properly use LayoutMangers with the GridBagLayout it's much more complex.
A quick way to somehow paint components to a graphics object is calling the paint method of component class. So in your render method:
g.fillRect(0, 0, getWidth(), getHeight());
menu.startGame.paint(g);
...
But as you'll soon see that everything is painted on the top left as components are laid out as said in the other answer and to get everything working to how you want them to work is a bit more complicated.
Now the following advice is based on my limited knowledge and was quickly put together so there are probably better ways.
About the menu class:
You are extending java.awt.Canvas when I think it would be best to extend a container like javax.swing.JPanel as you want it (I assume) to hold those 3 buttons.
Next would be to set the appropriate layout for this application, which would be null. So instead of:
game.janela.setLayout(new GridBagLayout());
it would now be:
setLayout(null);
This is because you want components (which are those buttons) to be paint on top of another component which is the Game class that extends Canvas and null allows you to do that.
Because the layout is now null, you must specify the bounds of the components which are the x and y coordinates alone with the width and the height otherwise everything will just be 0, 0, 0, 0 and nothing would show up.
So in the Game's constructor
setBounds(0, 0, width * scale, height * scale);
and janela.setPreferredSize(size); instead of setPreferredSize(size);
Back in the Menu class you will have to set the bounds of the buttons like so:
Dimensions sgSize = startGame.getPreferredSize();
startGame.setBounds(50, 50, sgSize.width, sgSize.height);
I am using preferred size to get the optimal width and height of the button that was set in the buttons UI (I think).
and add them to the Menu which is now a JPanel instead of adding them to the JFrame(janela). (add(startGame);) Also, don't forget to add the game to the menu panel.
and it should work like so:
(http://i.imgur.com/7cAopvC.png) (image)
Alternatively you could make your own widget toolkit or custom layout, but I wouldn't recommend that. I had this same problem last year but ended up moving to OpenGL but anyway, I hope this has helped :)
I want my program to display the canvas that is repainted once at the start and then whenever a change is made afterwards. I thought I had everything coded correctly, but for some reason nothing that is painted onto the canvas actually shows (I know it's repainting, I tested that).
Here are the code segments:
public TileMapCreator()
{
currentView = new BufferedImage(640, 640, BufferedImage.TYPE_INT_ARGB);
currentView.getGraphics().setFont(new Font("Arial", Font.BOLD, 100));
currentView.getGraphics().drawString("No Map Yet Open", currentView.getWidth()/2, currentView.getHeight()/2);
this.setJMenuBar(createMenuBar());
this.setContentPane(createMapPanel());
}
private JPanel createMapPanel()
{
JPanel p = new JPanel();
p.add(setUpCanvas());
p.setVisible(true);
return p;
}
private Canvas setUpCanvas()
{
mapCanvas = new Canvas(){
private static final long serialVersionUID = 1L;
public void repaint()
{
mapCanvas.getGraphics().drawImage(currentView, 0, 0, this);
}
};
mapCanvas.setIgnoreRepaint(true);
Dimension size = new Dimension(currentView.getWidth(), currentView.getHeight());
mapCanvas.setSize(size);
mapCanvas.setPreferredSize(size);
mapCanvas.setMaximumSize(size);
mapCanvas.setMinimumSize(size);
mapCanvas.setFocusable(true);
mapCanvas.addMouseListener(this);
mapCanvas.addMouseMotionListener(this);
mapCanvas.setVisible(true);
return mapCanvas;
}
Currently the area where the canvas should be painting is just the regular grey color of the Java GUI. Thanks for your help!
You appear to be mixing Swing with AWT components, and drawing in a very strange way, one that I've honestly never seen before (and I've seen a lot). Why not simply do your drawings in the paintComponent(Graphics g) method of a JPanel using the Graphics object given by the JVM, like you'll find in the Swing graphics tutorials and 98% of the Swing graphics answers on this site? Also for my money, I'd avoid using Canvas or trying to mix heavy and light weight components together. Stick with Swing all the way, and things should go more smoothly.
I'd be happy to give you more specific advice and perhaps some if you could create and post a minimal example program. Please have a look at the link and let us know if you need more information.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class TestImagePanel extends JPanel {
private static final int BI_WIDTH = 640;
BufferedImage currentView = new BufferedImage(BI_WIDTH, BI_WIDTH, BufferedImage.TYPE_INT_ARGB);
public TestImagePanel() {
Graphics g = currentView.getGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.BOLD, 60));
g.drawString("No Map Yet Open", 20, currentView.getHeight()/2);
g.dispose();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (currentView != null) {
g.drawImage(currentView, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (currentView != null) {
return new Dimension(BI_WIDTH, BI_WIDTH);
}
return super.getPreferredSize();
}
private static void createAndShowGui() {
TestImagePanel mainPanel = new TestImagePanel();
JFrame frame = new JFrame("TestImagePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I've found the Swing tutorials to be a great asset, and bet you would too. Please have a look at them.
Edit
You ask:
Hmm, so apparently getting the graphics object of my buffered image twice did not result in anything actually being painted... I had to get the graphics object, assign it to a variable, and then paint.
I wouldn't say that. I'd say that your way of getting the Graphics object should work the same as mine, but yours is not safe since the Graphics objects obtained in this way cannot be disposed of, and you risk running out of resources. I think that your image didn't show up due to your very convoluted and unusual way of trying to display your image. You override repaint(), put some weird code inside of it, tell the JVM to ignore repaint calls, never call the repaint super method inside of your override, so that repaint does in fact nothing. I have to wonder -- where did you get this code? Was it from a tutorial? If so, please share the link here. And never get advice from that site again.
As you already know everything I started writing little game about space.
"Not a bad start" - https://stackoverflow.com/questions/19818655/simulation-of-spaceplanets-and-stars :D
I wrote a little plan of the work, and the first point in that it is' Random generation of stars.
You could say, easier use the random.
Random random = new Random();
int x = random.nextInt(getWidth()*2);
int y = random.nextInt(getHeight()*2);
g.drawImage(Image,x,y,4,4,this);
But it does not work (
And it is not working because the pictures "jump" on the screen.
As to the video: https://www.youtube.com/watch?v=EELo_-eh3fA
So how do you randomly bring the stars? (Star is a small picture or a white square)
That's all the code:
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import java.io.IOException;
public class Game extends JComponent {
public Game() {
try {
image = ImageIO.read(getClass().getResource("star.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
repaint();
Random random = new Random();
int x = random.nextInt(getWidth()*2);
int y = random.nextInt(getHeight()*2);
g.drawImage(Image,x,y,4,4,this);
}
public static void main(String[] args) {
JFrame frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.add(new Game());
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.addMouseListener(mos);
frame.addMouseMotionListener(mos);
}
}
Here's a code does not work (
Pictures jump again.
public void paintComponent(Graphics g) {
super.paintComponent(g);
repaint();
Random random = new Random();
int x = random.nextInt(getWidth()*2);
int y = random.nextInt(getHeight()*2);
g.drawImage(kor,x,y,10,10,this);
}
#camickr, You said to remove repaint(); but without it I do not get a picture
Custom painting is done by overriding the paintComponent() method not the paint() method.
Never invoke repaint() in a painting method. This will cause an infinite loop.
How to fix the picture? that they did not jump.
Basically the location needs to be determined outside of the painting method.
Maybe you can start with Custom Painting Approaches to get the idea of painting multiple objects on a panel. I would suggest the first approach of adding objects to a List. So you would add multiple objects to the list, but each object would be given a random location.
You said to remove repaint(); but without it I do not get a picture
Did you take the time to look at the link I gave you? The examples show you when to do a repaint().
So my friend and I are making a very very basic game for fun, its going to be a top down (about 45 degree angle) where there is a lumberjack chopping down trees. Very basic and kinda lame I'm aware but we are just getting into semi-advanced java.
To start we decided we needed sprites for trees but we realized that no matter what it would be a rectangle with white pixels all around the tree, but that would cut out part of the background image. So we wanted to take every pixel that was white (whitespace/negative space), then make those pixels transparent. To do this we looked at a ton of codes and the one we saw the most was the code below, it worked but I don't quite understand it.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class simpleFrame extends JFrame {
JPanel mainPanel = new JPanel() {
ImageIcon originalIcon = new ImageIcon("image.png");
ImageFilter filter = new RGBImageFilter() {
int transparentColor = Color.white.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == transparentColor) {
return 0x00FFFFFF & rgb;
} else {
return rgb;
}
}
};
ImageProducer filteredImgProd = new FilteredImageSource(originalIcon.getImage().getSource(), filter);
Image transparentImg = Toolkit.getDefaultToolkit().createImage(filteredImgProd);
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getSize().width, getSize().height);
g.drawImage(transparentImg, 140, 10, this);
}
};
public simpleFrame() {
super("Transparency Example");
JPanel content = (JPanel)getContentPane();
mainPanel.setBackground(Color.black);
content.add("Center", mainPanel);
}
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
simpleFrame c = new simpleFrame();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setSize(700,700);
c.setVisible(true);
}
});
}
}
So what we don't exactly understand is why there are brackets after the declaration of the JPanel in the 6th line then I have no idea how the lines 6-16. Like in between the brackets, then the close bracket has a semi colon after it. I can't figure out how that works, every command line set aside but the structure of declaring the JPanel, JPanel mainPanel = new JPanel() { };
Im trying to implement this so I can import an image to my JPanel class, then make all the negative space transparent, then paint it. I just cant seem to understand the structure of the program and how I could implement it into a class.
My code is the following:
public class Frame extends JPanel {
/*
* This is the JPanel in which I want to add the transparent image to a JPanel
* then add the JPanel object,"Frame", above in a JFrame declared in my
* class above
*/
public Frame() {
JPanel jp = new JPanel();
jp.setSize(300,300);
jp.setVisible(true);
circle = new BufferedImage();
try {circle = ImageIO.read(new File("circle.PNG"));}
catch (IOException ex) {}
}
public void paintComponents(Graphics g) {
super.paintComponents(g);
g.drawImage(circle,0,0,300,300, null);
g.drawRect(50, 50, 50, 50);
}
}
It is only a test code to import an image, make it transparent, and then paint it on a JPanel. We are just trying to understand the best way to do this and the code that I found (the first code block) seems to do the job very well but we can't figure out the best way to implement it to our code.
Thanks in Advance,
Robbie and
Nick
What the code in your example block with the JPanel is doing is declaring the JPanel's class right there--immediately--when it is instantiated. It's sort of coding shorthand. Doing that, they don't have to write a formal new, named class for the JPanel in a new .java file: the entire definition of the class is right there. If you look at it as a Java class definition, I'm sure it will make more sense.
If you take all the stuff out and put it in a formal Java class, inherited from JPanel, it should work. The formal name for what they're doing is called implementing an anonymous class (http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html). I normally don't do it, because it makes the code much harder to read, but it's permitted.
HTH