I have reduced my codes to such a simple function: to show a picture on a window. But why does the picture not show up however I tried? I create a JFrame, and then created a JPanel which is expected to show the picture. Then add the panel to the frame. By the way, I imported the picture and double clicked it to get the url.
import java.awt.*;
import javax.swing.*;
import com.sun.prism.Graphics;
public class GUI {
JFrame frame=new JFrame("My game");
JPanel gamePanel=new JPanel();
public static void main(String[] args){
GUI gui=new GUI();
gui.go();
}
public void go(){
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Background backPic=new Background();
backPic.setVisible(true);
frame.getContentPane().add(backPic);
JPanel contentPane=(JPanel) frame.getContentPane();
contentPane.setOpaque(false);
frame.setVisible(true);
}
class Background extends JPanel{
public void paintComponent(Graphics g){
ImageIcon backgroundIcon=new ImageIcon("file:///E:/eclipse/EL/backgroundPicture.jpg");
Image backgroundPic=backgroundIcon.getImage();
Graphics2D g2D=(Graphics2D) g;
g2D.drawImage(backgroundPic,0,0,this);
}
}
}
It's because you've imported com.sun.prism.Graphics. It should be java.awt.Graphics.
I would also get rid of the "file:///" bit from your path. And you also probably don't want to be loading the image on each paint event. Here's a better version of the Background class;-
class Background extends JPanel {
Image backgroundPic;
public Background() {
ImageIcon backgroundIcon=new ImageIcon("E:/eclipse/EL/backgroundPicture.jpg");
backgroundPic=backgroundIcon.getImage();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D=(Graphics2D) g;
g2D.drawImage(backgroundPic,10,10,this);
}
}
Related
I'm trying to create a super simple component, and it's not appearing.
Component class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Player extends JComponent{
public Player()
{
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillRect(40,40,150,150);
}
}
Panel Class im adding it to:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.JPanel;
public class Game extends JPanel{
public Game()
{
this.setBackground(Color.yellow);
this.setPreferredSize(new Dimension(500,500));
Player p = new Player();
this.add(p);
}
}
And the JFrame:
import javax.swing.JFrame;
public class Launcher {
public static void main(String[] args) {
JFrame frame = new JFrame("Key Collector Demo");
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
}
The only thing showing up is the yellow background.
JFrame and JPanel are working fine; this problem consistently happens to me when building jcomponents. What am I missing?
Any help would be greatly appreciated!
Coordinates that you are using to draw a component are defined in the space of that component.
If you do this:
public void paint(Graphics g)
{
g.setColor(Color.green);
System.out.println(getSize());
g.fillRect(40,40,150,150);
}
You will see that at the moment it is attempted to get drawn its size is 1x1. So drawing it from 40,40 obviously takes it out of the visible area of the component.
Now change the method to:
public void paint(Graphics g)
{
g.setColor(Color.green);
System.out.println(getSize());
setSize(45, 45);
g.fillRect(40,40,150,150);
}
Now you can see small filled rectangle. This is because you forced the size to be 45x45 and now there are 5 pixels to show in the space of the component while the remaining part is still out of the area.
Do not assume the Player panel to have a fixed size.
For a first test your paint method could look like this:
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(0,0,getWidth(),getHeight());
}
The next problem is that the component probably has no size or position. Add a LayoutManager to your panel and add the component:
public Game() {
this.setBackground(Color.yellow);
this.setPreferredSize(new Dimension(500,500));
this.setLayout(new BorderLayout());
Player p = new Player();
this.add(p, BorderLayout.CENTER);
}
With that, your player might take the full space and you see green instead of yellow. Play around with the LayoutManager and the player's preferredSize.
I have a custom JLayeredPane, and I am repainting it in my game loop. There are two custom JPanels added into the JLayeredPane. These are foreground and background JPanels. How do I successfully only draw my background JPanel once, (And repaint when window is re-sized or any other reason) to reduce impact on system resources, while continuing to update my foreground JPanel constantly.
To re-iterate, I dont want to constantly repaint the background JPanel in a loop. I want to repaint it only when it is nessessary, as the background does not change. and is large.
In my attempt to do this, I have only drawn the background once. However. the background JPanel is simply not visible. while the foreground JPanel updates as normal. It is almost as if the foreground JPanel paints ontop of the background JPanel, even though I have both of the JPanels set to setOpaque(false)
I have made a mvce which shows my attempt at only drawing the background JPanel once, while updating the foreground JPanel constantly.
The problem with my code is that the background JPanel does not show.
Now. I know that if I were to draw it constantly it would show. But that defeats the purpose of what i'm trying to do. I am trying to only draw it once, and have be seen at the same time
My code successfully only draws the background JPanel once. The problem is that the background JPanel does not show. How do I fix THIS problem
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JLayeredPane {
static JFrame frame;
static Main main;
static Dimension screenSize;
public Main() {
JPanel backPanel = new BackPanel();
JPanel frontPanel = new FrontPanel();
add(backPanel, new Integer(7));
add(frontPanel, new Integer(8));
new Thread(() -> {
while (true){
repaint();
}
}).start();
}
public static void main(String[] args) {
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame("Game"); // Just use the constructor
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main = new Main();
frame.add(main, BorderLayout.CENTER);
frame.pack();
frame.setSize(screenSize);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class BackPanel extends JPanel{
public boolean drawn = false;
public BackPanel(){
setVisible(true);
setOpaque(false);
setSize(screenSize);
JLabel test1 = new JLabel("Test1");
JLabel test2 = new JLabel("Test2");
add(test1);
add(test2);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
drawOnce(g);
}
public void drawOnce(Graphics g){
if (!drawn){
g.setColor(Color.red);
g.fillRect(0, 0, screenSize.width, 200);
drawn=true;
}
}
}
public class FrontPanel extends JPanel{
public FrontPanel(){
setVisible(true);
setOpaque(false);
setSize(screenSize);
JLabel test = new JLabel("Test");
add(test);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(0+screenSize.width/2, 0, screenSize.width/4, 300);
}
}
}
Try RepaintManager.currentManager(component).markCompletelyClean(component). It will prevent the component from repainting. You might need to do this after each time you add new components.
http://docs.oracle.com/javase/6/docs/api/javax/swing/RepaintManager.html#markCompletelyClean%28javax.swing.JComponent%29
I don't know if this two lines of code
super.paintComponent(g);
drawOnce(g);
are the root of problem, I sincerly don't remember how paintComponent works (a test could help) but try to swap them :
drawOnce(g);
super.paintComponent(g);
maybe, on your original version, you tells JVM to paint the whole component and, only after the AWTEvent has been added to the queue, to draw what you need.
I guess that the awt's documentation will explain it.
I wrote a paint class, and added the jpanel to the frame, but it's getting called twice for some reason, as I put a print statement inside the graphics method, and it printed it twice. The codes below are all the codes I have in my package.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Paint extends JPanel {
static Paint paint = new Paint();
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Hello");
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(paint);
frame.pack();
frame.setLocation(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I tried your code and paintComponent it's not called twice every time. I don't think you have the control on when the JFrame is calling pack() when you call setVisible. It may depends on how your OS manage the windows.
Hi I Would like add to my JFrame border some image.
Is this Possible to attach picture to borders for JFrame and create it as 1 object ?
Something like this:
I'm not sure if it's possible to add the image directly to the border of a JFrame (suggestions welcome). I decided to solve this issue by using a transparent content pane, and using an inner frame to "appear" like the outer frame.
The code is pretty simple, however, let me know if you'd like an explanation of how the code works.
Here's the minimum code you'll need to get up and running.
You'll need to provide your own transparent-phone.png image, in the root of the classpath (i.e. next to your PhoneWindow.java file, in the root package).
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
public class PhoneWindow {
public static void main(String[] args) {
new PhoneWindow();
}
public PhoneWindow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the inner frame
final JInternalFrame frame2 = new JInternalFrame("My Telephone");
frame2.setClosable(true);
frame2.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
// add elements to the outer frame
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
JPanel pane = new TranslucentPane();
frame.setContentPane(pane);
frame.setLayout(new BorderLayout());
// add inner frame and phone picture
frame.add(frame2, BorderLayout.CENTER);
frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/transparent-phone.png")))), BorderLayout.EAST);
frame.setLocationRelativeTo(null);
frame.setMinimumSize(new Dimension(400, 300));
frame.pack();
// show
frame2.setVisible(true);
frame.setVisible(true);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
});
}
public class TranslucentPane extends JPanel {
public TranslucentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
}
Here's the full Java class (including close and draggable behaviour)
https://gist.github.com/nickgrealy/16901a6428cb79d4f179
And here's a screenshot of the final product
N.B. the transparent sections inside/outside the phone.
References:
How to make a transparent JFrame but keep everything else the same?
Trying to disable dragging of a JInternalFrame
I have been trying to upload an image onto a Java Applet Window but unfortunately it turns out to be blank..Here is the code i have written pls help!
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.net.*;
import java.util.*;
public class RandomImages extends JFrame
{
private Image img;
public void static main(String[] args)
{
new RandomImages();
}
public RandomImages()
{
super("Random Images");
setSize(450,450);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk=Toolkit.getDefaultToolkit();
img=tk.getImage(getURL("Your File Name"));
}
Below is the code that fetches the url of the filename looking for...
private URL getURL(String filename)
{
URL url=null;
try{
url=this.getClass().getResource(filename);
}
catch(Exception e) {}
return url;
}
AffineTransform id=new AffineTransform();
Code for paint component...
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
Random rand=new Random();
g2d.setColor(Color.BLACK);
width=getSize().width;
height=getSize().height;
g2d.fillRect(0,0,width,height);
Loop for generating random ships on screen
for(int s=0;s<20;s++)
{
trans.setTransform(id);
trans.translate(rand.nextInt()%width,rand.nextInt()%height);
trans.rotate(Math.toRadians(360*rand.nextDouble()));
double scaled=rand.nextDouble()+1;
trans.scale(scaled,scaled);
trans.drawImage(img,trans,this);
}
}
}
1)Instead of using paint(Graphics g) for custom paintings you need to use paintComponent(Graphics arg0) of JComponent. For example draw image on JPanel and the add panel to your frame. Your JFrame isn't a JComponent.
2) As I know public static void main(String[] args) ;)
Read more about customPaintings.
The best way to add image in JFrame is to use JLabel.
Example:
JLabel image = new JLabel(new ImageIcon("Image.jpg"));
Now add this JLabel(image) into your JFrame.
public RandomImages()
{
super("Random Images");
setSize(450,450);
setVisible(true);
setLayout(new FlowLayout());//you have not used the Layout
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel image = new JLabel(new ImageIcon("Image.jpg"));
add(image);
}
Another way is to use drawImage() function of Graphics class in paint(Graphics g) function .
But you should use paintComponent against paint