How to programmatically set the split position of BorderLayout in GXT? - gwt

I have a border layout set on a widget using Ext-GWT. Is there a way where I can set the 'split' position automatically? Reason being, if the user resizes a control on a page (not necessarily the parent of the one the split widget is in), I'd like to set the split value to a certain percentage value (like 30%). How can this be done?
Here's the existing code:
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.google.gwt.user.client.Element;
public class BorderLayoutExample extends LayoutContainer {
setSplitPositionTo(float percentage) {
// TODO: How to do this?
}
protected void onRender(Element target, int index) {
super.onRender(target, index);
final BorderLayout layout = new BorderLayout();
setLayout(layout);
setStyleAttribute("padding", "10px");
ContentPanel west = new ContentPanel();
ContentPanel center = new ContentPanel();
//uncomment this section if you dont want to see headers
/*
* west.setHeaderVisible(false);
* center.setHeaderVisible(false);
*/
BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 150);
westData.setSplit(true);
westData.setCollapsible(true);
westData.setMargins(new Margins(0,5,0,0));
BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
centerData.setMargins(new Margins(0));
add(west, westData);
add(center, centerData);
}
}

This one was fairly tricky
You'll need to get access to a non center layoutdata and widget for the border layout.
(As center is calculated via remaining space).
Then make them available to the setSplitPositionTo method.
In my example I made them members on the class.
In the end my method looks as follows and a call like myBorderLayoutInstance.setPlitPositionTo(0.4f);
works like a charm using the example you provided and this amendment.
BorderLayoutData westData;
ContentPanel west;
void setSplitPositionTo(float percentage) {
westData.setSize(percentage);
Component c = west;
Map<String, Object> state = c.getState();
state.put("size", westData.getSize());
c.saveState();
layout(true);
}

Related

Why is draw_picture called so many times?

When I run the following programme:
//compile: valac --pkg gtk+-3.0 sample.vala
using Gtk;
public class Main : Object
{
private Window window;
private Gdk.Pixbuf pixbuf;
private DrawingArea da1;
public Main()
{
window = new Window();
window.destroy.connect (main_quit);
pixbuf = new Gdk.Pixbuf.from_file("sample.jpg");
var box = new Box (Orientation.VERTICAL, 5);
da1 = new DrawingArea();
da1.set_hexpand(true);
da1.set_vexpand(true);
da1.draw.connect((context) => draw_picture(context, pixbuf));
box.pack_start (da1, true, true, 0);
window.add (box);
window.show_all();
}
bool draw_picture(Cairo.Context cr, Gdk.Pixbuf pixbuf)
{
print("draw_picture\n");
int width = da1.get_allocated_width();
int height = da1.get_allocated_height();
var temp = pixbuf.scale_simple(width, height, Gdk.InterpType.BILINEAR);
Gdk.cairo_set_source_pixbuf (cr, temp, 0, 0);
cr.paint ();
return false;
}
static int main(string[] args)
{
Gtk.init(ref args);
var app = new Main();
Gtk.main();
return 0;
}
}
after start I can see 'draw_picture' printed 2 times. When I switch window to terminal, it's displayed additional 7 times. Can anyone explain why and recommend some good book explaining the details?
In order to answer that question for sure, you would need to look at how your window manager works. Probably the redraws that occur when you switch to another window are due to the widget gaining the :backdrop pseudoclass when its window ceases to be the active window.
In general a widget's draw signal is invoked whenever the window manager needs to redraw a portion of the window that includes the widget, and also whenever the widget's active style changes.
If your widget is expensive to redraw then you can avoid drawing the whole thing when it's not necessary. The Cairo context's clip region will be set to the portion which needs redrawing.

iText Background Opacity

