add image in Jpanel using canvas - java

i want to add image to my panel which is created by Netbeans GUI Designer.
here's my canvas class
private static class GraphicsClass extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Toolkit tkit;
tkit=getToolkit();
Image img=tkit.getImage("ampera.jpg");
g.drawImage(img,0,0,this);
}
}
and this is how i use it in JFrame class constructor
this.Jpanel1=new GraphicsClass();
but the image doesnt show. How to fix it?

this.Jpanel1=new GraphicsClass();
Won't work. Assuming you just drag and dropped a panel onto the frame and named it Jpanel1, then in the constructor you did the above code. When you first drag and drop the original panel, it gets initialized and laid out. When you do the above code, you are making a new component. The original panel is still the one added, and is not the same referenced panel and the new one you just created. So the new panel will never show, it is just the one (with no reference identifier). Like if you has something like
public class MyFrame extends JFrame {
public MyFrame() {
initComponents();
jPanel1 = new GraphicsClass();
}
private void initComponent() {
jPanel1 = new JPanel();
// add jPanel1 to frame
}
private class GraphicsClass extends JPanel {}
private JPanel jpanel1;
}
That's the basic netbeans setup. The code in the initComponents method is autogenerated and is not editable by default. You could edit it, but I would advise against it (unless you really know what you're doing). If you look at the code, you will see exactly what I wan talking about in the beginning.
Fix: Created a panel form from the designer (i.e. New->Swing Form->JPanel form). Then you can simply drag and drop the panel to the frame, as seen here
Other note:
Don't create your images in the paintComponent method. Make it a class member and create it in the constructor.
Instead of a panel, if you want to create an image (say for a background), you can use an ImageIcon and a JLabel and set the layout manager to the label, You can then start adding component onto the label.
Drag and drop an label
Go to the properties of the label and click the ... of the icon property. In the dialog, you can browse for an image.
Then right click the label from the design view, and set a layout manager for the label. You can then start adding components to the label.

You can fix this by using the BufferedImage class, or using the MediaTracker to track when your image has loaded

Related

text field not appearing or not reacting on location code

strange thing, i want to add text field next to the label. When i'm doing that it's not reacting on .setLocation command and background color does not change. Dont know why.
But when i set frame Layout to null , than background command working and changing the color , but text field are not showing. Strange. i tried with adding text field through panel, not working, by simple frame.add(textField) , not working.
public class EcrWindow extends JFrame {
JFrame ecrFrame;
JLabel ecr;
static JTextField ecrTitle;
public static void main(String[] args)
{
new EcrWindow();
}
EcrWindow()
{
JPanel p = new JPanel();
ecrFrame = new JFrame ("ECR WINDOW");
ecrFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
ecrFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
ecrFrame.setResizable(true);
ecrFrame.getContentPane().setBackground(Color.RED);
//ecrFrame.setLayout(null);
ecr = new JLabel("Emergancy Change title");
ecr.setSize(ecr.getPreferredSize());
ecr.setLocation(100,50);
ecrFrame.add(ecr);
ecrTitle = new JTextField();
ecrTitle.setColumns(30);
//ecrTitle.setSize(ecrTitle.getPreferredSize());
ecrTitle.setLocation(150,50);
p.add(ecrTitle); // adding text field to the panel, and panel adding to the frame
ecrFrame.add(p);
// ecrFrame.add(ecrTitle);
ecrFrame.setVisible(true);
}
}
The ContentPane of the Frame is not visible as soon as you add the Panel p to the frame. The content pane will be hidden by the panel which will consume the whole available space in the frame.
When you set the Layout to null, you do not see the Panel p any more as there is no information where it is rendered in the frame (the TextBox should also disappear when you set the Layout to null). This is why the red background is visible then.
Please try to add the following line to your code before you add the Panel p to the frame:
p.setBackground(Color.RED);
Then you should see a red background which is actually the Panel p.
Regarding the layout, you shouldn't use setLocation(). It is much better to use a different layout mechanism with a proper LayoutManager.
See also this answer.
You can use setLocation() if you use absolute positioning. But that would mean that you effectively write a layout manager by hand. I would advise you to read the guide Laying Out Components Within a Container - there are various explanations and examples you can build up upon.

I am having some issues regarding jframe and jlabel?

