Java handle image with radioButton - java

I am trying to Add an image to a jLabel. Whenever the user clicks radiobutton "Single", or "Double" the jLabel should contain an image of a single or double room.
If rdbDouble(radio button) is clicked the program should do:
private void rdbDoubleActionPerformed(java.awt.event.ActionEvent evt) {
Image imageSingle;
try {
imageSingle = ImageIO.read(new File("C:\\Tegnikon\\2014\\Java\\Assignments\\Semester 2\\HotelBookingSrvice\\ProjectResources\\Double hotel Room.jpg"));
} catch (IOException ex) {
}
if(rdbDouble.isSelected())
{
rdbDouble.setIcon(imageSingle);
}
}
Code throws an error at the "rdbDouble.setIcon(imageSingle);" statement. Erros says, the required and found image is not in the same format.
Please tell me what can I do to get this right

This is because it takes an Icon and not Image. See the AbstractButton setIcon() method for details. In you case you should try
Icon icon = new ImageIcon(imageSingle);
rdbDouble.setIcon(icon);
One more thing I can see in your code is that ypu are adding image to a RadioButton and not JLabel.

Related

Animated gif does not play - mouse listener - event mouse entered

I have a button that I have replaced with an image, on hovering I want the image to play an animated gif. I have added a mouse listener and entered the code for changing the image to the gif. The image changes to the gif; however the gif does not animate. I have had a look for previous answers on this site, there are few but none have been able to help.
#Override
public void mouseEntered(MouseEvent arg0) {
try
{
Image img = ImageIO.read(getClass().getResource("images\\button_1_hover.gif"));
btnShip1.setIcon(new ImageIcon(img));
}
catch (IOException ex) {}
}
Don't use a MouseListener for this, just set up the icon using,
setPressedIcon(Icon),
setRolloverIcon(Icon) etc. See this answer for an example.
Don't attempt to load the image 'as needed', but instead load them & set them up on the button when it is initialized.
Change getClass().getResource("images\\button_1_hover.gif") togetClass().getResource("/images/button_1_hover.gif")
Change the method used to load the image. ImageIO will not typically load an animated GIF correctly. See Show an animated BG in Swing for details.
Change code of the form catch (Exception e) { .. to catch (Exception e) { e.printStackTrace(); // very informative! ..

Java Swing Colour Chooser Throwing Error

So I'm trying to implement a colour chooser that will then take that colour and pass it to another class to be used, but it's throwing up the error
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
javax.swing.colorchooser.DefaultColorSelectionModel cannot be cast to
javax.swing.JColorChooser"
every time I click a colour.
The code I'm using is:
For the actual JColorChooser:
JColorChooser RGB = new JColorChooser(Color.GREEN);
RGB.getSelectionModel().addChangeListener(this);
RGB.setAlignmentX(newPolyButton.LEFT_ALIGNMENT);
RGB.setMinimumSize(new Dimension(50, 25));
RGB.setPreferredSize(new Dimension(125, 25));
And for the listener:
public void stateChanged(ChangeEvent c) {
JColorChooser RGB = (JColorChooser)c.getSource();
Color poly = RGB.getColor();
imagePanel.setColor(poly);
}
And in the other class, imagePanel, I use:
public void setColor(Color poly) {
ImagePanel.poly = poly;
}
Can anyone see where I'm going with this? I was previously using a combo box with some manually input colours to choose from.
Any help greatly appreciated, thanks!
From your code
RGB.getSelectionModel().addChangeListener(this);
RGB.setAlignmentX(newPolyButton.LEFT_ALIGNMENT);
You are adding the ChangeListener to the Selection Modal for your RGB instance.
javax.swing.JColorChooser.getSelectionModel() will return an instance of DefaultColorSelectionModel.
Hence, you get a ClassCastException in your call (JColorChooser)c.getSource();.
UPDATE
From How to Use Color Choosers Java Tutorial:
tcc.getSelectionModel().addChangeListener(this);
. . .
public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
banner.setForeground(newColor);
}
When the state changes, you will want to get the new color as a property of the Color Chooser instead of attempting to get the Source of the ChangeEvent and cast it.
Hope this helps!
In your stateChanged method, c.getSource() returns a DefaultColorSelectionModel and not the reference to your JColorChooser.
However, JColorChooser is usually used to open a color dialog that returns a Color when closed using the OK button.
Color color = JColorChooser.showDialog(parent, title, initialColor);
if (color != null) {
// do something with the chosen color
}

Netbeans matisse, custom button icon property error

I have created a custom JButton where override the setIcon.
public class TestButton extends JButton {
public TestButton() {
super();
}
#Override
public void setIcon(Icon icon) {
super.setIcon(icon);
imgToBufferedImg(Toolkit.getDefaultToolkit().createImage("test.png"));
}
}
And here is the imgToBufferedImg method.
public BufferedImage imgToBufferedImg(Image image) {
if (image == null) {
return null;
}
if (image instanceof BufferedImage) {
return ((BufferedImage) image);
} else {
BufferedImage bufferedImage = new BufferedImage(
image.getWidth(null),
image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bufferedImage;
}
}
I have added this component in Matisse, no problem, however, when i try to set the icon property of the button i get the error:
Failed to write the value to the property "icon"
The problem seems to come from the imgToBufferedImg since i can set the property if i remove the call to this method in setIcon. What is wrong with my image conversion method?
EDIT:
The following test succeeded:
try {
imgToBufferedImg(ImageIO.read(new FileInputStream("test.png")));
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
Also i just figured out that the problem is caused by:
((ImageIcon) icon).getImage();
Running this code when the UI is ready (e.g using a SwingUtilities.invokeLater) seems to work.
The problem might be in Toolkit#createImage(). ImageIO.read() might be better. Also, it looks like you're throwing away the result from imgToBufferedImg().
no reason why
create BufferedImage inside JButtons setIcon(), there you would be to set (for JButton) Icon, ImageIcon
this BufferedImage (should be Icon, ImageIcon) is create after is added to JButton
but
method could be BufferedImage to Icon, ImageIcon
whats wrong with JButton#setIcon()
you can use paintComponent() too
Thanks to the thrashed comment:
Toolkit "operations may be performed asynchronously." Your Image may be incomplete when you try to render it.
I was able to figure out what the problem was. Straight from the setIcon method, i requested the image from the icon:
((ImageIcon) icon).getImage()
But this image is definitively incomplete. Putin my logic within the event dispatching thread did the trick.
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//requesting icon images here
}
}

Component Position (Vaadin)

I have a simple portlet with a few components : 3 Button objects, 1 Slider, 1 MenuBar and a picture assigned to a Label (generated by servlet). Now when I switch between pictures for a Label (I have more of them), I want the picture Label to be placed at the old picture Label object's position:
My picture Label is in the left corner of the portlet. The Button objects, MenuBar, and the Slider are under the picture Label when I select another picture Label the new picture Label is being drawn under the other components (under the Button objects , MenuBar , Slider ) so the Button objects... are top and the picture Label is at the bottom of the portlet
for example, I change the background of the picture Label by selecting the color in the menu :
newItem1.addItem("Blue",new Command(){
public void menuSelected(MenuItem selectedItem){
if(pictureA.isVisible()){
pictureB.setVisible(false);
pictureC.setVisible(false);
window.removeComponent(pictureA);
pictureA= new Label("<img src=http://localhost:8888/portlet/KiviatDiagramm?background=blue", Label.CONTENT_XHTML);
window.addComponent(pictureA);
} else {
window.showNotification("", Notification.TYPE_WARNING_MESSAGE);
}
}
});
UPDATE :
I have switched from Label objects to embedded images (Embedded) (which is a lot better) I have tried to reassign the resource on the Embedded object with the new color but it doesn't work, here is what I've done :
public void init() {
URL PictureAUrl= null;
try {
pictureAUrl= new URL("http://localhost:8888/portlet/pictureA");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL PictureBUrl= null;
try {
pictureAUrl= new URL("http://localhost:8888/portlet/pictureB");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL pictureCUrl= null;
try {
pictureCUrl= new URL("http://localhost:8888/portlet/pictureC");
} catch (MalformedURLException e) {
e.printStackTrace();
}
final Embedded pictureA = new Embedded("", new ExternalResource(pictureAURL));
pictureA .setType(Embedded.TYPE_IMAGE);
final Embedded pictureB = new Embedded("", new ExternalResource(pictureBURL));
pictureB .setType(Embedded.TYPE_IMAGE);
final Embedded pictureC = new Embedded("", new ExternalResource(pictureCURL));
pictureC .setType(Embedded.TYPE_IMAGE);
newItem.addItem("ColorBlue", new Command(){
public void menuSelected(MenuItem selectedItem) {
if(!pictureA.equals(pictureB )){
Resource newPictureResource = new ExternalResource("http://localhost:8888/portlet/pictureA?background=blue");
newPictureResource.setType(Embedded.TYPE_IMAGE);
pictureA.setResource(newPictureResource);
}
else {
window.showNotification("Please select pictureA");
}
}
});
rickthomas is correct, you should use the replaceComponent method. I'm pretty sure that the main problem here is that after you have removed the picture, you call addComponent(pictureA) which actually adds the component to the end of the component list. If you don't have a reference to the old picture and it's the first component, then you can use this:
window.replaceComponent(window.getComponentIterator().next(), newPicture);
In addition to that, you don't have to write HTML to show images. You can use Embedded.
If the images are in your classpath, you can use the following:
Embedded newPicture = new Embedded("", new ClassResource("my-picture.png", myApplication));
newPicture.setType(Embedded.TYPE_IMAGE);
window.replaceComponent(oldPicture, newPicture);
If they are found somewhere else, use this:
URL url = new URL("http://localhost:8888/portlet/KiviatDiagramm?background=blue");
Embedded newPicture = new Embedded("", new ExternalResource(url));
newPicture.setType(Embedded.TYPE_IMAGE);
window.replaceComponent(oldPicture, newPicture);
This might solve your problem.
Looking at the Vaadin API javadoc,
I found this
public void replaceComponent(Component oldComponent,Component newComponent)
I haven't tested it... but it should work.

Display a GWT Image in a centered PopupPanel onLoad

Using GWT I am displaying an image thumbnail with a ClickHandler that then shows the full image (can be several MB) in a centered PopupPanel. In order to have it centered the image must be loaded before the popup is shown, otherwise the top-left corner of the image is placed in the middle of the screen (the image thinks it is 1px large). This is the code I am using to do this:
private void showImagePopup() {
final PopupPanel popupImage = new PopupPanel();
popupImage.setAutoHideEnabled(true);
popupImage.setStyleName("popupImage"); /* Make image fill 90% of screen */
final Image image = new Image();
image.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
popupImage.add(image);
popupImage.center();
}
});
image.setUrl(attachmentUrl + CFeedPostAttachment.ATTACHMENT_FILE);
Image.prefetch(attachmentUrl + CFeedPostAttachment.ATTACHMENT_FILE);
}
However, the LoadEvent event is never fired, and thus the image is never shown. How can I overcome this? I want to avoid using http://code.google.com/p/gwt-image-loader/ because I do not want to add extra libraries if I can avoid it at all. Thanks.
The onLoad() method will only fire once the image has been loaded into the DOM. Here is a quick workaround:
...
final Image image = new Image(attachmentUrl + CFeedPostAttachment.ATTACHMENT_FILE);
image.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
// since the image has been loaded, the dimensions are known
popupImage.center();
// only now show the image
popupImage.setVisible(true);
}
});
popupImage.add(image);
// hide the image until it has been fetched
popupImage.setVisible(false);
// this causes the image to be loaded into the DOM
popupImage.show();
...
Hope that helps.

Categories