Setting Colors in SWT - java

This is pretty simple, I come from a swing/awt background.
I'm just wondering what the proper way to set the background color for a SWT widget is?
I've been trying:
widget.setBackground( );
Except I have no idea how to create the color Object in SWT?

For standard colors (including common colors and default colors used by the operating system) Use Display.getSystemColor(int), and pass in the SWT.COLOR_* constant for the color you want.
Display display = Display.getCurrent();
Color blue = display.getSystemColor(SWT.COLOR_BLUE);
Color listBackground = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
Note that you do not need to dispose these colors because SWT created them.

To create a color, try this:
Device device = Display.getCurrent ();
Color red = new Color (device, 255, 0, 0);

Remember that in SWT you must explicitly dispose any resources that you create when you are done with them. This includes widgets, fonts, colors, images, displays, printers, and GCs. If you do not dispose these resources, eventually your application will reach the resource limit of your operating system and the application will cease to run.
See also: SWT: Managing Operating System Resources

Related

How do I change the color of an actual JButton in Java? Not the background and not the text

button[currRow][currCol].setBackground(Color.RED);
button[currRow][currCol].setContentAreaFilled(true);
button[currRow][currCol].setOpaque(true);
That's what I have right now for my connect four game to denote a red player's move.
At the moment, it only colors the background and if I change my code to button[currRow][currCol].setForeground(Color.RED) then the whole thing just appears to not change. How would I fix this?
This is not easily achievable. The problem is that the pluggable look and feel paints the button content, and it does so in whatever way it sees fit. For instance, some L&F might paint a gradient which does not use the background color.
I suggest for a case such as yours to use a custom image (JButton.setIcon()) and no content area (JButton.setContentAreaFilled(false)).
Alternatively, you could create a custom component which draws the element itself, overriding JComponent.paintComponent().

Java awt SystemTray - Popmenu too small on Surface 4 Pro

We've a Java application with a trayicon (SystemTray) and a popup menu (PopupMenu) that worked nicely on all platforms.
On a new Surface 4 Pro we've a problem as the size of the menu is amazingly small. Looks as not noticing it's a 'retina'/high definition display.
Is there an easy way to fix this ?
Looks like you may have to resort to setting the menu UI.
See : https://docs.oracle.com/javase/8/docs/api/javax/swing/JPopupMenu.html#setUI-javax.swing.plaf.PopupMenuUI-
Of course that means you need some way to determine that you're running on the Surface Pro in the first place.
You could try figuring out the current font size and dimensions used by the menu UI and compare that with the screen dimensions from Toolkit.getDefaultToolkit().getScreenSize()
As a general solution, which is not tied up to specific devices, you could detect screen resolution in dots-per-inch via:
java.awt.Toolkit.getDefaultToolkit().getScreenResolution()
This will return screen resolution in DPI (dots-per-inch). The bigger this value - the smaller the textual fonts will get for a specific font size.
Use the DPI to set an acceptable (or maximal) DPI settings and calculate the adjustment ratio.
You can adjust either by replacing the UI delegates fonts (for an application-wide effect)
OR, if the issue is specific for the system-tray, by deriving a larger font only for SystemTray's MenuItems:
java.awt.Font defaultFont = java.awt.Font.decode(null); // default font
float adjustmentRatio = 1.0f; // Calculate this based on your metrics
float newFontSize = defaultFont.getSize() * adjustmentRatio ;
java.awt.Font derivedFont = defaultFont.deriveFont(newFontSize);
// PopupMenu with the adjusted font size:
MenuItem item = new MenuItem("Menu Item");
item.setFont(derivedFont);
popupMenu.add(item);

Swing: Resizing RadioButton

