Hey All
I want to set a Background for my JWindow. I used setIconImage method in JWindow. but it's not working
How knows what the problem is?
public MainMenu() throws Exception {
try {
bg = ImageIO.read(new File("pics" + File.separator
+ "mainMenuBackground.jpg"));
content = new JWindow(this);
content.setIconImage(bg);
gs.setFullScreenWindow(content);
content.repaint();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.repaint();
} catch (Exception e) {
throw new Exception("Some files are unavailable");
}
}
This lines of code makes a Full-screen window with no background image. why?
How can i fix it?
The setIconImage is for the window icon, not for the background.
Try for instance setBackground. If you want some custom background image, you probably have to either override some paint(Graphics g) method, or set some content pane / add some component that paints the image.
Related
I'm pulling my hair out on this one. Many questions like this here on SO, but I can't get it to work.
I'm trying to add an image to an existing JPanel. The problem is getting the image to be visible in the JPanel. The code runs, but the image is nowhere..
Here's my code:
private void loadImgBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
imagePnl2.add(picLabel);
imagePnl2.repaint();
imagePnl2.revalidate();
}
else
{
System.out.println("File access cancelled by user.");
}
}
In this question the problem was the missing revalidate(). But that makes no difference here.
What am I missing?
In this question the problem was the missing revalidate(). But that makes no difference here.
Order is important. The code should be:
panel.add(...);
panel.revalidate();
panel.repaint();
The revalidate() invokes the layout manager which in turn determines the components size and location. By default components have a size of (0, 0) so if you invoke repaint() first there is nothing to paint.
Also, an easier solution would be to just add an empty label to your panel when you create the GUI. Then when you want to add the image you can just do:
label.setIcon(...);
The setIcon() method automatically does the revalidate() and repaint() for you.
I want the user to be able to click a button and choose and image which'll be displayed on the screen.
This is the code I wrote. It doesn't seem to work:
uploadBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int retVal = fc.showOpenDialog(EditImage.this);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try{
Image img = ImageIO.read(file);
if(img==null){
//TODO: THE FILE IS NOT AN IMAGE. ERROR
}
ImageIcon ic = new ImageIcon(img);
JLabel imageLabel = new JLabel(ic);
imagePreview.add(imageLabel);
}
catch(IOException ex){
//TODO: THE FILE COULD NOT BE OPENED.
}
}
}
});
imagePreview is a JPanel that I've got somewhere on the screen.
What am I doing wrong?
agree with other answers here is required to call container.revalidate() and (there is an Image, then to required) container.repaint()
but this logics is wrong, you couldn't, why to add/remove JComponent for showing another Image, there no reason for, you can to switch betweens ImageIcons in JLabel - JLabel.setIcon(file)
and there is another issue, Images can increasing used JVM memory, you have to call Icon/ImageIcon.flush() before is added to JLabel.setIcon(a few times mentioned here)
Is imagePreview already visible when you add the JLabel to it? If so, you can't just add components to a visible container; you have to revalidate it.
call imagePreview.revalidate(); imagePreview.repaint() after imagePreview.add(imageLabel);, that needed if you add components to visible container.
So im making a gui, and i have a background image for it. i dont know how to make it set as the background, so any help with that would be good. an explination would also be good. also, after we get that image as a background, how do we get the image resize to the size of the window. such as
image.setSize(frame.getHeight(), frame.getWidth());
but i dont know if that would work. the image name is ABC0001.jpg and the frame name is frame. thanks!
To get the image to resize, you can either use
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // draw the image
}
or you can use a componentlistener, implemented like:
final Image img = ...;
ComponentListener cl = new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
Component c = ce.getComponent();
img = im1.getScaledInstance(c.getWidth(), c.getHeight(), Image.SCALE_SMOOTH);
}
};
Image quality will degrade over time with the second solution, so it is recommended that you keep the original and the copy separate.
Create a class the extends JPanel. Have that class load the image by overriding paintComponent
class BackgroundPanel extends JPanel
{
Image img;
public BackgroundPanel()
{
// Read the image and place it in the variable img so it can be used in paintComponent
img = Toolkit.getDefaultToolkit().createImage("ABC0001.jpg");
}
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 0, null); // draw the image
}
}
Now that you have this class, simply add this to your JFrame (or whereever you want the background).
//create refrence if you want to add stuff ontop of the panel
private BackgroundPanel backGroundPanel;
//constructor
add(backGroundPanel, BorderLayout.CENTER);
The size of the background will fill the entire frame so no need to scale it unless you want it smaller
I am doing slideshow of images program in java using timer.
In timer event listner i have added code to chnage image but image is not changing.
Below is the code i have written
class ImagePanel extends JPanel {
private Image backgroundImage;
public ImagePanel(Image backgroundImage) {
super();
this.backgroundImage = backgroundImage;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.backgroundImage, 0, 0, null);
}
}
public class A extends JFrame{
static int counter;
List<String> imagePaths;
int nimgpaths=0;
static A frame = new A();
public static void main(String[] args) {
frame.setSize(1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getPath();
/* Getting required image */
Image backgroundImage = null;
String pathToTheImage = "C:\\Documents and Settings\\Administrator\\My Documents\\My Pictures\\civ1.JPG";
try {
backgroundImage = ImageIO.read(new File(pathToTheImage));
} catch (IOException e) {
e.printStackTrace();
}
/* Initializing panel with the our image */
ImagePanel panel = new ImagePanel(backgroundImage);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.timerEvent();
//frame.show();
}
public void timerEvent(){
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Time event occured");
if(counter > nimgpaths)
counter=0;
String imgPath=imagePaths.get(counter);
Image backgroundImage = null;
try {
backgroundImage = ImageIO.read(new File(imgPath));
}catch (Exception e1) {
e1.printStackTrace();
}
/* Initializing panel with the our image */
frame.removeAll();
ImagePanel panel = new ImagePanel(backgroundImage);
panel.repaint();
//panel.setBackground(backgroundImage);
frame.getContentPane().add(panel);
}
});
timer.start();
}
// To get path of images
public void getPath(){
DbOps db=new DbOps();
imagePaths=db.getPath();
nimgpaths=imagePaths.size();
for(Iterator i=imagePaths.iterator();i.hasNext();){
System.out.println((String)i.next());
}
}
}
Why are you using a custom panel and painting?
Your code is simply painting the image at its preferred size. This functionality is available when you use a JLabel. Then when you use the label all you need to do is use:
label.setIcon(....);
when you want to change the image. Read the section from the Swing tutorial on How to Use Icons for more information.
The only reason to create a custom component is if you plan to scale the image or do something fancy like that. If this is the case then you can use something like the Background Panel which supports scaled images as well as a setImage() method so you can change the image dynamically.
A much better design for ImagePanel would let you just replace the image, rather than removing the component. If you do have to replace a visible component, though, you have to call validate() on its container, or the new one isn't going to show up (most of the time, anyway.) I think that's your problem here.
frame.removeAll() is not doing what you would expect - it is removing the components from the frame itself rather than removing the components from the content pane of the frame. Change the code at the end of the timer's action listener to something like this to fix it:
ImagePanel panel = new ImagePanel(backgroundImage);
frame.getContentPane().removeAll();
frame.getContentPane().add(panel);
frame.getContentPane().invalidate();
frame.getContentPane().validate();
Your concept itself is wrong.
You can refresh the panel like so:
public void refreshPanel(JPanel panel){
panel.removeAll();
panel.invalidate();
panel.validate();
}
Problem:
I see in your code that you are trying to create more than one object of the same panel, which you need to refresh.
It would be better to create one panel object and refresh that object.
ImagePanel panel = new ImagePanel(backgroundImage);
Hope you can understand what I wanted to explain to you.
If you are still confused then let me know.
How can we create a main JFrame with background image and a JFrame inside the main JFrame with Java Swing?
I believe you are looking for internal frames.
For the background image bit, sublass JPanel, override its paintComponent() method, and blit your image there. Then set an instance of that panel as your JFrame's content pane.
public class BackgroundPanel extends JPanel {
private BufferedImage bgImg;
public BackgroundPanel() {
try {
bgImg = ImageIO.read(BackgroundPanel.class.getResourceAsStream(
"mybackgroundimage.png"));
} catch (IOException ex) {
System.err.println("Could not load background image!");
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bgImg != null) {
g.drawImage(bgImg, 0, 0, null);
}
}
}
public class MyJFrame extends JFrame {
public MyJFrame() {
setContentPane(new BackgroundPanel());
}
}
It is hard to know what you are meaning with
a JFrame inside the main JFrame
Have a read about what a JFrame really is. Maybe you want a dialog window in your application, or maybe an internal window. Or maybe just another panel.
To get an background image in a JFrame, I recommend that you simply add a JPanel with a backround image to the JFrame:s contentpane.
Based on my understanding, you won't need to nest a JFrame inside another JFrame and I don't think it is good design to do so too. What you can do is nest JPanels instead.
You will mainly need to know about these two classes:
JPanel ->
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JPanel.html
Graphics ->
http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html