I am trying to create virtual desktop. I complete successfully.But i am not able to set background image for jdesktoppane. I want to set background image and After adding image also the desktop pane work normally.Is anyone know means just tell me
Thanks
From this thread at coderanch, a possible solution is to paint in the paintComponent method of your subclass of the JDesktopPane (or in your renderer for this class, which could be better).
You can extend JDeskTopPane class with another member as image and then in constructor set the background to that image.
public ExtendedJDesktopPane(Image image) {
super();
this.image = image;
}
protected void paintComponent(Graphics g) {
g.drawImage(scaledImage, 0, 0, this);
}
EDIT:
This is similar to the link provided below by Riduidel.. i just got late writing it.
Related
I'll start off by telling you what Im trying to do if thats OK, as Im not certain the route Im struggling with is even the best way of achieving my ends.
I have a JFrame containing two JPanels. One contains a number of buttons (buttonPanel), the other is, initially, blank (displayPane). When buttons are pressed the stuff shown in displayPanel changes. The way this is working is each press of a button creates a new object that extends JPanel and then adds that to displayPane
So all the above is working fine and dandy (although I freely admit it may not be the best way of doing it) except for one particular case.
In this particular case I need to create a JLayeredPanel and then draw a clipped image on it. JLayeredPanel because I want to draw some stuff on top of it, clipped because I only want to show part of the area (which exact part is passed to the constructor).
Now, the problem Im having is this. The only way I know to draw a clipped image is through g=thingie.getGraphics(), g.setClip(Shape shape), g.drawImage(various). However, all of that relies on being able to get graphics. But because I am assembling the object first there is no graphics object associated with the JLayeredPane (because its not displayed) so getGraphics is returning null and g.setClip() is throwing a Null Pointer Exception.
Obviously I am doing this wrong somehow and somewhere. Any help would be appreciated, sorry if the question is confusing. I tried to include as much detail as possible and now I am a little concerned I've muddied the issue. I'll keep an eye on this and clarify if required.
Warning!: Wrong answer, see below the line
Why don't you just create a new Graphics object, paint on it and then use it with the update() method?
Graphics g = new Graphics();
g.drawStuff();
thingie.update(g);
This showd be correct
As stated on the comments the previous solution was wrong but it can be done with an Double buffer, create a buffered image and draw on it, then override the paint method of the jLayeredPane pane to draw the image.
private void addStuff() {
BufferedImage bi =
new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);
Graphics bufferedGraphics = bi.getGraphics();
//Paint stuff
bufferedGraphics.drawLine(0, 0, 50, 50);
javax.swing.JLayeredPane layered;
layered = new JLayeredPane() {
#Override
public void paint(Graphics g) {
g.drawImage(bi, 0, 0, null);
}
};
this.add(layered);
this.validate();
this.repaint();
}
I created a class that extends a JFrame and added a JPanel inside it, but the paintComponents() method doesn't draw anything on the JPanel. Heres the code for the paintComponents(), I chose to use double image buffering.
public void paintComponents(Graphics graphics) {
panel.paintComponents(graphics);
bufferedImage = createImage(sizeX, sizeY);
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
for (ImageData myImage : imageData) {
g.drawImage(myImage.getImage(), myImage.getX(), myImage.getY(), null);
}
graphics.drawImage(bufferedImage, 0, 0, null);
}
Is there anything wrong with this? Btw, I tried paint() and it worked but I dont think it's the proper way to do this.
Thanks for your time. :)
Do not extend a top level component such as a JFrame. Instead keep an instance of a frame, and add a panel to that. All custom painting or addition of components is done in the panel.
When doing custom painting in a panel, do it in the paintComponent method (not paintComponents do not override that).
Other tips
Remember to call super.paintComponent(g);. This is important to ensure that borders and padding etc. are accounted for.
Swap null for this. Every JComponent is an ImageObserver.
please note that JFrame is NOT a JComponent! In fact, the paintComponents(Graphics) method is NEVER called. A fix would be subclassing JPanel and adding your subclassed panel to the frame as the content pane. In the panel override the paintComponents(Graphics) method.
Using JRE 5.0.0, simulator device is an 8520.
On a screen I am using a FlowFieldManager(Manager.VERTICAL_SCROLL) and adding Fields to it to show data.
When I do
this.flowManager = new FlowFieldManager(Manager.VERTICAL_SCROLL);
Field field = new Field()
{
protected void paint(Graphics graphics)
{
graphics.drawTest("Test", 0, 0);
}
protected void layout(int width, int height)
{
this.setExtend(300, 300); // just testing
}
}
this.flowManager.add(field);
The screen renders correctly and 'Test' appears on the screen.
If, on the other hand, I try and abstract this into a class called CustomField with the same properties and add it to the flow manager the render will not happen. Debugging shows that the device enters into the Object, into the layout function, but not the paint function.
I can't figure out why the paint function is not called when I extend Field. The 4.5 API says that layout and paint are the only functions that I really need to extend. (getPreferredWidth and getPreferredHeight will be used to calculate screen sizes etc.)
Thanks in advance.
If at the time of paint a Field is outside the clipping region, it will not be instructed to paint. That's really the only thing that I can see wrong with this.
So make sure you don't have this Field scrolled off the screen somewhere.
I'm trying to write an application where I want to add different pictures on a Jpanel. Everything works fine except for the JPG format which displays very bad quality images.
This is how I do the drawing :
class draw extends Canvas
{
Dimension canvasSize = new Dimension(400, 400);
String fileName;
public void paint(Graphics g)
{
if(this.fileName!=null)
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image img = toolkit.getImage(fileName);
g.drawImage(img, 0, 0, this);
}
}
public void setFileName(String name)
{
this.fileName=name;
}
public Dimension getMinimumSize()
{
return canvasSize;
}
public Dimension getPreferredSize()
{
return canvasSize;
}
}
Is there a way such that JPG format is covered ?
This is probably because you're stretching (or compressing) the image to the size of the canvas. JPEG images don't look great when you scale them, particularly if you're scaling up. Try an image that's the same size as (or close to) your canvas. You can also get the height and width of the JPEG from the Image class and display it in its original dimensions. Sun's Drawing an Image tutorial shows how to do this.
The posted code indicates that the OP is painting the image at its original size. So my comments about the code:
a) You say you want to add the image to a JPanel, yet for some reason you are extending Canvas. Stick with Swing components. Then if you need to do custom painting you would override the paintComponent() method NOT the paint method.
b) When you do use custom painting, you should never read the image in the painting method. This method can be called numerous times. It possible that the image has not been completely read into memory. I know Swing will automatically repaint as more of the image is read, I'm not sure how the AWT Canvas works.
c) Also, when overriding paint methods don't forget to invoke super.paint(), super.paintComponent() or you may get unexpected results.
d) However, based on the posted code there is no need to even do custom painting (since you are drawing the image at its actual size). Just create an ImageIcon from the image and add the Icon to a JLabel. Then you just add the label to the GUI.
I suggest you read the section from the Swing tutorial on How to Use Icons. If the image quality is poor then the problem is probably with your image because now you are using standard code, not custom code.
I am developing a simple platform game using Java using BlueJ as the IDE. Right now I have player/enemy sprites, platforms and other items in the game drawn using polygons and simple shapes. Eventually I hope to replace them with actual images.
For now I would like to know what is the simplest solution to setting an image (either URL or from local source) as the 'background' of my game window/canvas?
I would appreciate it if it isn't something long or complex as my programming skills aren't very good and I want to keep my program as simple as possible. Kindly provide example codes with comments to elaborate on their function, and also if it's in its own class, how to call on relevant methods used by it on other classes.
Thank you very much.
The answer will vary slightly depending on whether the application or applet is using AWT or Swing.
(Basically, classes that start with J such as JApplet and JFrame are Swing, and Applet and Frame are AWT.)
In either case, the basic steps would be:
Draw or load an image into a Image object.
Draw the background image in the painting event of the Component you want to draw the background in.
Step 1. Loading the image can be either by using the Toolkit class or by the ImageIO class.
The Toolkit.createImage method can be used to load an Image from a location specified in a String:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
Similarly, ImageIO can be used:
Image img = ImageIO.read(new File("background.jpg");
Step 2. The painting method for the Component that should get the background will need to be overridden and paint the Image onto the component.
For AWT, the method to override is the paint method, and use the drawImage method of the Graphics object that is handed into the paint method:
public void paint(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
For Swing, the method to override is the paintComponent method of the JComponent, and draw the Image as with what was done in AWT.
public void paintComponent(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
Simple Component Example
Here's a Panel which loads an image file when instantiated, and draws that image on itself:
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel()
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage("background.jpg");
}
public void paint(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
}
}
For more information on painting:
Painting in AWT and Swing
Lesson: Performing Custom Painting from The Java Tutorials may be of help.
Firstly create a new class that extends the WorldView class. I called my new class Background. So in this new class import all the Java packages you will need in order to override the paintBackground method. This should be:
import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;
Next after the class name make sure that it says extends WorldView. Something like this:
public class Background extends WorldView
Then declare the variables game of type Game and an image variable of type Image something like this:
private Game game;
private Image image;
Then in the constructor of this class make sure the game of type Game is in the signature of the constructor and that in the call to super you will have to initialise the WorldView, initialise the game and initialise the image variables, something like this:
super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();
Then you just override the paintBackground method in exactly the same way as you did when overriding the paint method in the Player class. Just like this:
public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}
Now finally you have to declare a class level reference to the new class you just made in the Game class and initialise this in the Game constructor, something like this:
private Background image;
And in the Game constructor:
image = new Background(this);
Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame has been declared:
frame.add(image);
Make sure you add this code just before frame.pack();.
Also make sure you use a background image that isn't too big!
Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.
Or try this ;)
try {
this.setContentPane(
new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};
The Path is the only thing you really have to worry about if you are really new to Java.
You need to drag your image into the main project file, and it will show up at the very bottom of the list.
Then the file path is pretty straight forward. This code goes into the constructor for the class.
img = Toolkit.getDefaultToolkit().createImage("/home/ben/workspace/CS2/Background.jpg");
CS2 is the name of my project, and everything before that is leading to the workspace.
<script>
function SetBack(dir) {
document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>