Can't align JKabel - alignment

Well, I have this code:
static class things implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame4 = new JFrame("More things");
frame4.setVisible(true);
frame4.setResizable(true);
frame4.setSize(1366,730);
JPanel panel = new JPanel();
JLabel label = new JLabel("<html>One thing more</html>");
label.setVerticalAlignment(SwingConstants.BOTTOM);
label.setHorizontalAlignment(SwingConstants.RIGHT);
panel.add(label);
frame4.add(panel);
}
}
But when I run it, the JLabel with the Vertical/horizontal alignment isn't align, why?

That happens because of LayoutManager. Read more about using different LayoutManager's
1)JPanel use FlowLayout as default. Set to right aligning components for that with help of constructor.
2)JFrame use BorderLayout as default. Add your panel to it with parameter BorderLayout.SOUTH.
3) useframe4.setVisible(true); at the end of construction of GUI for avoiding artifacts.
4)use pack()method instead of setting size to JFrame.
JFrame frame4 = new JFrame("More things");
frame4.setResizable(true);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JLabel label = new JLabel("<html>One thing more</html>");
panel.add(label);
frame4.add(panel,BorderLayout.SOUTH);
frame4.pack();
frame4.setVisible(true);

Related

Scrolling issue on Vaadin 21 and ApplicationLayout

I have a strange problem with the application layout and views which need to be scrolled:
If I create an application with the default App Layout, the drawer toggle is on the top and I add a VerticalLayout with fullsize as view everything is working as expected. But if the vertical content exceeded the height of the browser window (even if I put this content into a scroller), the whole view get scrolled and disappears behind the toggle until the height of the toggle is reached, than scrolling stops.
It seams that setHeight(100, Unit.Percentage) does not considers the height of the toggle.
Has someone a similiar problem?
Edit
Put the following code as a view into an AppLayout and open this on your mobile device e.g. iPhone and you will see the vertical scroller:
#Route(value = "application/test", layout = ApplicationLayout.class)
#PageTitle("Test")
#RolesAllowed({"ROLE_NEWSLETTER_ADMIN", "ROLE_ORGANIZATION_ADMIN"})
public class TestView extends VerticalLayout implements BeforeEnterObserver {
private MenuBar menu;
private Grid<Person> grid;
private Label footerLabel;
public TestView() {
this.setSizeFull();
menu = new MenuBar();
menu.addItem("New");
menu.addItem("Edit");
menu.addItem("Delete");
this.add(menu);
grid = new Grid<>(Person.class);
this.add(grid);
this.expand(grid);
footerLabel = new Label("Number of objetcs: #");
this.add(footerLabel);
}
#Override
public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
}
}
AppLayout:
public class ApplicationLayout extends AppLayout implements AfterNavigationObserver {
private ApplicationService applicationService;
private H1 headerTitle;
public ApplicationLayout(ApplicationService applicationService) {
this.applicationService = applicationService;
createHeader();
createDrawer();
this.setPrimarySection(Section.DRAWER);
}
private void createHeader() {
// Define the header
HorizontalLayout header = new Header(new H1("Header"));
addToNavbar(header);
}
private void createDrawer() {
....
}
}
It seams that setHeight(100, Unit.Percentage) does not considers the height of the toggle.
Correct. The 100% is the size of the view port. So if you have e.g. the following
VerticalLayout vLayout = new VerticalLayout();
Button button = new Button();
button.setHeight(50, Unit.Pixels);
HorizontalLayout hLayout = new HorizontalLayout();
hLayout.setHeight(100, Unit.Percentage);
vLayout.add(button,hLayout);
This will produce something where vLayout height is more that viewport height and scroll bar emerges. Instead you should do.
VerticalLayout vLayout = new VerticalLayout();
Button button = new Button();
button.setHeight(50, Unit.Pixels);
HorizontalLayout hLayout = new HorizontalLayout();
hLayout.setHeight(200, Unit.Pixels);
vLayout.add(button,hLayout);
vLayout.expand(hLayout); // or vLayout.setFlexGrow(1.0d, hLayout);

Place .net control on the sheet

