Change preview font in table? - java

In my program I implemented a table, I recently found out how to change the font size of the table so this is what I did:
It sets the font of the contents in the table to 20, however before I confirm an input with enter or select another cell, the preview is still the standard font and too small
table.setFont(new Font("Tahoma", Font.BOLD, 20));
The preview should also be the same size, that's what I wanna do.

What you need to do is modify the Default Cell Editor like this:
Object dce = jTable1.getDefaultEditor(Object.class);
if(dce instanceof DefaultCellEditor) {
Font font = new Font(jTable1.getFont().getName(), jTable1.getFont().getStyle(), 20); // 20 is your desired font size
((DefaultCellEditor) dce).getComponent().setFont(font);
}
This concept was retrieved from this SO Answer by #Redwine.

Related

How to change size of JCheckBox Swing? [duplicate]

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

Set the font of texts retrieved from JTextField

I have the user enter some words through a JTextField. I want to set the font of the string. Here is what I have so far.
Font f;
f = new Font(input.getText(), Font.ITALIC, 32);
word = new JLabel(f, SwingConstants.CENTER);
Unfortunately, Java is throwing me a compiler error because JLabel doesn't accept Font as a parameter. Is it possible to set the font of a string retrieved from a text field and have it displayed on a JFrame?
See JComponent.setFont(Font).
Sets the font for this component.
But better than a text field to set a font name, see this answer for a (styled) combo or this answer that uses a list:

JFreeChart - wrong chart font

I have a problem with XYLineChart. I don't know how to set the chart font to look like Swing components. When I use this:
chart.setTitle(new TextTitle("Tahoma title, style plain, size 11", new Font("Tahoma", Font.PLAIN, 11)));
It is still wrong :(
EDIT: When I create the chart in a new frame, the font in the title is good. How do I set all the labels, axis titles, and other texts to the same font size, without bold?
SOLVED :)
public static void changeStyle(JFreeChart chart) {
final StandardChartTheme chartTheme = (StandardChartTheme)StandardChartTheme.createJFreeTheme();
final Font font = new Font("Tahoma", Font.PLAIN, 11);
final Color color = new Color(0, 0, 0);
chartTheme.setExtraLargeFont(font);
chartTheme.setLargeFont(font);
chartTheme.setRegularFont(font);
chartTheme.setSmallFont(font);
chartTheme.setAxisLabelPaint(color);
chartTheme.setLegendItemPaint(color);
chartTheme.setItemLabelPaint(color);
chartTheme.apply(chart);
}
If you want to change the existing title's font, do something like this:
chart.getTitle().setFont(new Font("Tahoma", Font.PLAIN, 11));
Addendum:
How do I change all items' fonts, e.g. labels, axis, etc.?
StandardChartTheme offers this capability by operating on individual chart components.
I don't know 2 things about XYLineCharts, but it looks like you might be setting the font on the wrong thing. Try setting it on different components.
Not much, but might get you going.
Good luck ;)
Damo

Java: Fonts and Pixels

I'm making a game and in the menu I want to display the text in the center of the screen.
Is there a way in Java to get/calculate the width of a piece of text in a specified font with specified size and style.
Martijn
The FontMetrics.stringWidth method does just that -- it will return the width in pixels for a given String.
One can obtain the FontMetrics from a Graphics object by the getFontMetrics method.
For example:
g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");
System.out.println(width);
The result was:
135
In the class Font you have methods such like getLineMetrics or getStringBounds that may help you.
Just use a JLabel that is center aligned and the proper layout manager and you don't have to worry about this.
JLabel label = new JLabel("Text");
frame.add(label , SwingConstants.CENTER);

Are there any built-in methods in Java to increase Font size?

Are there any built-in methods in Java to increase Font size?
The Font class allows you to specify font size.
So, to create a font you do something like this:
Font f = new Font("serif", Font.PLAIN, fontSize);
The fontSize parameter will determine the size of your Font.
You can't actually change the size of an existing Font object. The best way to achieve a similar effect is to use the deriveFont(size) method to create a new almost identical Font that is a different size.
Font biggerFont = existingFont.deriveFont(bigNumber);
You can derive a new Font with a different size by using the following:
Font original = // some font
Font bigger = original.deriveFont(newSize);
Where newSize is a float, not an int. This is well documented in the JavaDoc for Font as other people have pointed out
Assuming that you want to change the font size on a specific JLabel, you can do:
label.setFont(label.getFont().deriveFont(newSize));
Make sure that newSize is a float not an int.
I interpreted this question as "How can I increase font size for Swing across the board." I'm not aware of any built-in way to do this, but you could do it yourself by modifying the values in the UIManager class on startup before you create any Swing components.
I do this by having a parameter passed into my app that I use as a multiplier. If I pass in 150 it'll multiply all existing fonts by 150%. The code is as follows
public static void initializeFontSize() {
String fontSizeParam = System.getProperty("myapp.fontSize");
if (fontSizeParam != null) {
float multiplier = Integer.parseInt(fontSizeParam) / 100.0f;
UIDefaults defaults = UIManager.getDefaults();
int i = 0;
for (Enumeration e = defaults.keys(); e.hasMoreElements(); i++) {
Object key = e.nextElement();
Object value = defaults.get(key);
if (value instanceof Font) {
Font font = (Font) value;
int newSize = Math.round(font.getSize() * multiplier);
if (value instanceof FontUIResource) {
defaults.put(key, new FontUIResource(font.getName(), font.getStyle(), newSize));
} else {
defaults.put(key, new Font(font.getName(), font.getStyle(), newSize));
}
}
}
}
}
you can set the property swing.plaf.metal.controlFont when running you application:
java -Dswing.plaf.metal.controlFont=Dialog-50 YourMainClass
in this example, you set the default font to be "Dialog" with size 50.
The question is way too vague to give a good answer. But I think you want to systematically increase font size in your application.
The font face, style and size in a Java Swing application is controlled via the LookAndFeel mechanism. You need to change the font in the look-and-feel if you want the change to apply to all Swing components of a given type.
Have a look at the UIManager example.
Here's how to change the font globally for some UI components:
UIManager.put("Label.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 10)));
UIManager.put("Button.font", new FontUIResource(new Font("Dialog", Font.BOLD, 10)));
UIManager.put("TextField.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 10)));

Categories