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
Related
I've been trying to make a 9x9 grid of textFields, where each textField is allocated to an element in a 2d array. For example the top left textField is field[0][0], the one right of that is field[1][0], and the bottom right textField is field[8][8].
So far I have
TextField[][] fields = new TextField[9][9]; {
for (Y=0;Y<9;Y++) {
XPosition=0;
for (X=0;X<9;X++) {
fields[X][Y] = new TextField(1);
fields[X][Y].setColumns(1);
fields[X][Y].setBounds(XPosition, YPosition ,32, 32);
frame.getContentPane().add(fields[X][Y]);
XPosition=XPosition+32;
}
YPosition = YPosition+32;
}
}
For some reason when I run the program, only the first 5 textFields in the top row get created. I have a feeling all the other textFields are placed under the visible ones. The frame is definitely big enough, and I can't figure out any issues with the code.
Use a grid layout : https://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html
Absolute positioning is not reliable.
Adding
frame.getContentPane().setLayout(null);
has fixed the error
I have a JPanel in which I need to add bunch of JLabels at a required coordinates. These JLabels will have key Listeners assigned to them that will determine new position using arrow keys.
To be more specific I know how to do it when there is only one JLabel but whenever I put a more of them the things mess up. while I use arrow key the first JLabel moves but all other JLabel disappears.
Can Anyone give me some hints to write a method to put a JLabel in a specific coordinate and also move them using arrow key later without making other JLabels dissapear?
Huge Thanks in Advance
You can try using JDesktopPane or JLayeredPane, it works the same as the JPanels, but you won't use layouts, with these you will use Bounds, you always have to set the bound of a jlabel like this.
JLabel label = new JLabel("Hello");
label.setBounds(0, 0, 100, 20);
//label.setBounds(x, y, width, height);
pane.add(label)
if you need to move that label, then you can use something like
int xx = label.getBounds().getX();
int yy = label.getBounds().getY();
int ww = label.getBounds().getWidth();
int hh = label.getBounds().getHeight();
//to the right 10 units
xx+=10;
label.setBounds( xx, yy, ww, hh );
I assume you are using repaint() to update the UI. Btw, upon which component you are calling repaint()?
I'm developing a webapplication in the Vaadin framework.
I have a table with 14 columns. The last column holds three icons and a problem I'm having is that like half of the time the table is rendered the icon furthest to the right will be "cut in half" vertically. To avoid this problem I tried to set a fixed width to this column that I think would eradicate the problem, however, nothing happens..
I'm using the conventional approach:
simCardTable.setColumnWidth(actionColumn, 135);
However, no matter what value I set to be the column width the column stays the same... Does anyone know why this is? Is it because it's the last column to be added and therefore there's no space to spare..?
Btw, that is the only column I set a specific width to, all of the restoring columns have a the standard width specified by the width of the column header or the cell content.
Any help would be very appreciated!
As i understand from your question ("The last column holds three icons") you use ColumnGenerator to create this last column, with icons. If I right, it mean that you created some sort of custom layout with this icons inside, in this case for you should work this:
final ColumnGenerator generator = new ColumnGenerator() {
private static final long serialVersionUID = 1L;
#Override
public Component generateCell(Table source, final Object itemId, Object columnId) {
final HorizontalLayout layout = new HorizontalLayout();
layout.setSizeFull();
Embedded icon1 = new Embedded();
Embedded icon2 = new Embedded();
Embedded icon3 = new Embedded();
//Add some themeresource to embedded components
//Do some listners to this icons
layout.addComponent(icon1);
layout.addComponent(icon2);
layout.addComponent(icon3);
//Set column with
setColumnWidth(columnId, 100);
return layout;
}
};
In all the examples that I can find that use a JTextArea, the height & width is known before constructing the JTextArea, and if the JTextArea would require more height, then it is put inside of a JScrollPane. Obviously, the height of JTextArea is dependent on the width and the text contents.
Now, my situation requires that I do not use a JScrollPane, but instead that the JTextArea be just tall enough to display all the text. When I create the JTextArea, I know the text contents and how much width it will have to work with; I don't know the height - I want that to be as small as possible without cutting off any of the text. This seems very difficult to accomplish.
As a side note, the JTextArea will be added to a JPanel that does not have a layout manager - it uses absolute positioning based on the added component's preferred size. This requires that my JTextArea would return the correct dimensions on getPreferredSize(). The correct dimensions should be the width that I provided when I constructed it, and the minimum height that is required to display all the text with the provided width.
I've found some similar threads that discuss the oddities/bugs involved with the JTextArea that are sometimes solved by calling pack() twice on the parent container. This is not an option for me. I'm tempted to basically create my own JTextArea that takes a width and String and computes the necessary minimum height based on the width and font settings, but I figured I would ask around first before spending the time to do that.
Hopefully my question is clear. Thank you all for your help!
it uses absolute positioning based on the added component's preferred size.
Sounds like the job of a layout manager.
This requires that my JTextArea would return the correct dimensions on getPreferredSize().
JTextArea textArea = new JTextArea();
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setText("one two three four five six seven eight nine ten");
System.out.println("000: " + textArea.getPreferredSize());
textArea.setSize(100, 1);
System.out.println("100: " + textArea.getPreferredSize());
textArea.setSize( textArea.getPreferredSize() );
import java.awt.*;
import javax.swing.*;
class FixedWidthLabel {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
String pt1 = "<html><body width='";
String pt2 =
"px'><h1>Label Height</h1>" +
"<p>Many Swing components support HTML 3.2 &" +
" (simple) CSS. By setting a body width we can cause the " +
" component to find the natural height needed to display" +
" the component.<br><br>" +
"<p>The body width in this text is set to " +
"";
String pt3 =
" pixels." +
"";
JPanel p = new JPanel( new BorderLayout() );
JLabel l1 = new JLabel( pt1 + "125" + pt2 + "125" + pt3 );
p.add(l1, BorderLayout.WEST);
JLabel l2 = new JLabel( pt1 + "200" + pt2 + "200" + pt3 );
p.add(l2, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, p);
}
};
SwingUtilities.invokeLater(r);
}
}
The solution described in FixedWidthLabel , using <html><body width="..."
will require the programmer to provide the message as part of the html string.
If the message is something like invalid integer: i<0 not allowed ,
then the < will have to be escaped (encoded?), otherwise there is no telling how JLabel will interpret the html.
This adds complexity to this solution.
Only if you know that the message doesn't contain any such characters, you will be allright.
Well perhaps if you know your width you could run some tests and work out how wide each character of text is, that way you could use a loop to determine how many characters fit on each line and total the characters that are to be shown, then you could set the height based on how many lines there are to be.
Say your text has 1000 characters including blank spaces, and the width of a character is equivalent to 4pixels, then you can work out if the width is 400 that 100 characters fit on each line, subsequently you will need 10 lines. Now say the height is 10 for the font size, you now know you need 10 x 10 == 100 pixels, so your TextArea should be 400x100
I'm trying to make a Swing JLabel with multiple lines of text. It's added just fine, but the line breaks don't come through. How do I do this? Alternatively, can I just specify a maximum width for a JLabel and know that the text would wrap, like in a div?
private void addLegend() {
JPanel comparisonPanel = getComparisonPanel();
//this all displays on one line
JLabel legend = new JLabel("MMM FFF MMM FFFO O OOM M MMMM.\nMMM FFF MMM FFFO O OOM M MMMM.\nMMM FFF MMM FFFO O OOM M MMMM.\n");
comparisonPanel.add(legend);
}
Use HTML in setText, e.g.
myLabel.setText("<html><body>with<br>linebreak</body></html>");
You can get automatic line break if you set the paragraph width in html.
label.setText("<html><p style=\"width:100px\">"+paragraph+"</p></html>");
By default, Swing does not wrap text. If you specify a size on the JLabel it will only paint the part of the text that fits and then add "..." to the end.
As suggested you can use HTML to enable line wrapping. However, I've actually created a custom Swing UI delegate not long ago to achieve this and even more: MultiLineLabelUI.
It will wrap your text to fit the available space and also respect hard line breaks. If you choose to try it out, it is as simple as:
JLabel label = new JLabel("Text that'll wrap if necessary");
label.setUI(MultiLineLabelUI.labelUI);
Or alternatively use the custom MultiLineLabel class that in addition to wrapping text supports vertical and horizontal text alignment.
UPDATE
I lost the domain with the original code samples. It can now be viewed on github instead: https://github.com/sasjo/multiline
You can put HTML inside of a JLabel and use the linebreak tag to achieve this.
What about using the wrapping feature in a JTextArea?
String text = "some really long string that might need to"+
"be wrapped if the window is not wide enough";
JTextArea multi = new JTextArea(text);
multi.setWrapStyleWord(true);
multi.setLineWrap(true);
multi.setEditable(false);
JLabel single = new JLabel(text);
JPanel textpanel = new JPanel(new GridLayout(2,1));
textpanel.add(multi);
textpanel.add(single);
JFrame frame = new JFrame();
frame.add(textpanel);
frame.pack();
frame.setVisible(true);
Simple,use HTML. Java Swing components though does not provide a 'fantastic' support for the HTML, you can use it for such simple purposes.
label.setText("<html>This is first line.<br/>This is second line.</html>");
I did not manage to specify a maximum width for a label but you can specify a concrete width.
By measuring the current width of a JLabel we can only apply the new fixed width if the JLabels's width is higher that our maxWidth:
JLabel label = new JLabel("<html>" + myVeryLongMessage + "<html>");
int maxWidth = 400;
Dimension size = label.getPreferredSize();
if (size.width > maxWidth) {
// Estimate the number of lines
int lineCount = (int) Math.ceil(((double) size.width) / maxWidth);
lineCount += 1; // Add one extra line as reserve
size.width = maxWidth; // Apply the maximum width
// Increase the height so that all lines will be visible
size.height *= lineCount;
label.setPreferredSize(size);
}
You can use a JTextArea and disable the TextArea, this way, you will only display what you want, and the user won't be able to type in
JTextArea area = new JTextArea("Here \n\n you \n\n put \n\n your \n\n text");
area.setBounds(10, 11, 500, 143);
area.setEditable(false);
yourPannel.add(area);