Display multiple images in a single applet - java

I have to build a small Java applet for a project. I have previously never used applets. Hence I don't know much about the various inbuilt functions available. The layout of this applet is as below:
The screen is divided into 3 parts
Top most part will have a set of buttons and text boxes
Middle part and bottom part will be displaying different images
These Images can vary in size when the program is run each time (Hence it requires scroll bars in case the image goes out of the screen)
Till now I have succeeded in partitioning the screen and creating separate panels for the each part and adding the corresponding components in them.
Problem:
The bottom image is not completely visible. And also scroll bars are not appearing for each Image when it does not fit into the panel.
I tried using setSize(), setMinimumSize() methods but it does not produce any changes in the output. Can you please help me with the above problem?
This is what I have done till now:
/*<applet code=DOSlayout.java width=400 height=400>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DOSlayout extends JApplet implements ActionListener {
Button ViewButton;
Panel1 Top;
Panel2 LeftSide;
Panel3 RightSide;
Label l1,l2,l3;
Image img;
public void init() {
setSize(400,400);
setLayout(new BorderLayout());
Top = new Panel1();
LeftSide = new Panel2();
RightSide = new Panel3();
Top.setSize(getSize().width, getSize().height/3);
LeftSide.setSize(getSize().width,getSize().height/3);
RightSide.setSize(getSize().width,getSize().height/3);
//RightSide.setMinimumSize (new Dimension(400, 10000));
add(Top, BorderLayout.NORTH);
add(LeftSide, BorderLayout.CENTER);
add(RightSide, BorderLayout.SOUTH);
ViewButton = new Button("View");
l1 = new Label("North");
l2 = new Label("East");
l3 = new Label("West");
Top.add(ViewButton);
Top.add(l1);
//LeftSide.add(l2);
//RightSide.add(l3);
ViewButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
class Panel1 extends JPanel {
Panel1() {
super();
}
public void paint(Graphics g) {
}
}
class Panel2 extends JPanel {
Panel2() {
super();
}
private Image img;
public void init()
{
img = null;
}
public void loadImage()
{
try
{
img = getImage(getCodeBase(), "input1.png");
}
catch(Exception e) { }
}
public void paint(Graphics g)
{
if (img == null)
loadImage();
g.drawImage(img, 0, 0, this);
//g.drawImage(img,0,0,(int)getBounds().getWidth(), (int)getBounds().getHeight(),this);
}
}
class Panel3 extends JPanel {
Panel3() {
super();
}
private Image img;
public void init()
{
img = null;
//setSize(400,400);
}
public void loadImage()
{
try
{
img = getImage(getCodeBase(), "input2.png");
}
catch(Exception e) { }
}
public void paint(Graphics g)
{
if (img == null)
loadImage();
g.drawImage(img, 0, 0, this);
//g.drawImage(img,0,0,(int)getBounds().getWidth(), (int)getBounds().getHeight(),this);
}
}}

Start with the container used in ImageViewer. It centers the image inside a scroll-pane whose scroll-bars appear reliably.
Further tips
"I have previously never used applets." That is ominous, given applets are tougher to develop & deploy than frames. I suggest develop this first in a JFrame (then launch the frame from a link using Java Web Start). Only after seeing the frame launched using JWS should you consider using an applet. By that stage, any 'conversion' needed will be much simpler.
Don't ever call setSize(..) in an applet. The size is in the HTML.
Don't mix Swing and AWT components unless necessary, use all Swing.
It is typically a bad idea to set the sizes (preferred, max or min) of any components.
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use it consistently.

Related

GridBagLayout not resizing on image load

I have a JFrame. It uses a JPanel as its content pane, and that JPanel uses GridBagLayout as its LayoutManager. That JPanel contains two more items: a button, and another JPanel. On program start, an image is loaded from file into the lowest-level JPanel as a BufferedImage using ImageIO.read(...). Here is where everything goes to pieces.
The image loads correctly, I can see a small corner of it on screen (14px square as specified in debugger). There is nothing I can figure out that will cause the layout to grow and fit the entire image in the lowest level JPanel on screen. The image in debuggers shows correct size of 500px. The preferred size of the CardImagePanel shows up correctly as the same size as the image. But the layout will not respect the preferred size unless I manually set the CardImagePanel size using setSize(...) which I'm pretty sure is not supposed to be necessary with GBL.
I have tried putting revalidate() and repaint() calls on every single JFrame, JPanel, layout, grid bag, image, etc throughout the entire program and just can't find the correct place or time to call them to make this thing work. Currently I've been trying to just let the image load incorrectly and use the button to force revalidation and repaint, but even this explicit call is not doing anything.
I'm losing my mind, I'll do anything to get this thing working.
Here is all my code for the whole stupid thing (minus imports and package specification.
P1s1.java:
public class P1s1 {
public static void main(String[] args) {
// TODO code application logic here
build();
}
public static void build()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(640, 480));
frame.setContentPane(new GuiPanel(frame));
frame.setVisible(true);
}
}
GuiPanel.java:
public class GuiPanel extends JPanel {
JFrame parentFrame;
JButton imageLoaderButton;
CardImagePanel cardImagePanel;
LayoutManager layout;
GridBagLayout gridBagLayout;
GridBagConstraints constraints;
public GuiPanel(JFrame frame)
{
parentFrame = frame;
constraints = new GridBagConstraints();
gridBagLayout = new GridBagLayout();
layout = gridBagLayout;
this.setLayout(layout);
this.setBorder(BorderFactory.createLineBorder(Color.black));
setupImageLoaderButton(imageLoaderButton);
cardImagePanel = new CardImagePanel();
this.add(cardImagePanel);
}
private void setupImageLoaderButton(JButton button)
{
button = new JButton("Click to load image!");
ActionListener imageLoaderListener;
imageLoaderListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Button clicked.");
cardImagePanel.revalidate();
cardImagePanel.repaint();
GuiPanel.this.revalidate();
GuiPanel.this.repaint();
parentFrame.revalidate();
parentFrame.repaint();
}
};
button.addActionListener(imageLoaderListener);
this.add(button);
}
}
CardImagePanel.java:
public class CardImagePanel extends JPanel {
BufferedImage cardImage;
public CardImagePanel()
{
this.setBorder(BorderFactory.createLineBorder(Color.black));
try {
cardImage = ImageIO.read(new File("c:\\dev\\cards\\2_of_clubs.png"));
this.setPreferredSize(new Dimension(cardImage.getWidth(), cardImage.getHeight()));
} catch (IOException ex) {
System.out.println("Exception trying to load image file.");
}
}
// The getPreferredSize() override was suggested by MadProgrammer.
// It did not solve the issue, but see MadProgrammer's updated,
// accepted answer below for the correct solution. The rest of the
// code reflects my original attempt to solve the issue.
#Override
public Dimension getPreferredSize()
{
return cardImage != null ? new Dimension(cardImage.getWidth(), cardImage.getHeight()) : super.getPreferredImage();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(cardImage, 0, 0, this);
}
}
GridBagLayout relies on a component telling it what size it would like to be (along with it's minimum and maximum size when it's relievent). You need to override the getPreferredSize method of the CardImagePanel, returning the size you would like the component to be
public class CardImagePanel extends JPanel {
BufferedImage cardImage;
public CardImagePanel() {
this.setBorder(BorderFactory.createLineBorder(Color.black));
try {
cardImage = ImageIO.read(new File("c:\\dev\\cards\\2_of_clubs.png"));
} catch (IOException ex) {
System.out.println("Exception trying to load image file.");
}
}
#Override
public Dimension getPreferredSize() {
return cardImage != null ? new Dimension(cardImage.getWidth(), cardImage.getHeight()) : super.getPreferredSize();
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(cardImage, 0, 0, this);
}
}
Have a look at How to Use GridBagLayout for more details
You CardImagePanel has no preferred size, so the layout manager doesn't know how to handle the size properly.
A couple of solutions:
There is no need to create a custom class to display the image. Just use a JLabel to display the image. The JLabel will return the preferred size of the image.
If you do use the CardImagePane, then you need to override the getPreferredsize() method of the CardImagePanel to return the size of the image.

Subtle differences between java swing objects

I am having some difficulty figuring out why there is a difference between the results I see on the Title Screen and the Setup Screen. I copy/pasted the majority of the code before tweaking each... it clearly has to do with something in my outer frame, but I don't know what. The problem I am seeing is that although the Title Screen comes up at the correct size of 1024x768 with the background correctly displayed, the Setup Screen comes up as a very small window as though I had not just set it's size. The background image is also only shown in that sliver of space, even if the box is resized.
I have removed all of the elements inside of Title Screen but it still maintains its size. Can someone help? Thanks
OuterFrame
public class OuterFrame extends JFrame {
public OuterFrame(String windowHeading) {
int WIDTH = 1024;
int HEIGHT = 768;
final Dimension screenSize = new Dimension(WIDTH,HEIGHT);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel title = new TitleScreen();
title.setLayout(new BoxLayout(title, BoxLayout.PAGE_AXIS));
JButton matchButton = new JButton("New Match");
//Add action listener to button
matchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
removeAll();
JPanel setupScreen = new SetupScreen();
add(setupScreen);
pack();
}
});
JButton exitButton = new JButton("Exit to Windows");
//Add action listener to button
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
System.exit(0);
}
});
matchButton.setAlignmentX(title.CENTER_ALIGNMENT);
exitButton.setAlignmentX(title.CENTER_ALIGNMENT);
title.setPreferredSize(screenSize);
title.add(matchButton);
title.add(Box.createRigidArea(new Dimension(0,25)));
title.add(exitButton);
add(title);
pack();
}
}
Title Screen
public class TitleScreen extends JPanel {
public BufferedImage background;
public TitleScreen() {
try {
InputStream is = new BufferedInputStream(new FileInputStream("images/datascreen.png"));
Image image = ImageIO.read(is);
background = (BufferedImage)image;
} catch (Exception a) {
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(background,0,0,1024,768,null);
}
}
SetupScreen
public class SetupScreen extends JPanel {
public BufferedImage background;
public SetupScreen() {
try {
InputStream is = new BufferedInputStream(new FileInputStream("images/datascreen.png"));
Image image = ImageIO.read(is);
background = (BufferedImage)image;
} catch (Exception a) {
}
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(background,0,0,1024,768,null);
}
}
Sorry about the formatting.. I can't for the life of me make it keep the indention I use in my code.
Edit:
#Override
public Dimension getPreferredSize() {
return new Dimension(1024, 768);
}
I added the above to both the title and the setup classes, as well as removing the hard coded resize. The issue still occurs - the window is sized correctly for the title but not the setup. Any help would be appreciated..
Read the Swing tutorial on Custom Painting for the basics. In this case the problem is that you don't override the getPreferredSize() method of your custom component, so the layout manager basically uses 0.
The reason your first screen displays is because you hardcoded:
title.setPreferredSize(screenSize);
This is a no-no (for too many reasons to go into detail here). The component should return its preferred size as mentioned above and then the pack() statement will work properly.
Figured out that the problem was the removeAll() statement. I added getContentPane. to it and it worked fine.

draw control inside another using its graphics

I'm basically trying to draw a JComponent inside another by calling the second component's paint passing it the first component's Graphics.
I'm trying to create a GUI editor, (reinventing the wheel, I know, it's just a proof of concept)
So I have a class that extends JPanel where I want to draw components from a VectorControls.
So far I got this method in my extended JPanel:
#SuppressWarnings("serial")
public class Sketch extends JPanel {
private Vector<JComponent> controls = new Vector<JComponent>();
public Sketch() {
super();
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
}
public void addControl(JComponent c) {
Dimension d = new Dimension(100,50);
c.setPreferredSize(d);
c.setMinimumSize(d);
c.setMaximumSize(d);
controls.add(c);
this.repaint();
this.revalidate();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=controls.size()-1; i>=0; i--) {
JComponent c = controls.get(i);
c.paint(g);
}
}
}
I'm building/attaching the Sketch panel like this:
public GUIEditor() {
mainFrame = new JFrame("GUI EDITOR");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Sketch mainPanel = new Sketch();
mainPanel.setPreferredSize(new Dimension(640,480));
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
mainFrame.setLayout(gbl);
JPanel toolsPanel = new JPanel();
toolsPanel.setPreferredSize(new Dimension(160,480));
toolsPanel.setLayout(new GridLayout(0,1));
for(Control c : toolBoxItems ) {
AbstractAction action = new ToolBoxButtonAction(mainPanel, c.type);
JButton b = new JButton(action);
b.setText(c.title);
toolsPanel.add(b);
}
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(mainPanel, gbc);
mainFrame.add(mainPanel);
gbc.gridx = 1;
gbc.gridy = 0;
gbl.setConstraints(toolsPanel, gbc);
mainFrame.add(toolsPanel);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
Inside ToolBoxButtonAction, basically I'm doing this:
public void actionPerformed(ActionEvent e) {
try {
sketch.addControl(control.newInstance());
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
}
but I'm writing this because it doesn't work.
Any ideas on how to achieve this?
I'm basically trying to draw a JComponent inside another by calling the second component's paint passing it the first component's Graphics.
Components can only be painted when the component has non-zero size. Normally the size of a component is determined by the layout manager.
Your basic code looks reasonable, but unless you have code to size and locate the components you won't see anything. If you just set the size then all components will paint on top of one another.
Or the problem may be that your parent panel doesn't have a size so it is not even painted. The default FlowLayout uses the preferred size of the child components to determine the panels size. Since you don't add components directly to the panel there are no child components so the preferred size will be 0. When you reinvent the wheel you need to reinvent everything.
Without a SSCCE the context of how you use this code is unknown to all we can do is guess.
Edit:
Create a SSCCE when you have a problem and get it working with hard coded values before trying to get it to work dynamically. Something like:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Sketch extends JComponent
{
private Vector<JComponent> controls = new Vector<JComponent>();
public void addControl(JComponent c)
{
c.setSize(100, 50);
int location = controls.size() * 50;
c.setLocation(location, location);
controls.add(c);
repaint();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i=controls.size()-1; i>=0; i--)
{
JComponent c = controls.get(i);
Point location = c.getLocation();
g.translate(location.x, location.y);
c.paint(g);
g.translate(-location.x, -location.y);
}
}
private static void createAndShowUI()
{
Sketch sketch = new Sketch();
sketch.addControl( new JButton("button") );
sketch.addControl( new JTextField(10) );
sketch.addControl( new JCheckBox("Checkbox") );
JFrame frame = new JFrame("Sketch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( sketch );
frame.setSize(400, 400);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Some time ago, I've written a framework for such tasks. Maybe you find it useful (the library is Open Source):
Tutorial:
http://softsmithy.sourceforge.net/lib/current/docs/tutorial/swing/customizer/index.html
Javadoc:
http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-swing-customizer/index.html
Info about the latest release:
http://puces-blog.blogspot.ch/2012/11/news-from-software-smithy-version-03.html

JButton and JLabel dissappears when adding custom background

JButton and JLabel disappears when adding custom background. I don't see any problems in my program, but maybe you guys find an solution! I think it's only a little thing I forgot, but I can't figure it out.
Here's the code:
GameWindow.java:
setContentPane(new StartImagePanel(RollrackLogo));
out.println("adding JLWelcome");
JLWelcome.setText("Welcome to Rollrack, " + namewindow.name);
add(JLWelcome);
JLWelcome.setVisible(true);
out.println("JLWelcome added");
out.println("adding JBRandom");
JBRandom.setText("Random");
add(JBRandom);
JBRandom.setVisible(true);
out.println("added JBRandom");
The background appears perfect, but not the JButton and JLabel!
Code to the StartImagePanel.java:
public class StartImagePanel extends JComponent{
private Image image;
public StartImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}
Your button and label are added to your GameWindow frame while they should be added to its contentPane, setContentPane(new StartImagePanel(RollrackLogo)); instead. That's why they are not showing, they are added to the frame.
Make a variable of the StartImagePanel and add the button and label to it and they should show up.
StartImagePanel contentPanel = new StartImagePanel(RollrackLogo);
setContentPane(contentPanel);
...
out.println("adding JLWelcome");
JLWelcome.setText("Welcome to Rollrack, " + namewindow.name);
contentPanel.add(JLWelcome);
JLWelcome.setVisible(true);
out.println("JLWelcome added");
out.println("adding JBRandom");
JBRandom.setText("Random");
contentPanel.add(JBRandom);
JBRandom.setVisible(true);
out.println("added JBRandom");
Answer dispute
The claims in the first paragraph are plain wrong. Here is source that proves it.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class AddToCustomContentPane {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new FlowLayout());
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
gui.setBackground(Color.RED);
JFrame f = new JFrame("Demo");
f.setContentPane(gui);
// Acid test. Can we add buttons direct to the frame?
f.add(new JButton("Button 1"));
f.add(new JButton("Button 2"));
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Edit after the custom panel code was given
Here's a snippet that works to show both button and label on a black image background, I removed that was not needed (listeners).
public static void main(String[] v) {
class StartImagePanel extends JPanel {
private Image image;
public StartImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}
class GameWindow extends JFrame{
public GameWindow() {
BufferedImage RollrackLogo;
RollrackLogo = new BufferedImage(400,200,BufferedImage.TYPE_INT_RGB);
final JButton JBRandom = new JButton();
final JLabel JLWelcome = new JLabel();
setDefaultCloseOperation(EXIT_ON_CLOSE);
StartImagePanel panel = new StartImagePanel(RollrackLogo);
setContentPane(panel);
setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
JLWelcome.setText("Welcome to Rollrack");
panel.add(JLWelcome);
JLWelcome.setVisible(true);
JBRandom.setText("Random");
panel.add(JBRandom);
JBRandom.setVisible(true);
}
}
GameWindow window = new GameWindow();
window.pack();
window.setVisible(true);
}
I rather use an instance of a JFrame, instead of extending it, as #Andrew Thompson suggested in another question.
However, if you're extending it, it might be a good practice to call super() in the constructor.
Additionally, we may need to know what is going on in your StartImagePanel.
It seems, to me, to be the problem.
Ensure both your GameWindow and StartImagePanel extend properly their superclasses (call super();).
Ensure your StartImagePanel has a proper Layout.
Add your components before you set your frame visible. This also means you won't need JLWelcome.setVisible(true);.
Ensure that your code is executed in the EDT (Event-Dispatch Thread).
Example:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class GameWindow extends JFrame{
BufferedImage rollrackLogo;
JButton jbRandom;
JLabel jlWelcome;
public GameWindow() {
super();
jbRandom = new JButton("Random");
jlWelcome = new JLabel("Welcome to Rollrack, " +
namewindow.name);
rollrackLogo = new BufferedImage(400, 200,
BufferedImage.TYPE_INT_RGB);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(new StartImagePanel(rollrackLogo));
// Add your components.
add(jlWelcome);
add(jbRandom);
addKeyListener(new KeyListener() {
#SuppressWarnings("static-access")
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_ESCAPE){
System.exit(7);
}
}
#Override
public void keyReleased(KeyEvent arg0) {}
#Override
public void keyTyped(KeyEvent arg0) {}
});
// Pack, or otherwise set fullscreen.
pack();
// Now, set frame visible.
setVisible(true);
}
}
Edit: Now that you've posted the code for your StartImagePanel, I see that you're extending JComponent. Follow my previous advice, (call super), set a Layout, and extend JPanel instead.

Why slideshow not working in Java using Swing and Awt?

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.

Categories

Resources