How to set size of custom button? - java

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:)

Related

Swing JLabel icon: use same image for all resolutions

I know they are quite a few forums that kinda talks about this, but my problem is that I have a JLabel with an icon which I do NOT want to scale when resolution is <> 100% ! I.e. (sorry, in french):
Initially, I set my JLabel icon with something like:
lblImage.setIcon( getNoteIcon() );
//...
ImageIcon getNoteIcon(){
return new ImageIcon( getClass().getResource('path/to/file.png') );
}
This results are that my image displays blurry when HiDPI resolution is set to higher than 100%. Examples:
At 100%:
And at 150%:
You can see that the music note image is fuzzier in the 150% resolution.
What I want: I DO NOT want it to up or downscale the image! I want to keep the original size, unless I can provide different image sizes for various resolutions.
That being said, I looked and tried to use the BaseMultiResolutionImage class to deal with resolutions, passing along an array of the "same size image", but I get the same results when I change the resolution. This is the code I tried :
ImageIcon getNoteIcon(){
List<Image> imgList = new ArrayList<Image>();
/* all images are width = 108 height = 83 */
imgList.add(ImageIO.read(new File('path/to/file.png'))); // 100%
imgList.add(ImageIO.read(new File('path/to/file.png'))); // 125%
imgList.add(ImageIO.read(new File('path/to/file.png'))); // 150%
imgList.add(ImageIO.read(new File('path/to/file.png'))); // 175%
imgList.add(ImageIO.read(new File('path/to/file.png'))); // 200%
BaseMultiResolutionImage multiResolutionImage = new BaseMultiResolutionImage(imgList.toArray(new Image[0]));
return new ImageIcon(
multiResolutionImage
);
}
I don't understand what I'm doing wrong, or if I'm even using BaseMultiResolutionImage correctly. Finally, if I do manage say to give 3 different images for 3 resolutions, (i.e. 100, 125, 150%), is there a way to tell it the "default" one to use when I do not have an image for a given resolution (i.e. 200%) ?
Can anyone shed a light on all of this? Seems like a lot of confusion on my end just to get an image to NOT scale in my window...
Much thanks!
Pat
UPDATE AFTER "PROPER" USE OF BaseMultiResolutionImage:
try {
List<Image> imgList = new ArrayList<Image>();
imgList.add(ImageIO.read(getClass().getResource("images/notes/hidpi_100/file.png"))); // 100% - 108x83
imgList.add(ImageIO.read(getClass().getResource("images/notes/hidpi_125/file.png"))); // 125% - 135x104
imgList.add(ImageIO.read(getClass().getResource("images/notes/hidpi_150/file.png"))); // 150% - 162x124
imgList.add(ImageIO.read(getClass().getResource("images/notes/hidpi_175/file.png"))); // 175% - 189x145
imgList.add(ImageIO.read(getClass().getResource("images/notes/hidpi_200/file.png"))); // 200% - 216x166
BaseMultiResolutionImage multiResolutionImage = new BaseMultiResolutionImage(imgList.toArray(new Image[0]));
ImageIcon icon = new ImageIcon(multiResolutionImage);
return icon;
}
catch(IOException ex){
ex.printStackTrace();
return null;
}
On screen font DPI set to 175% in Windows, this results in:
Before using BaseMultiResolutionImage
After using BaseMultiResolutionImage
Here is a comparison of what I get (left), with the actual image file it's supposed to show on the right hand side (mind you Paint doesn't take into account background transparency):
Any ideas as to why this "choppy" image is showing? What am I missing ?
Thanks again.
Pat

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!

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

resizing a ImageIcon in a JButton

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.

Categories

Resources