Rectangle 27 3

1. Use a separate JS layout.

I've found two answers, but I wonder if there's a better way still. These answers are for Rails 3, by the way.

This is probably the "more correct" way, but unfortunately didn't work for my situation as I'll explain shortly.

What I wasn't fully aware of, is that in a JS request, the lookup formats are set to JS and HTML. Meaning that the controller will render the HTML template if the JS template does not exist.

But it will not look to the HTML layout in the same fashion, meaning the HTML template will be rendered, but the content_for block is never yielded to, leading to an empty response.

So to make the simple example above work out-of-the-box. You'd delete "show.js.erb" and add a JS layout, (e.g. "bars.js.erb") in the lookup path, which would look like this:

$("#foo").html("<% escape_javascript(yield(:foo)) %>");

In this way, the HTML template is rendered, but in the JS layout, and the HTML of #foo is swapped out for the new content of the response.

However, #1 this was not an ideal answer for me. My app uses many nested layouts, most of which are very similar. To make the above example work I'd have to create a lot of JS layouts, all of which more or less copies of the original HTML layouts. A waste of time, and not at all DRY. So I came up with this solution.

It feels less ideal than #1, and please tell me if there's a more appropriate way. But this is what I came up with:

# in bars_controller.rb
def show
  # ...
  respond_to do |format|
    format.js do
      lookup_context.update_details(:formats => [:html]) do
        @content = render_to_string
      end

      render
    end
  end
end

In this way I temporarily set the mimetype for the template lookup to be HTML, render the content to a variable, then render the JS template:

// show.js.erb
$("#foo").html("<%= escape_javascript(@content) %>");

There is one further complication to this. In my nested layout setup, in the HTML response, the layout calls the rendering of its parent to continue to build the body, leading to the complete page. In my case, I want it to simply return the body content. So while I don't need JS layouts for this solution, I do need to slightly change my layout, like this:

-# my_layout.html.haml

-# (given a parent layout that yields to :body)
- content_for :body do
  = yield(:foo)

- if request.xhr?
  = yield(:body)
- else
  = render :file => "layouts/my_parent_layout"

In this way the parent is not called on a JS request, simply resulting in the body (up to this point in the nested layout stack).

+1 Thanks for the render_to_string method. This will be very helpful :)

Glad to help. Please let me know if you have an issue with it, or if you come up with a nicer way to do the same thing :)

ruby - Rails: How do you render with a layout inside a JS template? - ...

ruby-on-rails ruby
Rectangle 27 65

1. No separate table with unique users

CREATE INDEX user_msg_log_combo_idx
ON user_msg_log (user_id, aggr_date DESC NULLS LAST)

To make index only scans possible, add the otherwise not needed column running_total:

CREATE INDEX user_msg_log_combo_covering_idx
ON user_msg_log (user_id, aggr_date DESC NULLS LAST, running_total)
DESC NULLS LAST

For few rows per user_id a simple DISTINCT ON is among the fastest solutions:

For many rows per user_id a loose index scan would be (much) more efficient. That's not implemented in Postgres (at least up to Postgres 10), but there are ways to emulate it:

users
LATERAL
WITH RECURSIVE cte AS (
   (  -- parentheses required
   SELECT user_id, aggr_date, running_total
   FROM   user_msg_log
   WHERE  aggr_date <= :mydate
   ORDER  BY user_id, aggr_date DESC NULLS LAST
   LIMIT  1
   )
   UNION ALL
   SELECT u.user_id, u.aggr_date, u.running_total
   FROM   cte c
   ,      LATERAL (
      SELECT user_id, aggr_date, running_total
      FROM   user_msg_log
      WHERE  user_id > c.user_id   -- lateral reference
      AND    aggr_date <= :mydate  -- repeat condition
      ORDER  BY user_id, aggr_date DESC NULLS LAST
      LIMIT  1
      ) u
   )
SELECT user_id, aggr_date, running_total
FROM   cte
ORDER  BY user_id;

This is preferable in current versions of Postgres and it's simple to retrieve arbitrary columns. More explanation in chapter 2a. below.

Convenient to retrieve either a single column or the whole row. The example uses the whole row type of the table. Other variants are possible.