I am making simple login screen. I added two JLabel's in JFrame in my program and it's running successfully but the problem is that when I run the program I got blank screen and empty jframe, however I have added two jlabel's in that frame but it's not showing me any thing and then if I minimize the window and after some time if I open that window again then I can see those components.
Here is my code:
package javaapplication41;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.*;
public class JavaApplication41 {
JavaApplication41()
{
JFrame cpec=new JFrame();
cpec.setBounds(300,200,600,350);
cpec.setUndecorated(false);
cpec.setVisible(true);
cpec.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l = new JLabel(new ImageIcon("C:\\Users\\MUHAMMAD SHAHAB\\Documents\\NetBeansProjects\\Real Estate\\src\\real\\estate\\file (2).jpg"));
l.setBounds(100,100,200,125);
//l.setLayout(null);
cpec.add(l);
JLabel kiq=new JLabel(new ImageIcon("C:\\Users\\MUHAMMAD SHAHAB\\Documents\\NetBeansProjects\\Real Estate\\src\\real\\estate\\bla.jpg"));
kiq.setBounds(100,100,100,100);
//kiq.setLayout(null);
l.add(kiq);
}
public static void main(String[] args) {
JavaApplication41 ne=new JavaApplication41();
}
}
I am getting this output when I run program:
and when I minimize this window and again open this, then I am getting the desired output here it is:
what am I doing wrong?
You have to put cpec.setVisible(true); after adding all the items in your jframe.I hope this will surely solve your problem
You have set the visibility of JFrame at a very early stage. At that time the JLabel was not added. When you minimized and resized your frame, it got rendered again resulting in showing your added components.
Remember to add components before setting the Frame's visibility( set visibility at last).
Also I would suggest you to use GUI threads when working on swing components. Refer to swing utilities here : https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
Lastly set the layout of JFrame to null as you are trying to add labels to specific coordinates with setBounds() method.
Default layout of jframe is BorderLayout, so if you want you can change layout by reference of java.awt.Container abstract class.
It is initialized by getContentPane() of javax.swing.JFrame class.
The components are added only through reference of java.awt.Container class.
java.awt.Container c=cpec.getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
c.add(l); //label will get added to JFrame instance that is referenced
//then define size and at last define visibility
cpec.setSize(500, 500);
cpec.setVisible(true);
Set the Layout manager of the container as null. By default it uses BorderLayout as its Layout manager. You just have to call the getContentPane() method using the reference of the JFrame, which returns a container reference. Example:
Container c = frame.getContentPane();
c.setLayout(null);
For more information you can go through my Website.

what is the purpose of JFrame setBackground

When you create JFrame instance, you have setBackground method available from this instance. However, regardless to what color you try to put there, you`ll receive gray background color.
This happens (as i understood), because default JPanel instance is automatically created inside JFrame and lays over it . So, to get color set, you need to call
JFrame.getContentPane().setBackground(Color.RED);
that actually calls setBackground of default JPanel , that exists inside JFrame.
I also tried to do next :
JFrame jf = new JFrame();
//I expect this will set size of JFrame and JPanel
jf.setSize(300, 500);
//I expect this to color JFrame background yellow
jf.setBackground(Color.yellow);
//I expect this to shrink default JPanel to 100 pixels high,
//so 400 pixels of JFrame should became visible
jf.getContentPane().setSize(300, 100);
//This will make JPanel red
jf.getContentPane().setBackground(Color.RED);
After this set of code, I am having solid red square of JFrame size , i.e. 300 x 500.
Questions :
Why jf.getContentPane().setSize(300, 100); does not resize default JPanel , revealing JFrame background?
Why JFrame has setBackground method if anyway you cannot see it and it is covered by default JPanel all the time?
As per the class hierarchies of JFrame as shown below:
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
The method Frame#setBackground() is inherited from Frame and JFrame doesn't do override it.
What JFrame states:
The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case.
You can override default setBackground() of JFrame as shown below:
#Override
public void setBackground(Color color){
super.setBackground(color);
getContentPane().setBackground(color);
}

Java Swing Repaint an image

I'd like to implement a DragAndDrop for an Image but can't seem to get the Swing repaint function to work on the specific Image.
Code:
public class playerFrame extends JFrame{
...
private void destroyerImageMouseDragged(java.awt.event.MouseEvent evt)
}
repaintCurrentPosition(evt);
}
public void repaintCurrentPosition(MouseEvent e){
this.setLocation(e.getX(), e.getY());
this.repaint();
}
this.repaint <- this function repaints the whole frame and not just the Image I'd like it to repaint, which is about 50x50 size.
How do you repaint a specific JPEG image without creating a new class?
thanks.
this.repaint will force the parent frame to be repainted. Call repaint only on the control holding your image.
Example: to refresh this image loaded onto the JLabel:
ImageIcon icon = createImageIcon("images/middle.gif");
label = new JLabel("Image and Text", icon, JLabel.CENTER);
You do:
label.repaint();
not just the Image I'd like it to repaint, which is about 50x50 size
JComponent#paintImmediately carefully with EDT
How are you doing the drag and drop?
The easiest way is to just add an Icon to a JLabel and then drag the label around. Everytime you invoke setLocation(...) on the label it will repaint() itself.
The Component Mover class does all the hard work for you.
Call repaint only on the panel where your image is drawn.

How can I Change the default Icon of a JPanel based swing app (or window)

I've seen many answers for this question when it's a JFrame, but none for JPanel, and all that I've tried didn't work.
So basically I've written this simple class/app that extends JPanel, and all is working fine. Now I'd like to change the Default Icon.
Any ideas?
Just as guys are saying here in comments please reconsider what you are trying to do.
The only option to change an icon is to set it for the frame in which the panel is child, since the icon is a part/belongs to the frame.
If you want setting of the icon to be a functionality of a panel then in addNotify() method, which is called when a component receives a parent, look through the panel's parent and it parent and so on until you will reach the frame and set the icon for it.
Sample showing a number of parent you must go through to get to frame if a panel is its content pane.
JPanel p = new JPanel();
JFrame f = new JFrame();
f.setContentPane(p);
System.out.println(SwingUtilities.windowForComponent(p));

Categories

Resources