So i have this existing method on our project which defines the width and height of a widget using Dimension():
wProps.setBounds("Widget.frame.bounds", new Rectangle(WidgetStartPosition.getInstance().getStartPos(),new Dimension(getDefWidth(), getDefHeight())))
But getDefWidth() and getDefHeight() both retrieves hard coded values.
example: int height = 360; int width = 210;
public void setBounds(String key, Rectangle r)
{
if (key == null || "".equals(key) || r == null)
return;
try
{
JSONObject jObject = new JSONObject();
jObject.put(X, r.x);
jObject.put(Y, r.y);
jObject.put(WIDTH, r.width);
jObject.put(HEIGHT, r.height);
getLocalJSONObject().put(key, jObject);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
because i noticed if the width and height for new Dimension() are both hard coded. Then if the width of content of the widget is more than the width defined in the new Dimension(), the content would be truncated and cut.
What i want to do is to set values in Dimension() depending on the total width and total height of whatever the content will be of the widget since the content of the widget changes every day. Is that possible?
Don't hardcode width/height values of any Swing component. Each component is responsible for determining its own size and then a layout manager can do its job when determining the size/location of each component on a panel.
What i want to do is to set values in Dimension() depending on the total width and total height of whatever the content will be of the widget
You need to override the getPreferredSize() method of your component. This is a dynamic calculation that can be done whenever a property of your component changes.
So as the content changes the preferred size can also change. Think of a component like a JLabel. As the text changes its preferred size changes.
Related
I have column headers that use a VerticalTextPainter.
If I set setCalculateByTextHeight and setCalculateByTextLength to true is resizes the columns to fit all of the text inside the cells correctly.
Sometimes the headers will have a lot of text in them so I would like them to have a maximum height.
If I stop usingsetCalculateByTextHeight and setCalculateByTextLength then the cells aren't resized at all so they just show ....
How could I go about doing this?
Update
#Override
protected void setNewMinLength(ILayerCell cell, int contentHeight) {
final ILayer layer = cell.getLayer();
final int cellLength = cell.getBounds().height;
if (contentHeight < MAXIMUM_HEIGHT && cellLength < contentHeight) {
layer.doCommand(new RowResizeCommand(layer, cell.getRowPosition(), contentHeight));
} else {
layer.doCommand(new RowResizeCommand(layer, cell.getRowPosition(), MAXIMUM_HEIGHT));
}
}
Override paintControl in NatTable
#Override
public void paintControl(final PaintEvent event) {
super.paintControl(event);
/**
* After first time rendering we stop column/row headers calculating their
* height/lengths. This allows the user to resize the column/row headers after
* the NatTable has been rendered.
*/
if (firstRender) {
columnHeaderPainter.setCalculateByTextHeight(false);
columnHeaderPainter.setCalculateByTextLength(false);
rowHeaderPainter.setCalculateByTextHeight(false);
rowHeaderPainter.setCalculateByTextLength(false);
firstRender = false;
}
}
There is no build in mechanism to specify a max height or width. Either you configure that the height should be calculated based on the content or set a fixed height.
I think you could achieve this by subclassing the VerticalTextPainter and overriding setNewMinLength() to only execute a RowResizeCommand if the contentHeight is bigger than the cellLength and the cellLength is not bigger than your maximum. And of course the RowResizeCommand should only resize to your specified maximum then.
Performing the check on any other place would probably result in an endless processing of cell height resizing.
I am creating a jlist in java where I want to be height of list to be dynamic according to number of rows in the list:
I mean when there are no rows in the list, it should not show that empty list box, (I want to set jlist minimum height to be 0)
I want to set the maximum height of list to be fixed, when the rows exceed that maximum height it should start scrolling the jlist
when the list occupies a smaller height than the maximum height size, it should only show up to those space which were occupied by rows (I mean no empty space should be shown on the list)
I've already created a jlist, but it is showing empty space when the number of rows occupies a smaller space than the maximum list space height.
You can override the getPreferredSize() method to return the size based on your requirements.
But first you would need to do:
list.setVisibleRowCount(???);
This will allow the default preferred size calculation to calculate the size of your list before the scrollbars appear.
Then you need to modify the getPreferredSize() method of the JList. It might look something like:
#Override
public Dimension getPreferredSize()
{
Dimension d = super.getPreferredSize();
int rows = getModel().getSize();
if (rows < getVisibleRowCount())
{
int rowHeight = d.height / getVisibleRowCount();
d.height = rows * rowHeight;
}
return d;
}
I have a JTextPane with content type "text/html". It is integrated in a JScrollPane.
The user can scroll down in this JTextPane and hits a button. At this moment I want to compute the topmost actual visible line of the JTextPane!
What I found in another post here where these lines:
public Integer getActualDisplayedRows() {
int y1 = jtextpane.getVisibleRect().y;
int lineHeight = jtextpane.getFontMetrics(jtextpane.getFont()).getHeight();
int topMostRow = (int) Math.ceil((double) y1 / lineHeight);
return topMostRow;
}
But this does not compute correct.. The number in lineHeight is too small. So, if I scroll to the 20th row -for example- the method returns more then 20..
I tried to set the height of the line via stylesheet (like here):
StyleSheet sh = editorKit.getStyleSheet();
sh.addRule("body {line-height: 50px}");
But doesn't matter what pixel number I set there, the resulting JTextPane has always the same height (and I am using the body tag)..
Do you have any suggestions??
Thank you very much for your help!
If I understand your requirement you just want to know the line number at the top of the viewport?
Here is some code for getting the line at the caret position:
public static int getLineAtCaret(JTextComponent component)
{
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex( caretPosition ) + 1;
}
Don't know if this will work for HTML with all kinds of weird tags with images and tables etc. In this case I'm not sure what the meaning of "line" would be.
Now obviously the caret will not be at the top of the viewport, so you need to modify the logic to get an "offset" of the text at the top of the viewport.
So you should be able to use the viewToModel(...) method of the text pane. Something like:
int y = textPane.getVisibleRect().y;
Point p = new Point(5, y);
int offset = textPane.viewToModel( p );
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 want old and new height, width of window on window re-size event.
How I can do that, I am just getting new height and width on window re-size.
Thanks in advance
There is no way to get old dimensions in the ResizeEvent received when the window size changes. But you can save old values attributes inside your ResizeHandler.
Window.addResizeHandler(new ResizeHandler() {
// Save old dimensions
int oldW = Window.getClientWidth(), oldH = Window.getClientHeight();
public void onResize(ResizeEvent ev) {
// Get new dimensions
int newW = ev.getWidth(), newH = ev.getHeight();
// Do something with old and new dimensions
myResizeMethod(oldW, newW, oldH, newH);
// Update old dimensions
oldW = newW; oldH = newH;
}
});
Additional info: Window class tracks old sizes in order to fire the resize event only in case new values are different to old ones, so it will be ease to add those values to the ResizeEvent object. You can either request or send a patch to GWT with this feature.