WITH RECURSIVE cte AS (
   (
   SELECT u  -- whole row
   FROM   user_msg_log u
   WHERE  aggr_date <= :mydate
   ORDER  BY user_id, aggr_date DESC NULLS LAST
   LIMIT  1
   )
   UNION ALL
   SELECT (SELECT u1  -- again, whole row
           FROM   user_msg_log u1
           WHERE  user_id > (c.u).user_id  -- parentheses to access row type
           AND    aggr_date <= :mydate     -- repeat predicate
           ORDER  BY user_id, aggr_date DESC NULLS LAST
           LIMIT  1)
   FROM   cte c
   WHERE  (c.u).user_id IS NOT NULL        -- any NOT NULL column of the row
   )
SELECT (u).*                               -- finally decompose row
FROM   cte
WHERE  (u).user_id IS NOT NULL             -- any column defined NOT NULL
ORDER  BY (u).user_id;

It could be misleading to test the row value with c.u IS NOT NULL. This only returns true if every single column of the tested row is NOT NULL and would fail if a single NULL value is contained. (I had this bug in my answer for some time.) Instead, to assert a row was found in the previous iteration, test a single column of the row that is defined NOT NULL (like the primary key). More:

More explanation for this query in chapter 2b. below. Related answers:

Table layout hardly matters as long as we have exactly one row per relevant user_id. Example:

CREATE TABLE users (
   user_id  serial PRIMARY KEY
 , username text NOT NULL
);
SELECT u.user_id, l.aggr_date, l.running_total
FROM   users u
CROSS  JOIN LATERAL (
   SELECT aggr_date, running_total
   FROM   user_msg_log
   WHERE  user_id = u.user_id  -- lateral reference
   AND    aggr_date <= :mydate
   ORDER  BY aggr_date DESC NULLS LAST
   LIMIT  1
   ) l;

JOIN LATERAL allows to reference preceding FROM items on the same query level. You get one index (-only) look-up per user.

Consider the possible improvement by sorting the users table suggested by Gang Liang in another answer. If the physical sort order of the users table happens to match the index on user_msg_log, you don't need this.

You don't get results for users missing in the users table, even if you have entries in user_msg_log. Typically, you would have a foreign key constraint enforcing referential integrity to rule that out.

You also don't get a row for any user that has no matching entry in user_msg_log. That conforms to your original question. If you need to include those rows in the result use LEFT JOIN LATERAL ... ON true instead of CROSS JOIN LATERAL:

This form is also best to retrieve more than one rows (but not all) per user. Just use LIMIT n instead of LIMIT 1.

Effectively, all of these would do the same:

JOIN LATERAL ... ON true
CROSS JOIN LATERAL ...
, LATERAL ...

The latter has a lower priority, though. Explicit JOIN binds before comma.

Good choice to retrieve a single column from a single row. Code example:

The same is possible for multiple columns, but you need more smarts:

CREATE TEMP TABLE combo (aggr_date date, running_total int);

SELECT user_id, (my_combo).*  -- note the parentheses
FROM (
   SELECT u.user_id
        , (SELECT (aggr_date, running_total)::combo
           FROM   user_msg_log
           WHERE  user_id = u.user_id
           AND    aggr_date <= :mydate
           ORDER  BY aggr_date DESC NULLS LAST
           LIMIT  1) AS my_combo
   FROM   users u
   ) sub;

SQL Fiddle demonstrating all four queries. With a big test for 1k users and 100k log entries.

sql - Optimize GROUP BY query to retrieve latest record per user - Sta...

sql postgresql indexing greatest-n-per-group postgresql-performance
Rectangle 27 1

2. Use the editor template in your view.

Rather than dividing them into separate forms and recombining them, why not just create 1 well formatted form to submit? Welcome to the magical world of EditorTemplates!

/Views/Shared/EditorTemplates/Model_x.cshtml
[parent_root]/EditorTemplates/Model_x.cshtml
@model MyProject.Models.Model_x

@Html.LabelFor(model => model.prop_1)
@Html.EditorFor(model => model.prop_1)
@Html.ValidationMessageFor(model => model.prop_1)

...

@Html.LabelFor(model => model.prop_n)
@Html.EditorFor(model => model.prop_n)
@Html.ValidationMessageFor(model => model.prop_n)

They will replace your use of partials (which do not work well for forms) and will look something like this.