I am using spreadsheetgear, and I want to place the combobox (ComponentOne) into 1 cell. I want that when the user go to this cell, this combobox will activate and show the list to user. After user chose item on the list, it will place this item into the cell value and hide the combobox.
How to do it in Spreadsheetgear.
Thanks,
Doit
I am not familiar with ComponentOne controls, so cannot really speak for that portion of your question. However, regarding a more general approach to embedding custom controls onto a SpreadsheetGear WorkbookView UI control, this is possible by sub-classing the UIManager class, which would allow you to intercept the creation of existing shapes on a worksheet and replace them with your own custom controls.
Below is a simple example that demonstrates this with the Windows Forms WorkbookView control and a sub-class of SpreadsheetGear.Windows.Forms.UIManager. This example just replaces a rectangle AutoShape with a button. You could modify it to show a ComponentOne CheckBox instead.
Note that the UIManager.CreateCustomControl(...) method gets called anytime a shape is scrolled into view / made visible on the WorkbookView. Also note that that your custom control will be disposed of every time it is scrolled out of view or otherwise made invisible. Please see the documentation for more details on this API.
Another important point about shapes and worksheets in general--shapes are not embedded inside a cell. Instead they hover over cells. So there will be no explicit "link" between a given shape and a given cell. The closest you could come to making such an association is with the IShape.TopLeftCell or BottomRightCell properties, which will provide the ranges for which this shape's respective edges reside over. The IShape interface contains a number of other API that you might find useful in your use-case. For instance, you can hide a shape by setting the IShape.Visible property to false.
using System;
using System.Windows.Forms;
using SpreadsheetGear;
using SpreadsheetGear.Shapes;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Create the UIManager replacement.
new MyUIManager(workbookView1.ActiveWorkbookSet);
}
private void buttonRunSample_Click(object sender, EventArgs e)
{
// NOTE: Must acquire a workbook set lock.
workbookView1.GetLock();
try
{
// Get a reference to the active worksheet and window information.
IWorksheetWindowInfo windowInfo = workbookView1.ActiveWorksheetWindowInfo;
IWorksheet worksheet = workbookView1.ActiveWorksheet;
// Get a reference to a cell.
IRange cell = workbookView1.ActiveWorksheet.Cells["B2"];
// Add a placeholder shape to the worksheet's shape collection.
// This shape will be replaced with a custom control.
double left = windowInfo.ColumnToPoints(cell.Column) + 5;
double top = windowInfo.RowToPoints(cell.Row) + 5;
double width = 100;
double height = 30;
IShape shape = worksheet.Shapes.AddShape(AutoShapeType.Rectangle, left, top, width, height);
// Set the name of the shape for identification purposes.
shape.Name = "MyCustomControl";
}
finally
{
// NOTE: Must release the workbook set lock.
workbookView1.ReleaseLock();
}
buttonRunSample.Enabled = false;
}
// UIManager replacement class.
private class MyUIManager : SpreadsheetGear.Windows.Forms.UIManager
{
private Button _customControl;
public MyUIManager(IWorkbookSet workbookSet)
: base(workbookSet)
{
_customControl = null;
}
// Override to substitute a custom control for any existing shape in the worksheet.
// This method is called when a control is first displayed within the WorkbookView.
public override System.Windows.Forms.Control CreateCustomControl(IShape shape)
{
// If the shape name matches...
if (String.Equals(shape.Name, "MyCustomControl"))
{
// Verify that a control does not already exist.
System.Diagnostics.Debug.Assert(_customControl == null);
// Create a custom control and set various properties.
_customControl = new Button();
_customControl.Text = "My Custom Button";
// Add a Click event handler.
_customControl.Click += new EventHandler(CustomControl_Click);
// Add an event handler so that we know when the control
// has been disposed. The control will be disposed when
// it is no longer in the viewable area of the WorkbookView.
_customControl.Disposed += new EventHandler(CustomControl_Disposed);
return _customControl;
}
return base.CreateCustomControl(shape);
}
private void CustomControl_Click(object sender, EventArgs e)
{
MessageBox.Show("Custom Control was Clicked!");
}
private void CustomControl_Disposed(object sender, EventArgs e)
{
// Add any cleanup code here...
// Set the custom control reference to null.
_customControl = null;
}
}
}

Horizontally centering a popup window in Vaadin

