resizing a ImageIcon in a JButton - java

I am creating a JButton which includes a specific ImageIcon. The main issue is that the original icon size is much bigger than the button size. As result when the button is displayed, only part of the icon can be seen. What is the method that "resize" an ImageIcon i n order to make it fit inside a JButton?

Image img = icon.getImage() ;
Image newimg = img.getScaledInstance( NEW_WIDTH, NEW_HEIGHT, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newimg );
from http://www.coderanch.com/t/331731/GUI/java/Resize-ImageIcon

I would try to override the getIcon() method of JButton, and resize the super.getIcon(). (Or, redefining the lnf for that button.)

I used this class
I included the code from "get the code" (at the bottom) as another class in my project. Be sure to change the package name if you want it to work.

Related

How to display a JLabel on top of another JLabel, with specified coordinate?

I'm working on a GUI for a Tic Tac Toe project, in which I want to get an image (the player's move) to show up when clicking the corresponding area. However, I can't figure out how to display a JLabel (the move) on top of another JLabel (the background).
I have searched and tried to use layeredpanes, but it just fails to show the entire frame when I run it. I am new to GUI, so I am not quite sure if I implemented it correctly.
layer = new JLayeredPane();
//set up the board as background
String path = "sampleUrl";
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
bg4 = new JLabel(new ImageIcon(image));
layer.add(bg4, new Integer(-1));
frame.add(layer);
frame.pack();
frame.addMouseListener(new MouseListener4());
String xPath = "sampleUrl";
URL xUrl = new URL(xPath);
BufferedImage x = ImageIO.read(xUrl);
icon = new JLabel(new ImageIcon(x));
layer.add(icon);
It just shows up a window with minimum width and height, without displaying the background. Is there something wrong with this code, or any other ways for me to put a JLabel on top of another JLabel?
You can add one label object into another, as JLabel is a container. Try something like this.
JLabel parentLabel = new JLabel("Parent");
JLabel childLabel = new JLabel("Child");
parentLabel.add(childLabel );
I highly recommend you to read about javafx if you are new in GUI.you can merge nodes in any way you need.you can put labels on each other using stackpane,and display them top and down of each other using gridpane very easily.
more information on:
https://docs.oracle.com/javafx/2/

Align JMenuItem text regardless of whether or not an ImageIcon is used

I have a Menu that when I have an ImageIcon on the menu, it move the text to the right. I would like it to always move the text to the right regardless of whether or not there is an ImageIcon used for the menu.
I have tried setting the horizontal alignment.
You can see what is happening in the attached image. I am using the following code (ignore the horizontal alignment as I was testing )
JMenuItem menuItem = new JMenuItem(childmenu.getProperty(MenuDef.text()));
menuItem.setHorizontalAlignment(SwingConstants.LEFT);
menuItem.setToolTipText(childmenu.getProperty(MenuDef.tooltip()));
String image = childmenu.getProperty(MenuDef.image());
HIcon icon = ThinClient.iconManager().getIcon(image);
if(icon!=null)
menuItem.setIcon(icon.getIcon());
Some menus will have images and some will not but I don't want the text alignment to look bad.
After the suggestion by madprogrammer below is the result
I used the following code for a blank icon:
public static Icon BlankIcon(int size) {
BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
return new ImageIcon(image);
}
THANKS AGAIN!

How to set size of custom button?

I've created a GUI program with custom icons for buttons. I'm unable, however, to set the size of these buttons in Java, so they remain their original size, 230x227. I'm trying to get them to be around 20x20 so I used the following code:
classAlcBtn.setPreferredSize(new Dimension(20,20));
classAlcBtn.setIcon(new ImageIcon(getClass().getResource("Alchemist.png")));
classAlcBtn.setBorder(null);
classAlcBtn.setBorderPainted(false);
classAlcBtn.setContentAreaFilled(false);
classAlcBtn.setPressedIcon(
new ImageIcon(getClass().getResource("alchemistClicked.png")));
classAlcBtn.setCursor(new Cursor(Cursor.HAND_CURSOR));
Is there a way to force these icons to size down, or do I have to size down the actual icon file? Thanks for any help.
Assuming you can size down the buttons, without icons. So use the following method to size down the image, without changing the size of original file:
ImageIcon icon = new ImageIcon("whatever.jpg");
Image img = icon.getImage() ;
Image newImg = img.getScaledInstance( NEW_WIDTH, NEW_HEIGHT, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newImg );
...
classAlcBtn.setIcon(icon);
And if Button resizing itself is not working, then you can try using setMaximumSize() instead of setPreferredSize() method as following:
classAlcBtn.setMaximumSize(new Dimension(100,100));
See this for more info. about sizes. Hope this Helps:)