@model MyProject.Models.CompositeModel
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.EditorFor(model => model.Table1RowData)
    for (int i = 0; i < Model.Table2Rows.Count(); i++)
    {
        @Html.EditorFor(m => m.Table2Rows[i])
    }
    <p><input type="submit" /></p>
}

When you post the form, you should have a complete model MyProject.Models.CompositeModel filled in.

jquery - Submit n forms With one button MVC .NET - Stack Overflow

jquery asp.net-mvc forms asp.net-mvc-4 razor
Rectangle 27 40

1. Create the following flow layout subclass

There's a cleaner way to do this than some of the other answers here, and it works well. It should be performant (collection views load fast, no unnecessary auto layout passes etc), and doesn't have any 'magic numbers' like a fixed collection view width. Changing the collection view size, e.g. on rotation, and then invalidating the layout should work great too.

class HorizontallyFlushCollectionViewFlowLayout: UICollectionViewFlowLayout {

    // Don't forget to use this class in your storyboard (or code, .xib etc)

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as? UICollectionViewLayoutAttributes
        guard let collectionView = collectionView else { return attributes }
        attributes?.bounds.size.width = collectionView.bounds.width - sectionInset.left - sectionInset.right
        return attributes
    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let allAttributes = super.layoutAttributesForElementsInRect(rect)
        return allAttributes?.flatMap { attributes in
            switch attributes.representedElementCategory {
            case .Cell: return layoutAttributesForItemAtIndexPath(attributes.indexPath)
            default: return attributes
            }
        }
    }
}
// The provided size should be a plausible estimate of the actual
// size. You can set your item size in your storyboard
// to a good estimate and use the code below. Otherwise,
// you can provide it manually too, e.g. CGSize(width: 100, height: 100)

flowLayout.estimatedItemSize = flowLayout.itemSize
override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    layoutAttributes.bounds.size.height = systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    return layoutAttributes
}

Can't get this to work on iOS (9.3). On 10 it works fine. The application crashes on _updateVisibleCells (infinite recursion ?). openradar.me/25303115

@cristiano2lopes it works well for me on iOS 9.3. Make sure you are providing a reasonable estimate, and make sure your cell constraints are set up to resolve to a correct size.

This works amazing. I am using Xcode 8 and tested in iOS 9.3.3 (physical device) and it does not crash! Works great. Just make sure your estimate is good!

ios - Specifying one Dimension of Cells in UICollectionView using Auto...

ios objective-c uicollectionview autolayout
Rectangle 27 40

1. Create the following flow layout subclass

There's a cleaner way to do this than some of the other answers here, and it works well. It should be performant (collection views load fast, no unnecessary auto layout passes etc), and doesn't have any 'magic numbers' like a fixed collection view width. Changing the collection view size, e.g. on rotation, and then invalidating the layout should work great too.

class HorizontallyFlushCollectionViewFlowLayout: UICollectionViewFlowLayout {

    // Don't forget to use this class in your storyboard (or code, .xib etc)

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as? UICollectionViewLayoutAttributes
        guard let collectionView = collectionView else { return attributes }
        attributes?.bounds.size.width = collectionView.bounds.width - sectionInset.left - sectionInset.right
        return attributes
    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let allAttributes = super.layoutAttributesForElementsInRect(rect)
        return allAttributes?.flatMap { attributes in
            switch attributes.representedElementCategory {
            case .Cell: return layoutAttributesForItemAtIndexPath(attributes.indexPath)
            default: return attributes
            }
        }
    }
}
// The provided size should be a plausible estimate of the actual
// size. You can set your item size in your storyboard
// to a good estimate and use the code below. Otherwise,
// you can provide it manually too, e.g. CGSize(width: 100, height: 100)

flowLayout.estimatedItemSize = flowLayout.itemSize
override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    layoutAttributes.bounds.size.height = systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    return layoutAttributes
}

Can't get this to work on iOS (9.3). On 10 it works fine. The application crashes on _updateVisibleCells (infinite recursion ?). openradar.me/25303115

@cristiano2lopes it works well for me on iOS 9.3. Make sure you are providing a reasonable estimate, and make sure your cell constraints are set up to resolve to a correct size.

This works amazing. I am using Xcode 8 and tested in iOS 9.3.3 (physical device) and it does not crash! Works great. Just make sure your estimate is good!

ios - Specifying one Dimension of Cells in UICollectionView using Auto...