I have added a popup window to my main UI as follows:
Window component = new Window();
UI.getCurrent().addWindow(component);
Now, I want my popup to be centered horizontally and e.g. 40 pixels from the top of the screen. As far as I can see Vaadin has 4 methods for positioning my window.
component.center()
component.setPosition(x, y)
component.setPositionX(x)
component.setPositionY(y)
None of these are really what I want. I was hoping at first that setPositionY might help me. This does allow me to get the right distance from the top, but the x-position is now set to 0, where I wanted it to be centered.
The setPosition might have helped if I was able to calculate what the x-position should be, but this would require me to know the width of the component in pixels, but component.getWidth just tells me 100%.
Next I tried to use CSS styling on the component, writing and explicit css rule and adding it to the component with addStyleName. It seems though that Vaadin overrides whatever I wrote in my css with its own defaults...
Any ideas how to get my Window component positioned correctly?
I used the methods getBrowserWindowWidth() and getBrowserWindowHeight() from the com.vaadin.server.Page class for this.
I centered my "log" window horizontally in the lower part of the browser window with
myWindow.setHeight("30%");
myWindow.setWidth("96%");
myWindow.setPosition(
(int) (Page.getCurrent().getBrowserWindowWidth() * 0.02),
(int) (Page.getCurrent().getBrowserWindowHeight() * 0.65)
);
Solution 1: Use SizeReporter
Indeed, setPositionY() will reset the window's centered property to false. As the width of your pop-up and that of your browser window are not know before they appear on the screen, the only way I know to get those values is to use the SizeReporter add-on. Its use is quite straightforward:
public class MyUI extends UI {
private Window popUp;
private SizeReporter popUpSizeReporter;
private SizeReporter windowSizeReporter;
#Override
protected void init(VaadinRequest request) {
Button button = new Button("Content button");
VerticalLayout layout = new VerticalLayout(button);
layout.setMargin(true);
popUp = new Window("Pop-up", layout);
popUp.setPositionY(40);
addWindow(popUp);
popUpSizeReporter = new SizeReporter(popUp);
popUpSizeReporter.addResizeListenerOnce(this::centerPopUp);
windowSizeReporter = new SizeReporter(this);
windowSizeReporter.addResizeListenerOnce(this::centerPopUp);
}
private void centerPopUp(ComponentResizeEvent event) {
int popUpWidth = popUpSizeReporter.getWidth();
int windowWidth = windowSizeReporter.getWidth();
if (popUpWidth == -1 || windowWidth == -1) {
return;
}
popUp.setPositionX((windowWidth - popUpWidth) / 2);
}
}
This piece of code will be okay as long as you don't resize the pop-up. If you do, it will not be automatically recentered. If you replace addResizeListenerOnce() by addResizeListener() then it will automatically recenter the pop-up but you'll get some "UI glitches" as the add-on sends resize events almost continually while you're resizing your pop-up...
You could try to do it using CSS, but I personally avoid CSS as much as I can with Vaadin :).
You'll need to recompile the widgetset after you've added the add-on as a dependency.
Solution 2: Use com.vaadin.ui.JavaScript
I won't vouch for the portability of this solution but I guess it will work on most modern browsers.
public class MyUI extends UI {
private Window popUp;
#Override
protected void init(VaadinRequest request) {
Button button = new Button("Content button");
VerticalLayout layout = new VerticalLayout(button);
layout.setMargin(true);
popUp = new Window("Pop-up", layout);
popUp.setPositionY(40);
popUp.addStyleName("window-center");
addWindow(popUp);
// Add a JS function that can be called from the client.
JavaScript.getCurrent().addFunction("centerWindow", args -> {
popUp.setPositionX((int) ((args.getNumber(1) - args.getNumber(0)) / 2));
});
// Execute the function now. In real code you might want to execute the function just after the window is displayed, probably in your enter() method.
JavaScript.getCurrent().execute("centerWindow(document.getElementsByClassName('window-center')[0].offsetWidth, window.innerWidth)");
}
}

Width of child vertical layout