JFrame not displaying all images in fullscreen

So, I am working on a project which requires switching between images. The images need to be in fullscreen mode. There seem to be 2 problems that I am facing.
First is with the image switching. When I switch between images, some images appear ok when I switch. Others dont seem to show up on the screen at all. I just seem to be getting an empty frame.
Second is that the right key seems to work everytime but just for my sanity, I have put system prints. The system outs dont seem to show up on the console but it switches images in the frame(Even though, I get an empty frame sometimes).
Any suggestions/solutions would be highly appreciated.
Note about the code: The draw strings that I have are for testing purposes of the coordinates. I am using an Eyetribe, so just to show where I am looking. The drawstring seems to work perfectly.
Also, I am calling switchImage very quickly, almost 22 times in a second. Could that be an issue? Although it makes me wonder why it works for some images and not for others.
UPDATE: The problem seems to be in g.drawImage. It doesnt seem to be drawing for some images but I can't seem to figure out why thats happening.
Currently this is my code for fullscreen images.
public void showFrame(){
//jL -> JLabel
//jF -> JFrame
//jP -> Panel
jF.setTitle("Test");
jF.setUndecorated(true);
jF.setResizable(false);
jF.setVisible(true);
Toolkit tk = Toolkit.getDefaultToolkit();
int xsize = (int)tk.getScreenSize().getWidth();
int ysize = (int)tk.getScreenSize().getHeight();
jF.setSize(xsize, ysize);
jF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if(testImagesList != null){
img = new ImageIcon(testImagesList.get(0));
}
Image imag = img.getImage();
bi = new BufferedImage(1280, 800, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(imag, 0, 0, 1280, 800, null);
ImageIcon newIcon = new ImageIcon(bi);
jL.setIcon(newIcon);
jF.add(jL);
jP.add(jL);
jF.add(jP);
jF.validate();
}
To switch between images I am using a key listener. The keyListner calls the switch image code. Both are given below.
public void switchImage(ImageIcon image, JFrame jF, JLabel jL, JPanel jP, GazeData gazeData){
Image imag = image.getImage();
BufferedImage bi = new BufferedImage(1280, 800, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.drawImage(imag, 0, 0, 1280, 800, null);
g.setColor(Color.black);
int x = (int) gazeData.smoothedCoordinates.x;
int y = (int) gazeData.smoothedCoordinates.y;
Font font = new Font("Verdana", Font.BOLD, 16);
g.setFont(font);
String text = "hello(" + gazeData.smoothedCoordinates.x + gazeData.smoothedCoordinates.y + ")";
g.drawString(text, x, y);
g.drawString("Fixed Coordinate at (400, 500)", 400, 500);
ImageIcon newIcon = new ImageIcon(bi);
jL.setIcon(newIcon);
jP.add(jL);
jF.validate();
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
// j.switchImage(image, jF, jL, jP, gazeData);
System.out.println("RightDetected");
imageIndex++;
ImageIcon newImage = new ImageIcon(imageList.get(imageIndex));
if(newImage != null){
this.currentImage = newImage;
System.out.println("IMAGE SWITCHED!!!! Current Image="+imageList.get(imageIndex));
j.switchImage(currentImage, j.jF, j.jL, j.jP, currentGazeData);
}
}
}
Probably won't fix your problem but you have incorrect Swing coding practices:
jL.setIcon(newIcon);
//jF.add(jL); // remove
jP.add(jL);
jF.add(jP);
jF.validate();
A Swing component can only have a single parent. First you add the label to the frame and the to the panel. So the label will only ever appear on the panel. Get rid of the first statement.
All the Swing components should be added to the frame BEFORE the frame is made valid. So get rid of the validate() statement and move the setVisible(...) to the bottom.
jL.setIcon(newIcon);
//jP.add(jL);
//jF.validate();
When you change a property of a Swing component the component is smart enough to repaint itself. All you need to do is change the icon of the label. There is no need to add the label back to the panel or validate() the frame.
Others dont seem to show up on the screen at all
Maybe the image isn't found?
The drawstring seems to work perfectly.
Instead of creating all the BufferedImages and doing custom painting you can just display a label on top your label.
So the basic code would be:
imageLabel = new JLabel();
imageLabel.setLayout( new FlowLayout() );
textLabel = new JLabel();
imageLabel.add(textLabel);
frame.add(imageLabel);
Note:
The imageLabel can be added directly to the frame. I don't see any reason for your panel.
To change the image you just invoke the setIcon() method on the imageLabel
To change the text your just invoked the setText() method on the textLabel

Make JCheckbox bigger..?

i want to make my JCheckboxes in a JTable bigger (for Touchscreen), but it doesn't change the size.
I tried it with
setPrefferedSize
setSize
What should I do?..
I assume you mean you want a bigger check box. If so then you need to create images to represent the unselected and selected icons of the check box. Then you can create a renderer and editor using these icons. Finally you would need to increase the height of each row in the table. The code might look something like:
Icon normal = new ImageIcon(...);
Icon selected = new ImageIcon(...);
JTable table = new JTable(...);
table.setRowHeight(...);
TableCellRenderer renderer = table.getDefaultRenderer(Boolean.class);
JCheckBox checkBoxRenderer = (JCheckBox)renderer;
checkBoxRenderer.setIcon( normal );
checkBoxRenderer.setSelectedIcon( selected );
DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Boolean.class);
JCheckBox checkBoxEditor = (JCheckBox)editor.getComponent();
checkBoxEditor.setIcon( normal );
checkBoxEditor.setSelectedIcon( selected );
IMPORTANT NOTE: This was only tested with the default 'Metal' look and feel. I do not guarantee that this will work for any other look and feel. Also I am not entirely sure how it works because it is admittedly a bit of a hack.
I was able to solve this in a slightly different way.
I wanted to use the existing images and just apply a scale to it. I am already scaling the font of my application using the UI defaults and so I have a rather large font. I wondered if I could leverage that and scale the check boxes accordingly.
After scouring the internet and trying a bunch of things I came up with this method:
public static void scaleCheckBoxIcon(JCheckBox checkbox){
boolean previousState = checkbox.isSelected();
checkbox.setSelected(false);
FontMetrics boxFontMetrics = checkbox.getFontMetrics(checkbox.getFont());
Icon boxIcon = UIManager.getIcon("CheckBox.icon");
BufferedImage boxImage = new BufferedImage(
boxIcon.getIconWidth(), boxIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB
);
Graphics graphics = boxImage.createGraphics();
try{
boxIcon.paintIcon(checkbox, graphics, 0, 0);
}finally{
graphics.dispose();
}
ImageIcon newBoxImage = new ImageIcon(boxImage);
Image finalBoxImage = newBoxImage.getImage().getScaledInstance(
boxFontMetrics.getHeight(), boxFontMetrics.getHeight(), Image.SCALE_SMOOTH
);
checkbox.setIcon(new ImageIcon(finalBoxImage));
checkbox.setSelected(true);
Icon checkedBoxIcon = UIManager.getIcon("CheckBox.icon");
BufferedImage checkedBoxImage = new BufferedImage(
checkedBoxIcon.getIconWidth(), checkedBoxIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB
);
Graphics checkedGraphics = checkedBoxImage.createGraphics();
try{
checkedBoxIcon.paintIcon(checkbox, checkedGraphics, 0, 0);
}finally{
checkedGraphics.dispose();
}
ImageIcon newCheckedBoxImage = new ImageIcon(checkedBoxImage);
Image finalCheckedBoxImage = newCheckedBoxImage.getImage().getScaledInstance(
boxFontMetrics.getHeight(), boxFontMetrics.getHeight(), Image.SCALE_SMOOTH
);
checkbox.setSelectedIcon(new ImageIcon(finalCheckedBoxImage));
checkbox.setSelected(false);
checkbox.setSelected(previousState);
}
What it does is get the size of the font from the checkbox's font metrics. Then using that it derives a new icon based on the icon found in the 'Look and Feel'.
One odd thing that I am not able to explain is how the icon for the checkbox in its 'un-selected' or default state, changes to the 'selected' icon, when I am accessing the same property to get each one.
I start by saving the state of the control so I can restore it at the end. This is done because in order for the icons to be set properly, the state needs to be unchecked when you first request the icon from the UIManager and then it will need to be checked when you request the icon the second time to get the 'selected' icon.
I am not entirely sure how the UIManager works or why the checkbox icon changes when we call the same property just by setting the 'selected' value of a single checkbox, but that is what is required in order to get both the necessary icons.
If you did not want to base the size on the font you could easily just pass in the height and width as parameters and use them instead of the font's height when setting the buffered image size.
I might mention that this same methodology works with radiobuttons

Categories

Resources