ios objective-c uicollectionview autolayout
Rectangle 27 8

There is a lot of repetition in your code. I would break down each section and make it a separate component and focus on it's individual layout needs.

In you main screen you have 4 main areas (excluding the menu).

I would use something like GridBagLayout to layout these 4 sections. This allows each section the ability to grow to it's required height, without effecting the others. You can also supply individual growth hints to each section as you see fit.

The first section is a JLabel, so it's pretty simple

This section is basially three labels with slightly different alignments. I would still use a GridBagLayout as it provides the greatest flexibility to allow for individual cell alignment, while allowing you to provide sizing hints (for example, I might make the time row in width as the screen size is changed).

This section is a little more complicated. Basically, it's the same component on the left and right, with some clever properties, you would be able to change the position of the labels without to much of an issue.

The individual dots/labels could be laid out using a GridLayout. I might err on the side of caution and use a GridBagLayout, as it would allow the labels to be different sizes to the dots

I would then use something like a GridLayout to place each side onto a component (which would then be placed on the main screen)

Again, this simple the same component mirrored. I would simply create a single component that could be adjusted via a property to change the alignment.

I would then simply use a GridBagLayout to lay out each label as required. I'd do it this way because it allows each row the ability to have it's own height.

thx a lot but there is still one question. How I can create menu which is overflowing 3 of main screen parts. PS: there isnt much to do I just creating some app for my own use

@hudi I would use the frames glass pane. I will allow you to "float" components ontop of the others. It's a little more complicated as you become responsible for positioning and sizing the components, but will give you the result you want. Take a look at how to use glass panes

This is a great answer. However, I'd recommand to use an OverlayLayout instead of the glass pane.

@barjak You could also use JLayer, but it comes down to needs and knowledge. +1 for suggestion

Which java swing layout should I use - Stack Overflow

java swing layout layout-manager
Rectangle 27 8

There is a lot of repetition in your code. I would break down each section and make it a separate component and focus on it's individual layout needs.

In you main screen you have 4 main areas (excluding the menu).

I would use something like GridBagLayout to layout these 4 sections. This allows each section the ability to grow to it's required height, without effecting the others. You can also supply individual growth hints to each section as you see fit.

The first section is a JLabel, so it's pretty simple

This section is basially three labels with slightly different alignments. I would still use a GridBagLayout as it provides the greatest flexibility to allow for individual cell alignment, while allowing you to provide sizing hints (for example, I might make the time row in width as the screen size is changed).

This section is a little more complicated. Basically, it's the same component on the left and right, with some clever properties, you would be able to change the position of the labels without to much of an issue.

The individual dots/labels could be laid out using a GridLayout. I might err on the side of caution and use a GridBagLayout, as it would allow the labels to be different sizes to the dots

I would then use something like a GridLayout to place each side onto a component (which would then be placed on the main screen)

Again, this simple the same component mirrored. I would simply create a single component that could be adjusted via a property to change the alignment.

I would then simply use a GridBagLayout to lay out each label as required. I'd do it this way because it allows each row the ability to have it's own height.

thx a lot but there is still one question. How I can create menu which is overflowing 3 of main screen parts. PS: there isnt much to do I just creating some app for my own use

@hudi I would use the frames glass pane. I will allow you to "float" components ontop of the others. It's a little more complicated as you become responsible for positioning and sizing the components, but will give you the result you want. Take a look at how to use glass panes

This is a great answer. However, I'd recommand to use an OverlayLayout instead of the glass pane.

@barjak You could also use JLayer, but it comes down to needs and knowledge. +1 for suggestion

Which java swing layout should I use - Stack Overflow

java swing layout layout-manager
Rectangle 27 8

There is a lot of repetition in your code. I would break down each section and make it a separate component and focus on it's individual layout needs.

In you main screen you have 4 main areas (excluding the menu).

I would use something like GridBagLayout to layout these 4 sections. This allows each section the ability to grow to it's required height, without effecting the others. You can also supply individual growth hints to each section as you see fit.

The first section is a JLabel, so it's pretty simple

This section is basially three labels with slightly different alignments. I would still use a GridBagLayout as it provides the greatest flexibility to allow for individual cell alignment, while allowing you to provide sizing hints (for example, I might make the time row in width as the screen size is changed).