I have a HorizontalLayout (let's call it parent). Inside this I have two VerticalLayouts (left's call them left and right).
Left contains just some text, right contains a lot of elements.
Parent has a width of 100% so it takes the full browser width:
parent.setWidth("100%");
Left should take just as much space as it needs, right should take all other space.
How can I do so? I tried all variations described here and there without success. I tried to:
left.setWidthUndefined();
right.setWidth("100%");
left.setWidth("150px");
left.setWidth("30%"); together with right.setWidth("70%");
Nothing had an effect.
Updated source code:
HorizontalLayout parent = new HorizontalLayout();
parent.setCaption("Parent");
VerticalLayout left = new VerticalLayout();
left.setCaption("Left");
VerticalLayout right = new VerticalLayout();
right.setCaption("Right");
parent.addComponent(left);
parent.addComponent(right);
parent.setWidth("100%");
right.setWidth("100%");
parent.setExpandRatio(right, 1.0f);
setCompositionRoot(parent);
I just did a quick test, and the following seems to work:
...
left.setSizeUndefined();
parent.setWidth("100%");
parent.setExpandRatio(right, 1);
...
This is the full code of the test application (without imports):
#Theme("reindeer")
public class ForumUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = ForumUI.class)
public static class Servlet extends VaadinServlet {
}
public static class SomeComponent extends CustomComponent {
public SomeComponent() {
HorizontalLayout parent = new HorizontalLayout();
parent.setCaption("Parent");
parent.addStyleName("v-ddwrapper-over");
VerticalLayout left = new VerticalLayout();
left.setCaption("Left");
left.addStyleName("v-ddwrapper-over");
VerticalLayout right = new VerticalLayout();
right.setCaption("Right");
right.addStyleName("v-ddwrapper-over");
parent.addComponent(left);
parent.addComponent(right);
left.setSizeUndefined();
parent.setWidth("100%");
parent.setExpandRatio(right, 1);
setCompositionRoot(parent);
}
}
#Override
protected void init(VaadinRequest request) {
setContent(new SomeComponent());
}
}
Here is the documentation for the space "distribution" of the HorizontalLayout component.
The key to solve your problem is to tell the HorizontalLayout component how to expand it's childrens via the layout.setExpandRatio(leftComponent, 1.0f); method.

How to create a custom dialog

I need to create yes/no confirmation dialog in a foreign language. I think I need to create my own class by extending Dialog ?
Thanks
this should do the trick. My apologies to any Swedish chefs watching.
int answer = Dialog.ask("Gersh gurndy morn-dee burn-dee, burn-dee, flip-flip-flip-flip-flip-flip-flip-flip-flip?", new String[] {"Hokey dokey","Bork bork bork"}, new int[] {Dialog.OK,Dialog.CANCEL}, Dialog.CANCEL);
Edits:
The above explained better:
public final static int NEGATIVE = 0;
public final static int AFIRMATIVE = 1;
public final static int DEFAULT = NEGATIVE;
int answer = Dialog.ask("question?", new String[] {"afirmative button label", "negative button label"}, new int[] {AFIRMATIVE,NEGATIVE}, DEFAULT);
As you can see from the above it is possible to change all the text (language) values on a Dialog just by using this method so you shouldn't need a custom class to create a Dialog in another language.
It's even simpler if you use the standard BB localizing approach the simpler method (Dialog.ask(res.getString(SOMEQUESTION)) will automatically have it's afirmative and negative buttons adjusted for the language set in the phones options. You will only need to add the question as a string resource.
You can find a list of valid methods and constructors here:
http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/ui/component/Dialog.html
More Edits below:
I thought my above answer was what you were after but if you do need to further customize the dialog in a new class you may do it like this:
public class MyDialogScreen extends MainScreen implements LocalResource {
private int exitState;
...
protected void sublayout( int width, int height ) {
setExtent( dialogWidth, dialogHeight );
setPosition( XPOS, YPOS );
layoutDelegate( dialogWidth, dialogHeight );
}
// do some stuff and assign exitState appropriately
// e.g. a button that sets exitState = 1 then pops this screen
// another button that sets exitState = 2 then pops this screen
...
public int getExitState()
{
return this.exitState;
}
In the above I've created a new screen and I have overridden the sublayout method to specify a custom width, height and xy positions in layoutDelegate. When you push this screen you will see it as a dialog like box above the previous screen on the stack at the XY positions you specified.
Make sure to use pushModal. This will allow you to access the getExitState method after the screen has been popped from the display stack.
E.g
MyDialogScreen dialog = new MyDialogScreen();
UiApplication.getUiApplication().pushModalScreen(dialog);
int result = dialog.getExitState();
Cheers
Ray

Resources