I want to overlay a text with semi-transparent background over an existing text using iText 7. Setting the background opacity for a text element doesn't seem to work (line 1), I can only set it for the whole paragraph (line 2):
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import java.io.IOException;
public class TextBackgroundOpacityTest {
public static void main(String[] args) throws IOException {
try (Document doc = new Document( new PdfDocument(new PdfWriter("TextBackgroundOpacityTest.pdf")))) {
doc.add(new Paragraph(new String(new char[130]).replace("\0", "A")));
// opacity doesn't work for text element
doc.showTextAligned(new Paragraph(new Text("missing background transparency").setBackgroundColor(ColorConstants.WHITE, .8f)), 500, 805, 0, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
// opacity for the whole paragraph works, but this is not what I want
doc.showTextAligned(new Paragraph("whole pharagraph background transparancy").setBackgroundColor(ColorConstants.WHITE, .8f), 500, 785, 0, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
}
}
}
How can I overlay a text with a semi-transparent background as show in line 2, but just for the overlayed text, not the whole paragraph? Desired output:
To work around the solution you can use custom renderers. If you look at the BlockRenderer#drawBackground which is called in case you set transparent background to a paragraph you can see the following lines there:
TransparentColor backgroundColor = new TransparentColor(background.getColor(), background.getOpacity());
drawContext.getCanvas().saveState().setFillColor(backgroundColor.getColor());
backgroundColor.applyFillTransparency(drawContext.getCanvas());
TextRenderer, however, has its own implementation and does not respect transparent background. But we can customize the renderer implementation. We'll need to copy-paste quite a bit of code from the current TextRenderer implementation, but the good news is that we don't need to change a lot of code. Just insert two lines in the right place:
TransparentColor backgroundColor = new TransparentColor(background.getColor(), background.getOpacity());
backgroundColor.applyFillTransparency(drawContext.getCanvas());
Overall we get the following implementation:
private static class TextRendererWithBackgroundOpacity extends TextRenderer {
public TextRendererWithBackgroundOpacity(Text textElement) {
super(textElement);
}
#Override
public void drawBackground(DrawContext drawContext) {
Background background = this.<Background>getProperty(Property.BACKGROUND);
Float textRise = this.getPropertyAsFloat(Property.TEXT_RISE);
Rectangle bBox = getOccupiedAreaBBox();
Rectangle backgroundArea = applyMargins(bBox, false);
float bottomBBoxY = backgroundArea.getY();
float leftBBoxX = backgroundArea.getX();
if (background != null) {
boolean isTagged = drawContext.isTaggingEnabled();
PdfCanvas canvas = drawContext.getCanvas();
if (isTagged) {
canvas.openTag(new CanvasArtifact());
}
boolean backgroundAreaIsClipped = clipBackgroundArea(drawContext, backgroundArea);
canvas.saveState().setFillColor(background.getColor());
TransparentColor backgroundColor = new TransparentColor(background.getColor(), background.getOpacity());
backgroundColor.applyFillTransparency(drawContext.getCanvas());
canvas.rectangle(leftBBoxX - background.getExtraLeft(), bottomBBoxY + (float) textRise - background.getExtraBottom(),
backgroundArea.getWidth() + background.getExtraLeft() + background.getExtraRight(),
backgroundArea.getHeight() - (float) textRise + background.getExtraTop() + background.getExtraBottom());
canvas.fill().restoreState();
if (backgroundAreaIsClipped) {
drawContext.getCanvas().restoreState();
}
if (isTagged) {
canvas.closeTag();
}
}
}
#Override
public IRenderer getNextRenderer() {
return new TextRendererWithBackgroundOpacity((Text)modelElement);
}
}
To make Text element use the custom renderer implementation just call setNextRenderer method:
Text customTextElement = new Text("missing background transparency");
customTextElement.setNextRenderer(new TextRendererWithBackgroundOpacity(customTextElement));
By the way you are very welcome to file the fix as a pull request to iText (please follow the contribution guidelines though). The repository is located at https://github.com/itext/itext7

Adding label to PolylineConnection in Draw2D

I'm trying to add a label to a PolylineConnection in Draw2d. I'm using the example in java2s as a basis. The problem is that even if I can create the text by using graphics.drawText() on the paintFigure method from the PathFigure object (that extends PolylineConnection), the label is cut out most of the time, as shown in these captures:
To me, it looks like the bounds of the figure are leaving part of the text outside from the paint area, as it does indeed paint correctly in diagonal arrows, which have bigger bounds.
I have tried to set explicitly the bounds of the object, both in constructor and paint methods, but it seems like the PolylineConnection is ignoring them. Any idea of how to solve this or if there is another way of achieving this kind of label?
Please use below figure for your connection figure.
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MidpointLocator;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
public class LabelConnectionFigure extends PolylineConnection {
protected Label label;
public LabelConnectionFigure() {
setTargetDecoration(new PolygonDecoration());
MidpointLocator labelLocator = new MidpointLocator(this, 0);
label = new Label("1");
label.setOpaque(true);
add(label, labelLocator);
}
public void setLabelText(String labelText) {
label.setText(labelText);
}
public String getLabelText() {
return label.getText();
}
}

Images getting cut off using Swing

I am writing a tile based platform game. At the moment I am trying to get 400 tiles to display at once. This is my panel. On the top and left sides everything is working great but on the right and bottom sides the images are cut off by a few pixels. Each image is 32*32. All of blocks are initialized. None are null. What is wrong here?
public class Pane extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
Timer timer;
boolean setup = false;
Block[][] blocks;
Level level;
public Pane()
{
level = new Level();
level.Generate();
blocks = level.Parse();
setBackground(Color.WHITE);
timer = new Timer(25, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(Block[] b : blocks)
{
for(Block bx : b)
{
// Debug code if(bx.letter.equals("D"))
// Debug codeSystem.out.println(bx.y*32 +" = "+ bx.x*32);
g2d.drawImage(bx.bpic, bx.x*32, bx.y*32, this);
}
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
on the right and bottom sides the images are cut off by a few pixels
If you mean the right and bottom sides of the whole panel (not on the single tiles), than it's probably a LayoutManager related problem. The solution depends on the layout manager you are using for the component your JPanel will be added to.
You could try to specify the minimum/preferred size of your JPanel with:
Pane pane = new Pane();
pane.setPreferredSize(...);
pane.setMinimumSize(...);
In order to specify its minimum dimension accordingly to the size of the generated image (32 * COL , 32 * ROW).
Unfortunately the effectiveness of the setPreferredSize call depends on the layout manager of your Pane parent component.
JComponent can do that basically and can return very easily something as MinimumSize or PreferredSize, valid for majority of standard Swing LayoutManagers, examples here.

How to create a GEF figure with separate label?

I've been trying to create a Draw2D Figure that consists of two parts - a central resizeable shape, such as a circle or rectangle, and an editable label for the bottom part. An example of this type of figure is the icon/label you see on a computer's Desktop.
The first attempt was to create a parent container figure with two child sub-figures - a shape figure placed centrally and a label placed at the bottom. It also implemented HandleBounds so that selection and resizing occurs only on the upper shape sub-figure. This turned out not to be a working solution because as the label gets wider with more text so does the main parent figure and consequently the central shape figure. In other words the overall parent figure is as wide as the child label figure.
What I'm seeking is a Figure that maintains the size of the shape figure but allows the width of the label figure to grow independently. Exactly the same behaviour as a desktop icon.
Ok I get your question right now. It's impossible to do what you want:
The parent figure can't be smaller than one of its children or this child will not be visible !!!
You have to create a container figure as you mentioned with an XYLayout and "manually" place and "size" the 2 (the shape and the label) children figure inside this layout using the IFigure.add(IFigure child, Object constraint) method with a Constraint of type Rectangle (Draw2d)
Edit with code sample
Here is an example of what your figure class could look like:
package draw2dtest.views;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureListener;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Rectangle;
public class LabeledFigure extends Figure {
private final Figure shapeFigure;
private final Label labelFigure;
private Rectangle customShapeConstraint;
public LabeledFigure(String label) {
setLayoutManager(new XYLayout());
setBackgroundColor(ColorConstants.lightGray);
setOpaque(true);
shapeFigure = new Ellipse();
this.add(shapeFigure);
shapeFigure.setBackgroundColor(ColorConstants.yellow);
shapeFigure.addMouseListener(new MouseListener.Stub() {
#Override
public void mousePressed(MouseEvent me) {
customShapeConstraint = new Rectangle(
(Rectangle) LabeledFigure.this.getLayoutManager()
.getConstraint(shapeFigure));
customShapeConstraint.width -= 6;
customShapeConstraint.x += 3;
LabeledFigure.this.getLayoutManager().setConstraint(
shapeFigure, customShapeConstraint);
LabeledFigure.this.revalidate();
}
});
labelFigure = new Label(label);
labelFigure.setOpaque(true);
labelFigure.setBackgroundColor(ColorConstants.green);
labelFigure.addMouseListener(new MouseListener.Stub() {
#Override
public void mousePressed(MouseEvent me) {
Rectangle shapeFigureConstraint = new Rectangle(0, 0,
bounds.width, bounds.height - 15);
LabeledFigure.this.getLayoutManager().setConstraint(
shapeFigure, shapeFigureConstraint);
LabeledFigure.this.revalidate();
}
});
this.add(labelFigure);
this.addFigureListener(new FigureListener() {
#Override
public void figureMoved(IFigure source) {
Rectangle bounds = LabeledFigure.this.getBounds();
Rectangle shapeFigureConstraint = new Rectangle(0, 0,
bounds.width, bounds.height - 15);
LabeledFigure.this.getLayoutManager().setConstraint(
shapeFigure, shapeFigureConstraint);
Rectangle labelFigureConstraint = new Rectangle(0,
bounds.height - 15, bounds.width, 15);
if (customShapeConstraint != null) {
labelFigureConstraint = customShapeConstraint;
}
LabeledFigure.this.getLayoutManager().setConstraint(
labelFigure, labelFigureConstraint);
}
});
}
}
This is not a clean class but it should be a good entry to show you how to achieve your goal. This is an example based on pure Draw2d without any Gef code, thus the resizing of the shape is done by clicking in the yellow Ellipse (the size is decreased) and on the green label (the initial size is restored)
To test this class I created a simple Eclipse view as following:
#Override
public void createPartControl(Composite parent) {
FigureCanvas fc = new FigureCanvas(parent, SWT.DOUBLE_BUFFERED);
fc.setBackground(ColorConstants.red);
Panel panel = new Panel();
panel.setLayoutManager(new XYLayout());
LabeledFigure labeledFigure = new LabeledFigure("This is the label");
fc.setContents(panel);
panel.add(labeledFigure, new Rectangle(10,10, 200,100));
}
Hope this can help,
Manu