This section is a little more complicated. Basically, it's the same component on the left and right, with some clever properties, you would be able to change the position of the labels without to much of an issue.

The individual dots/labels could be laid out using a GridLayout. I might err on the side of caution and use a GridBagLayout, as it would allow the labels to be different sizes to the dots

I would then use something like a GridLayout to place each side onto a component (which would then be placed on the main screen)

Again, this simple the same component mirrored. I would simply create a single component that could be adjusted via a property to change the alignment.

I would then simply use a GridBagLayout to lay out each label as required. I'd do it this way because it allows each row the ability to have it's own height.

thx a lot but there is still one question. How I can create menu which is overflowing 3 of main screen parts. PS: there isnt much to do I just creating some app for my own use

@hudi I would use the frames glass pane. I will allow you to "float" components ontop of the others. It's a little more complicated as you become responsible for positioning and sizing the components, but will give you the result you want. Take a look at how to use glass panes

This is a great answer. However, I'd recommand to use an OverlayLayout instead of the glass pane.

@barjak You could also use JLayer, but it comes down to needs and knowledge. +1 for suggestion

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Which java swing layout should I use - Stack Overflow

java swing layout layout-manager
Rectangle 27 8

There is a lot of repetition in your code. I would break down each section and make it a separate component and focus on it's individual layout needs.

In you main screen you have 4 main areas (excluding the menu).

I would use something like GridBagLayout to layout these 4 sections. This allows each section the ability to grow to it's required height, without effecting the others. You can also supply individual growth hints to each section as you see fit.

The first section is a JLabel, so it's pretty simple

This section is basially three labels with slightly different alignments. I would still use a GridBagLayout as it provides the greatest flexibility to allow for individual cell alignment, while allowing you to provide sizing hints (for example, I might make the time row in width as the screen size is changed).

This section is a little more complicated. Basically, it's the same component on the left and right, with some clever properties, you would be able to change the position of the labels without to much of an issue.

The individual dots/labels could be laid out using a GridLayout. I might err on the side of caution and use a GridBagLayout, as it would allow the labels to be different sizes to the dots

I would then use something like a GridLayout to place each side onto a component (which would then be placed on the main screen)

Again, this simple the same component mirrored. I would simply create a single component that could be adjusted via a property to change the alignment.

I would then simply use a GridBagLayout to lay out each label as required. I'd do it this way because it allows each row the ability to have it's own height.

thx a lot but there is still one question. How I can create menu which is overflowing 3 of main screen parts. PS: there isnt much to do I just creating some app for my own use

@hudi I would use the frames glass pane. I will allow you to "float" components ontop of the others. It's a little more complicated as you become responsible for positioning and sizing the components, but will give you the result you want. Take a look at how to use glass panes

This is a great answer. However, I'd recommand to use an OverlayLayout instead of the glass pane.

@barjak You could also use JLayer, but it comes down to needs and knowledge. +1 for suggestion

Which java swing layout should I use - Stack Overflow

java swing layout layout-manager
Rectangle 27 183

I wrote the Pinterest script. The ID's are unrelated to the layout, and are used for other interaction-related JS. Here's the base of how it works:

  • Absolutely position the pin containers
  • Get the width of the parent container; calculate the # of columns that will fit
  • Create an empty array, with a length equaling the # of columns. Use this array to store the height of each column as you build the layout, e.g. the height of column 1 is stored as array[0]
  • Put each pin in the shortest column at the moment it is added
  • "left:" === the column # (index array) times the column width + margin
  • "top:" === The value in the array (height) for the shortest column at that time
  • Finally, add the height of the pin to the column height (array value)

The result is lightweight. In Chrome, laying out a full page of 50+ pins takes <10ms.

How do you mean calculate the height of the column? How do you know how high it should be if you don't know the number and height of items within it? Any chance you could layout some pseudo code to demonstrate?

Feedback from an anonymus user (found in edit queue): Curiously I did exactly the same script in jQuery, with the slight difference of actually creating a table with 1 row and N columns, and just appending them to the shortest column from left to right priority. Even though I also added a "Minimum height difference" Constant required to actually skip a column when positioning from left to right, this gives the layout a chronologically intuitive display without loosing the heights being as even as possible

@MichaelGiovanniPumo I think the height should be known prior to the layout (in case of Pinterest), they do not have an "initial" state which have divs overlap each other. This can not be done if height is not known.

