Make JCheckbox bigger..? - java

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

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

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

Font size in textfield libgdx

How can I change the size of textfield font in libgdx?
UserNameTextField = new TextField("", GlobalSKin);
UserNameTextField. ???
There are various builtin methods you can call to set size.
If you just want to set the size of textfield you can call
UserNameTextField.setWidth(float width) Or UserNameTextField.setHeight(float width) or UserNameTextField.setMaxLength(maxLength)
And if you only want to set size of font then do it like `
TextField.TextFieldStyle textFieldStyle = skin.get(TextField.TextFieldStyle.class);
textFieldStyle.font.scale(1.6f);
`
You can check all methods , just need to take a look at API.

Libgdx Label multiline text height

i have done a small test on LibGdx, on Multi-line Label, it seems that i cant get the wrapped line's height. Following is the code. Theoretically, height for aLebel should be > bLabel. But the result appear the same.
code:
aLabel.setText("this is a super long long long text that need wrapping."); // line wrapped into 3 lines
aLabel.setWrap(true);
aLabel.setWidth(470);
doLog("aLabel.getHeight(): " + aLabel.getHeight());
bLabel.setText("this is short."); // unwrapped line
bLabel.setWrap(true);
bLabel.setWidth(470);
doLog("bLabel.getHeight(): " + bLabel.getHeight());
result:
aLabel.getHeight(): 45.0
bLabel.getHeight(): 45.0
Do anyone have any idea how to get the actual multi-line height in LibGdx? Thanks in advance.
I had this issue for years and accidentally solved it by setting the width and packing the label twice. Note that multiline labels were never intended to figure out their own width, so you have to set them externally, preferably from it's parent.
public Label createLabel() {
// Create label and set wrap
Label label = new Label("Some long string here...", skin);
label.setWrap(true);
// Pack label
label.pack(); // This might not be necessary, unless you're changing other attributes such as font scale.
// Manual sizing
label.setWidth(textWidth); // Set the width directly
label.pack(); // Label calculates it's height here, but resets width to 0 (bug?)
label.setWidth(textWidth); // Set width again
return label;
}
LibGDX version used: 1.6.4
Pack sizes the widget to its pref size, nothing more. Pref width of a label with wrapping is 0.
Label label = new Label(...);
label.setWrap(true);
label.setWidth(123);
label.setHeight(label.getPrefHeight());
I had the same issue and it seems there doesn't exist a method in Label class to solve this. Also, I agree with you, the getHeight() method should return the real height of the Actor, so I don't know if that's a bug or there is a reasoning behind that behaviour.
Anyways, how I solved the issue is by using BitmapFont's getWrappedBounds method. It's not short, but for your example it would be the following:
doLog("aLabel.getHeight(): " + aLabel.getStyle().font.getWrappedBounds(aLabel.getText(), aLabel.getWidth()).height);
This could be done by adding a restriction to the cell that contains the Label in the Table:
Label label = new Label("Example", new Label.LabelStyle(font, Color.WHITE));
label.setWrap(true);
Table table = new Table();
table.add(label).width(WITH);
For more information about how to use Table go to: https://github.com/libgdx/libgdx/wiki/Table

Categories

Resources