I need to implement font size switching in my app. But when I increase font's size RadioButtons remain same size and on small screen with high resolution my customer just can't hit it easily. Is there a way to resize RadioButton's round thing programmatically without diging into L&F and redrawing Icons manually (it's complicated since app targets multiple platforms with different UIs and each of them must have 7 icons).
Perfect solution could look like this:
Extraction of native UI icon.
Resizing it
Setting resized icon as component's icon.
How to implement step 1? Is it possible?
EDIT: this is what i tried so far
public class IconImageSaver extends JFrame{
public IconImageSaver() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(0,0,100,100);
setVisible(true);
JRadioButton rad1 = new JRadioButton();
rad1.setBounds(10,10,40,40);
add(rad1);
Icon icon = UIManager.getIcon("RadioButton.icon");//(1) trying to get icon
int w = icon.getIconWidth(),h = icon.getIconHeight();
Image i = rad1.createImage(w, h);
Image i2 = rad1.createImage(w,h);
Graphics g = i.getGraphics();
Graphics g2 = i2.getGraphics();
g.setColor(Color.CYAN);
g.fillRect(0, 0, w, h);
rad1.setIcon(new ImageIcon(i));//setting icons
g2.setColor(Color.RED);
g2.fillRect(0, 0, w, h);
rad1.setPressedIcon(new ImageIcon(i2));//setting icons
}
public static void main(String[] args) {
new IconImageSaver();
}
}
At position (1) i'm trying to get icon image, but it returns only background color.
Can't understand why.
Setting icons for various states works as intended.
Some L&Fs (e.g. Nimbus, Aqua) support a large JComponent.sizeVariant, as discussed in Resizing a Component and Using Client Properties.
Addendum: I must use pure native L&F.
The rendering of a JRadioButton is determined by its associated ButtonUI delegate. The internals of delegates supplied by the native L&F are generally inaccessible and rely on host platform APIs. You have to use the available feature(s) of the user's chosen L&F or supply your own. If you can explain more about the underlying problem, it may help to suggest better alternatives.
Addendum: Absent developing a complete L&F, it may be possible to work with the radio button's parent, JToggleButton. Such buttons work well in a ButtonGroup, as shown here, and they can be decorated arbitrarily, as outlined here.
is very L&F sensitive, by default you can
use proper L&F (only Nimbus has implemented auto_whatever) but we talking about Custom L&F
to override keys in UIManager, but these keys can, could (be presented or with value) or missing in compare with another L&F
create own (J)Component, to overide important methods and
a) put to the UIManger (one def. valid for whole JVM instace)
b) add to the selected, desired or part of (J)Components, e.i. .... in the visible GUI
notice for (I need to implement font size switching in my app) there is very important to test if is required to change (we'll talking about) Font or FontUIResources, part of implemented methods for part of (J)Components to pretty ignore Font and required FontUIResources, now not sure if vice versa too
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 a little bit differently.
I Was scaling my font globally using the UIManager defaults and so I wanted my radio buttons to scale with the font.
I found I could do this by extracting the Icon for the radio button from the UIManager, buffering them, re-sizing them and then deriving a new icon from the graphics of the buffered icons.
I ended up with this function:
public static void scaleRadioButtonIcon(JRadioButton rb){
boolean previousState = rb.isSelected();
rb.setSelected(false);
FontMetrics boxFontMetrics = rb.getFontMetrics(rb.getFont());
Icon radioIcon = UIManager.getIcon("RadioButton.icon");
BufferedImage radioImage = new BufferedImage(
radioIcon.getIconWidth(), radioIcon.getIconHeight(),BufferedImage.TYPE_INT_ARGB
);
Graphics graphics = radioImage.createGraphics();
try{
radioIcon.paintIcon(rb, graphics, 0, 0);
}finally{
graphics.dispose();
}
ImageIcon newRadioImage = new ImageIcon(radioImage);
Image finalRadioImage = newRadioImage.getImage().getScaledInstance(
boxFontMetrics.getHeight(), boxFontMetrics.getHeight(), Image.SCALE_SMOOTH
);
rb.setSelected(true);
Icon selectedRadioIcon = UIManager.getIcon("RadioButton.icon");
BufferedImage selectedRadioImage = new BufferedImage(
selectedRadioIcon.getIconWidth(), selectedRadioIcon.getIconHeight(),BufferedImage.TYPE_INT_ARGB
);
Graphics selectedGraphics = selectedRadioImage.createGraphics();
try{
selectedRadioIcon.paintIcon(rb, selectedGraphics, 0, 0);
}finally{
selectedGraphics.dispose();
}
ImageIcon newSelectedRadioImage = new ImageIcon(selectedRadioImage);
Image selectedFinalRadioImage = newSelectedRadioImage.getImage().getScaledInstance(
boxFontMetrics.getHeight(), boxFontMetrics.getHeight(), Image.SCALE_SMOOTH
);
rb.setSelected(previousState);
rb.setIcon(new ImageIcon(finalRadioImage));
rb.setSelectedIcon(new ImageIcon(selectedFinalRadioImage));
}
What it does is get the size of the font from the radiobuttons's font metrics. Using those metrics, it derives a new icon based on the icon found in the 'Look and Feel' and sizing it to the font's height.
One thing that I am not able to explain is how the icon for the radiobutton coming out of the UIManager changes to the 'selected' icon when I am accessing the same property to get both icons.
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.
Again, I am not entirely sure how the UIManager works or why the icon changes when we call the same property just by setting the 'selected' value of a single radiobutton, but that is what is required in order to get both the necessary icons.
If you did not want to use the font to size the controls, 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 checkboxes

Modifying taskbar icon of my .jar program

I'm trying to change the default java icon that appears in taskbar everytime I run my .jar program. I managed to change it with frame.setIconImage(img); but this makes icon way too small, I want it to be as big as other programs icons and have a high quality. Any way I can do that? Thanks.
As you only supplied a single icon, Windows will then scale that icon to whatever size it needs displaying it in the taskbar (could be 16x16, 32x32 or other sizes, depending on the desktop them and size of the taskbar.
If you want to have a "good looking" icon in the task bar you will need to provide a 32x32 pixel version of your icon.
Once you have that you can call setIconImages(List) instead of setIconImage() to define the icons that the operating system can use:
List<Image> icons = new ArrayList<Image>();
icons.add(getImage("someImage16x16.gif"));
icons.add(getImage("someImage32x32.gif"));
window.setIconImages(icons);
Where getImage() is some method returning the proper image icon. Essentially that would be the same steps you already used to define the current icon.
You can also supply a 64x64 and 24x24 icon using this method (just add more icons to the list).
Try looking at this example. It looks like you need to use frame.setIconImage(Toolkit.getDefaultToolkit().getImage("your_image.gif")); line

How to change the size of JFrame icon

How to change the size of JFrame icon?
JFrame f = new JFrame("Test");
Image icon = Toolkit.getDefaultToolkit().getImage("icons/logo.png");
// icon.setPreferredWidth()...
f.setIconImage(icon);
Frame icons are set according to a size decided by the OS.
If you supply icons of various sizes, Windows will use the smaller one for the frame icon, and the larger one as the image to include in the window shown when the user types alt tab to change between apps.
OS X shows no frame icon at all.
See also: Sizes of frame icons used in Swing.
Top Level Containers came from Native OS, from current used theme, then not possible to increase numbers of available pixels,
some dirty hack are possible to wrote in case that you setSystemLookAndFeel, including caption, Font type&size or background, simple don't do that this way,
possible only by implements Custom Look and Feel especially some of Substance's themes can do that

Categories