jquery - how to replicate pinterest.com's absolute div stacking layout...

jquery css layout
Rectangle 27 6

For the first case you can use a simple GridLayout on the JPanel with 3 Rows each having a separate JPanel with FlowLayout having constraints, FLowLayout.LEFT. Have a look at this code example :

And for the Second case, simply add first two components to the JPanel having default Layout. And for the third components, simply add components on to a JPanel having GridBagLayout, with no constraints.

import java.awt.*;
import javax.swing.*;

public class ExampleLayout
{
    private void displayGUI()
    {
        JFrame frame = new JFrame("Example Layout");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(5, 5));

        JPanel basePanel = new JPanel();
        basePanel.setLayout(new GridLayout(0, 1, 5, 5));

        JPanel topPanel = new JPanel();
        //topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

        JLabel label1 = new JLabel("Label 1", JLabel.CENTER);
        JRadioButton rbut1 = new JRadioButton("RadioButton 1", false);

        topPanel.add(label1);
        topPanel.add(rbut1);        

        JPanel middlePanel = new JPanel();
        middlePanel.setLayout(new GridBagLayout());

        JButton button1 = new JButton("Button 1");

        middlePanel.add(button1);

        basePanel.add(topPanel);
        basePanel.add(middlePanel);

        contentPane.add(basePanel, BorderLayout.PAGE_START);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new ExampleLayout().displayGUI();
            }
        });
    }
}

Wow, it is incredible. Thanks a lot, I think it is what I need. But speaking about GridBagLayout, isn't it better to substitute it with BoxLayout with center alignment? And about buttons for the first case. If I use only icon without text (for example, "open folder" button) won't its size be stretched? I mean something like 40x16 instead of 16x16 (as icon size is).

@Dragon : Actually, specifying GridBagLayout with no constraints, simply puts the component in the center of the container, it might can work for your case I guess, instead of using BoxLayout. Never tried BoxLayout that much, since Nested Layout approach or GridBagLayout can do that task for all easily :-) BoxLayout stretches the component depending upon the contents of the component. So sometimes it leads to alignment issues, IMHO (that's why I restrain myself from using it, in many situations).

@GagandeepBali, it seemed to me that BoxLayout agile enough. Hm, maybe I need to rethink it. Thanks a lot, anyway.

@Dragon : Please have a look at this wonderful example by mKorbel, for providing properties to the JButton, that might will look good. You might be right from your prespective, as I liked GridBagLayout and from your perspective it's a bit unfriendly to work with. For the rest, You're MOST WELCOME and KEEP SMILING :-)

java - What swing layouts structure to choose for an app? - Stack Over...

java swing layout layout-manager jcomponent
Rectangle 27 21

1) Use return PartialView() from controller, it won't take Layout from View start

@{
     Layout = null;
  }

c# - How to override the layout defined in _ViewStart for certain view...

c# .net asp.net-mvc asp.net-mvc-3
Rectangle 27 21

1) Use return PartialView() from controller, it won't take Layout from View start

@{
     Layout = null;
  }

c# - How to override the layout defined in _ViewStart for certain view...

c# .net asp.net-mvc asp.net-mvc-3
Rectangle 27 196

If you want to have a simple Line in your Layout to separate two views you can use a generic View with the height and width you want the line to have and a set background color.

With this approach you don't need to override a View or use a Canvas yourself just simple and clean add the line in xml.

<View
 android:layout_width="match_parent"
 android:layout_height="1dp"
 android:background="@android:color/black" />

The example code I provided will generate a line that fills the screen in width and has a height of one dp.

If you have problems with the drawing of the line on small screens consider to change the height of the line to px. The problem is that on a ldpi screen the line will be 0.75 pixel high. Sometimes this may result in a rounding that makes the line vanish. If this is a problem for your layout define the width of the line a ressource file and create a separate ressource file for small screens that sets the value to 1px instead of 1dp.

This approach is only usable if you want horizontal or vertical lines that are used to divide layout elements. If you want to achieve something like a cross that is drawn into an image my approach will not work.

How can add the same view at runtime that's dynamically?

How to draw a line in android - Stack Overflow

android
Rectangle 27 193

If you want to have a simple Line in your Layout to separate two views you can use a generic View with the height and width you want the line to have and a set background color.

