I have to write app, which can scale font's size of label and buttons depending on size of entire frame. My idea is to increase size of font until whole text fits into label or button.
How can I check is all string fit to button/label?
Something like the following
JComponent c = ... // it can be label, button or any other component
FontMetrics fm = c.getFontMetrics(c.getFont()); // or another font
int strw = fm.stringWidth("My text");
I took this example from Getting string size in java (without having a Graphics object available)
Related
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.
I'm making a Matrix calculator in Java using a two-dimensional array of JTextFields on a JPanel to input a given Matrix. Since the panel that this matrix is placed on has a fixed size, I want to scale down the text size to accommodate how long the number is as it's being typed in.
For example:
If it's one digit long, font size = 18. If it's two digits long, font size = 14. Etc.
I want this to dynamically occur as the user is entering the text, and I want repainting to occur everytime the user interacts with the JTextField, not only after the user presses "enter". This is because the field is transparent and currently looks sloppy (numbers overlapping) until the user presses enter.
What's the most straightforward and reliable way to do this? Here's my current code if it helps anyone answer my question:
public class MatrixPanel extends JPanel implements ActionListener
{
float[][] matrice = new float[3][3];
JTextField[][] parameter = new JTextField[3][3];
Font font = new Font("SansSerif", Font.BOLD, 40);
public MatrixPanel(String title)
{
setLayout(null);
setOpaque(false);
for (int width = 0; width < 3; width++){
for (int height = 0; height < 3; height++){
matrice[width][height] = 0;
parameter[width][height] = new JTextField();
parameter[width][height].setHorizontalAlignment(JTextField.CENTER);
parameter[width][height].setFont(font);
parameter[width][height].setText("0");
parameter[width][height].setLocation((50*width), (50*height));
parameter[width][height].setSize(50,50);
parameter[width][height].setOpaque(false);
parameter[width][height].setBorder(null);
parameter[width][height].addActionListener(this);
add(parameter[width][height]);
}
setSize(150,150);
}
}
I want to scale down the text size to accommodate how long the number
is as it's being typed in.
Take a look to How to Write a DocumentListener to achieve your goal.
Some useful tips:
About setSize(150,150) and setLocation((50*width), (50*height)): please have a look to this topic Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (yes we should). Components size and location should be handled by layout managers.
You may want to try GridLayout to place the text fields in a grid and forget about the fixed size/location. See How to Use GridLayout and Laying Out Components Within a Container tutorials for a better understanding on this subject.
If you want to input floats (or doubles) in your matrix then maybe formatted text fields or spinners are a better choice than plain text fields. Take a look to How to Use Formatted Text Fields and How to Use Spinners tutorials.
I have JLabel which I would like to change its size while I resize the window. When JLabel contains String which is too big, the String should be shortened, with right part visible and adds dots on the left hand side of the String.
My JLabel is inside innerPanel which is a header in middlePanel which is added to outerPanel. So when I resize window I use listener on outerPanel in that way:
outerPanel.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent evt) {
int width = ((JPanel) evt.getSource()).getWidth();
windowSize = width;
refresh();
}
// [...] other not used override methods
});
refresh() repaints view and creates new middlePanel where is called class which creates innerPanel where is located my JLabel:
Public class InnerPanel extends JPanel {
private int maxSize;
String string = "<VERY_LONG_STRING>";
private static final int DEFAULT_INDEND_PIXEL = 70;
public InnerPanel(int windowSize) {
maxSize = windowSize - DEFAULT_INDENT_PIXEL;
createPanel();
}
private createPanel() {
// [...] gridbag and GridBagConstraints implementation
String shortString = countString();
JLabel label = new JLabel(shortString);
add(label,gc);
}
private String countString() {
int index = 0;
boolean toBig = true;
StringBuilder sb = new StringBuilder(string);
while(toBig) {
Rectangle2d rect = // [...] code which creates rectangle around text from sb.toString()
// I have no access to repo at home but if it's important I can paste it tomorrow
if(rect.getWidth() > maxSize)
sb.deleteCharAt(0);
else
toBig = false;
}
return sb.toString();
}
}
That's works fine in general, bacause it do resize JLabel in one step when I enlarge window in width. But the problem is appear when I try to reduce the window in width. In this case componentResized() calculate width step by step (and it's called multiple times), gradually decreases width by some amount of pixels till it reach real window size. It's behave in that way even thow I change window size in one step from maximum size to 800. Whole process is so slow, that it takes around a second to fit string to window size. So it looks bit like an animation.
The problem is very rare to me, bacause width in componentResized() method is calculeted step by step only when I assign windowSize variable.
When I give windowSize fixed size like for example 500 - componentResized() is called only onces - with correct width indicated real window size (!!) - and there's no its step by step decrease!
It's look like width variable which is assigned by ((JPanel) evt.getSource()).getWidth() knows that windowSize is used to dynamically change size of JLabel component even before first call of refresh() method.
If anyone have an idea what is going on here - I will be very appreciate for help.
You may be able to adapt one of the approaches shown here to better effect. As shown here, the ellipsis is supplied by the label's UI delegate via a call to SwingUtilities2.clipString(), which appends the clipString. Rather than re-invent the label UI, use TextLayout to determine the required geometry, prepend the ellipsis, and handle the alignment in a table or list renderer, as shown here.
I load a text in a JTextPane and automatically every line takes the max number of words it can. When I decrease the Font size text just zoom out and all lines are half empty. How can I auto resize the text so every line is filled no matter what size of Font I use?
The code for changing font is
JComboBox cb =(JComboBox)evt.getSource();
String Selection =(String)cb.getSelectedItem();
int n = Integer.parseInt(Selection);
Font font = new Font("Monospaced", Font.PLAIN, n);
editPane.setFont(font);
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