Home > Software engineering >  How to make this layout in Java Swing?
How to make this layout in Java Swing?

Time:11-25

I want to make layout which looks like this image. I am having difficulty understanding how to go about this? Could somebody give me some pointers on how to go about this in that .. which layout and components to use?

  1. No need for multiple pages, just what is visible in image.
  2. In addition to image, I have text below every image in each card

Output image

The above is a general representation of how it should appear. The actual location of cards is like 'Dashborad' in the image below:

Output1

The second row cards are to be placed between gaps of first row.

CodePudding user response:

The central area looks like a GridLayout of 3 x 3 JButton controls with icons. Below that is a centered FlowLayout of 3 x JRadioButton which I'd guess is allowing the user to control a CardLayout currently pointing to the '9 button card'.

I want to make layout which looks like this image.

One thing that confuses many, is that there can be more than one layout within a single view. It is rare I'll use but a single layout for a main GUI or much else, for that matter.

CodePudding user response:

One way to achieve the layout of 5 cards as illustrated by dashboard is to use a combination of panels managed by BoxLayout:

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

public class Main{

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.add(new CardsPane());
        frame.pack();
        frame.setVisible(true);
    }
}

class CardsPane extends JPanel{

    private static final String SQUARE =
            "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/128x128/Box_Green.png";
    private static Icon icon;

    public CardsPane() {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        try {
            icon = new ImageIcon(new URL(SQUARE));
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }

        JPanel topCards = new JPanel();
        topCards.setLayout(new BoxLayout(topCards, BoxLayout.X_AXIS));

        for (int i = 0; i < 3; i  ) {
            topCards.add(getCard("card " i));
        }
        add(topCards);

        JPanel bottomCards = new JPanel();
        bottomCards.setLayout(new BoxLayout(bottomCards, BoxLayout.X_AXIS));
        for (int i = 3; i < 5; i  ) {
            bottomCards.add(getCard("card " i));
        }
        add(bottomCards);
    }

    private static JComponent getCard(String text){

        JLabel label = new JLabel(text);
        label.setHorizontalTextPosition(JLabel.CENTER);
        label.setVerticalTextPosition(JLabel.BOTTOM);
        label.setIcon(icon);
        return label;
    }
}

enter image description here

  • Related