With this approach you don't need to override a View or use a Canvas yourself just simple and clean add the line in xml.

<View
 android:layout_width="match_parent"
 android:layout_height="1dp"
 android:background="@android:color/black" />

The example code I provided will generate a line that fills the screen in width and has a height of one dp.

If you have problems with the drawing of the line on small screens consider to change the height of the line to px. The problem is that on a ldpi screen the line will be 0.75 pixel high. Sometimes this may result in a rounding that makes the line vanish. If this is a problem for your layout define the width of the line a ressource file and create a separate ressource file for small screens that sets the value to 1px instead of 1dp.

This approach is only usable if you want horizontal or vertical lines that are used to divide layout elements. If you want to achieve something like a cross that is drawn into an image my approach will not work.

How can add the same view at runtime that's dynamically?

How to draw a line in android - Stack Overflow

android
Rectangle 27 11

I would look at nesting JPanels. It would be very easy to make each row a separate JPanel and then just stack the JPanels.

Otherwise you can use the GridBagLayout. That is the one I use for more control over where components are placed.

GridBagLayout
GridBagConstraint
.gridx
GridBagConstraint.gridx = 0
GridBagConstraint.gridy++

+1 : I also would use the GridBagLayout!

yup, this is pretty gridbag-able. JGoodies formlayout would be ok, but i've had some "iffy" results with that, especially if the size or controls change dynamically.

Hooray for GridBagLayout! \o/ I prefer to use the full GridBagConstraints constructor when adding new components, though. That makes it easier to insert additional components between existings ones without having to worry about leftovers in the constraints object.

I think that the Constraints work well with default values most of the time. Just changing gridx/y and gridheight/width usually do it for me.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - How can I best lay out these components in Swing? - Stack Overf...

java swing layout
Rectangle 27 4

I would just put the buttons in their own panel. That simplifies the layout and similar components tend to get modified together so it is good to have them in their separate function or class.

Whenever possible I try to use a tree-like structure of containers rather than have a complicated layout that includes all the components. It makes it harder to read and rearrange things when everything depends on the layout of everything else.

java - Vertical button bar layout using miglayout - Stack Overflow

java swing layout layout-manager miglayout
Rectangle 27 4

I would just put the buttons in their own panel. That simplifies the layout and similar components tend to get modified together so it is good to have them in their separate function or class.

Whenever possible I try to use a tree-like structure of containers rather than have a complicated layout that includes all the components. It makes it harder to read and rearrange things when everything depends on the layout of everything else.

java - Vertical button bar layout using miglayout - Stack Overflow

java swing layout layout-manager miglayout
Rectangle 27 5

1) Is there a "main" area with smaller surrounding areas in your design. If so use a BorderLayout.

2) Is there equal grid like areas in your design, If so use a GridLayout.

3) If you need a top-down, or left-right layout, consider a BoxLayout

4) If you want to show a complex form, probably use a FormLayout from jgoodies.

But you have to look at things from a high level. There may be subsections in any one top level section of your dialog. If that is the case, then you need to put a JPanel in that section, and then use a sub layout in that JPanel. Use the above questions over again for that panel.

+1, the tutorial is the best way to answer this. The poster know needs to spend time and do some reading and playing with each of the layout managers to learn their strengths and weaknesses.

+1 for mentioning 'sub layouts'. I do not make too many (non trivial) GUIs that rely on just one layout.

how to use the layout managers in swing java - Stack Overflow

java swing layout
Rectangle 27 5

1) Is there a "main" area with smaller surrounding areas in your design. If so use a BorderLayout.

2) Is there equal grid like areas in your design, If so use a GridLayout.

3) If you need a top-down, or left-right layout, consider a BoxLayout

4) If you want to show a complex form, probably use a FormLayout from jgoodies.

But you have to look at things from a high level. There may be subsections in any one top level section of your dialog. If that is the case, then you need to put a JPanel in that section, and then use a sub layout in that JPanel. Use the above questions over again for that panel.

+1, the tutorial is the best way to answer this. The poster know needs to spend time and do some reading and playing with each of the layout managers to learn their strengths and weaknesses.

+1 for mentioning 'sub layouts'. I do not make too many (non trivial) GUIs that rely on just one layout.

how to use the layout managers in swing java - Stack Overflow

java swing layout