Изменения положения компоновки Java-компонентов после восстановления свернутого окна - PullRequest
0 голосов
/ 04 марта 2019

Я разрабатываю приложение для отображения информации о полете (FID), которое отображает информацию с помощью JLabels.У меня есть разные JPanels, которые содержат разные метки.

Моя проблема в том, что когда я запускаю окно, оно отображается правильно с каждым компонентом, сохраняя желаемую позицию макета, но позиция метки изменяется (кластеры в центре) при попыткевосстановить окно после его минимизации.Тем самым объединяются все метки вместе.Пожалуйста, мне действительно нужно решить эту проблему.

Ниже приведен мой фрагмент кода:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Departure extends javax.swing.JFrame {

    final private JPanel container = new JPanel();
    final private JPanel secPanel;
    final private JPanel imgPanel;
    final private JLabel logo;
    final private JLabel lagosLbl;
    final private JLabel londonLbl;
    final private JLabel newYorkLbl;
    final private JLabel lagosTime;
    final private JLabel londonTime;
    final private JLabel newYorkTime;
    final private JLabel departureLbl;
    final private JLabel airlineHd;
    final private JLabel flightHd;
    final private JLabel destHd;
    final private JLabel schedHd;
    final private JLabel gateHd;
    final private JLabel statusHd;
    final private JLabel footer;
    private JLabel footerLeft, footerMid, footerRight;


    private String todayDate, timeLocale, timeLondon, timeNewYork;

    Dimension sizeMain, sizeHeading, sizeBody, sizeLogo, sizeSec, screenSize;
    Insets insetsMain, insetsHeading, insetsBody, insetsLogo, insetsSec;

    public Departure(){

        super("DEPARTURES");

        screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(0,0,screenSize.width, screenSize.height);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(false);      
        this.setVisible(true);



        container.setPreferredSize(new Dimension(screenSize.width, 
        screenSize.height));
        container.setBackground(new Color(53,86,163));
        this.getContentPane().add(container);

        Insets insets = this.getInsets();
        Dimension size = container.getPreferredSize();
        container.setBounds(0 + insets.left, 0 + insets.top,
        size.width + 5, size.height + 5);
        container.setLayout(null);


        ImageIcon icon = new ImageIcon(getClass().getResource("headerDe.jpg"));
        logo = new JLabel();
        logo.setIcon(new 
        ImageIcon(icon.getImage().getScaledInstance(screenSize.width, 200,
        java.awt.Image.SCALE_SMOOTH)));
        logo.setBackground(new Color(0,0,0));
        container.add(logo);

        insetsMain = container.getInsets();
        sizeMain = logo.getPreferredSize();
        logo.setBounds(0 + insetsMain.left, 0 + insetsMain.top,
        sizeMain.width + 5, sizeMain.height + 5);


        lagosLbl = new JLabel("LAGOS:");
        lagosLbl.setFont(new Font("Century Gothic",Font.BOLD, 40));
        lagosLbl.setForeground(new Color(0,0,140));
        logo.add(lagosLbl);

        insetsLogo = logo.getInsets();
        sizeLogo = lagosLbl.getPreferredSize();
        lagosLbl.setBounds(1550 + insetsLogo.left, 5 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);

        timeLocale = myTimeLocale();
        lagosTime = new JLabel(timeLocale);
        lagosTime.setFont(new Font("Century Gothic",Font.BOLD, 45));
        lagosTime.setForeground(new Color(0,0,140));
        logo.add(lagosTime);

        sizeLogo = lagosTime.getPreferredSize();
        lagosTime.setBounds(1750 + insetsLogo.left, 2 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);


        londonLbl = new JLabel("LONDON:");
        londonLbl.setFont(new Font("Century Gothic",Font.BOLD, 40));
        londonLbl.setForeground(new Color(0,0,140));
        logo.add(londonLbl);

        sizeLogo = londonLbl.getPreferredSize();
        londonLbl.setBounds(1515 + insetsLogo.left, 65 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);

        timeLondon = myTimeLondon();
        londonTime = new JLabel(timeLondon);
        londonTime.setFont(new Font("Century Gothic",Font.BOLD, 45));
        londonTime.setForeground(new Color(0,0,140));
        logo.add(londonTime);

        sizeLogo = londonTime.getPreferredSize();
        londonTime.setBounds(1750 + insetsLogo.left, 62 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);

        newYorkLbl = new JLabel("NEW YORK:");
        newYorkLbl.setFont(new Font("Century Gothic",Font.BOLD, 40));
        newYorkLbl.setForeground(new Color(0,0,140));
        logo.add(newYorkLbl);

        sizeLogo = newYorkLbl.getPreferredSize();
        newYorkLbl.setBounds(1485 + insetsLogo.left, 125 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);

        timeNewYork = myTimeNewYork();

        newYorkTime = new JLabel(timeNewYork);
        newYorkTime.setFont(new Font("Century Gothic",Font.BOLD, 45));
        newYorkTime.setForeground(new Color(0,0,140));
        myTimeNewYork();
        logo.add(newYorkTime);

        sizeLogo = newYorkTime.getPreferredSize();
        newYorkTime.setBounds(1750 + insetsLogo.left, 122 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);

        departureLbl = new JLabel("DEPARTURES");
        departureLbl.setFont(new Font("Century Gothic",Font.BOLD, 100));
        departureLbl.setForeground(new Color(53,86,163));
        logo.add(departureLbl);

        sizeLogo = departureLbl.getPreferredSize();
        departureLbl.setBounds(680 + insetsLogo.left, 50 + insetsLogo.top,
        sizeLogo.width + 5, sizeLogo.height + 5);


        secPanel = new JPanel();
        secPanel.setPreferredSize( new Dimension( screenSize.width, 
        (screenSize.width - 300) ) );
        secPanel.setBackground(new Color(255,255,255));
        container.add(secPanel);

        sizeMain = secPanel.getPreferredSize();
        secPanel.setBounds(0 + insetsMain.left, 200 + insetsMain.top,
        sizeMain.width + 5, sizeMain.height + 5);


        imgPanel = new JPanel();
        imgPanel.setPreferredSize( new Dimension( screenSize.width,45 ) );
        imgPanel.setBackground(new Color(0,0,140));
        secPanel.add(imgPanel);

        insetsHeading = secPanel.getInsets();
        sizeHeading = imgPanel.getPreferredSize();
        imgPanel.setBounds(0 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);


        schedHd = new JLabel("STD");
        schedHd.setFont(new Font("Century Gothic",Font.BOLD, 28));
        schedHd.setForeground(new Color(255, 255, 255));
        imgPanel.add(schedHd);

        insetsHeading = imgPanel.getInsets();
        sizeHeading = schedHd.getPreferredSize();
        schedHd.setBounds(100 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);

        airlineHd = new JLabel("AIRLINE");
        airlineHd.setFont(new Font("Century Gothic",Font.BOLD, 28));
        airlineHd.setForeground(new Color(255, 255, 255));
        imgPanel.add(airlineHd);

        sizeHeading = airlineHd.getPreferredSize();
        airlineHd.setBounds(350 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);

        destHd = new JLabel("DESTINATION");
        destHd.setFont(new Font("Century Gothic",Font.BOLD, 28));
        destHd.setForeground(new Color(255, 255, 255));
        imgPanel.add(destHd);

        sizeHeading = destHd.getPreferredSize();
        destHd.setBounds(650 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);

        flightHd = new JLabel("FLIGHT");
        flightHd.setFont(new Font("Century Gothic",Font.BOLD, 28));
        flightHd.setForeground(new Color(255, 255, 255));
        imgPanel.add(flightHd);   

        sizeHeading = flightHd.getPreferredSize();
        flightHd.setBounds(1020 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);


        gateHd = new JLabel("GATE");
        gateHd.setFont(new Font("Century Gothic",Font.BOLD, 28));
        gateHd.setForeground(new Color(255, 255, 255));
        imgPanel.add(gateHd);

        sizeHeading = gateHd.getPreferredSize();
        gateHd.setBounds(1280 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);

        statusHd = new JLabel("STATUS");
        statusHd.setFont(new Font("Century Gothic",Font.BOLD, 28));
        statusHd.setForeground(new Color(255, 255, 255));
        imgPanel.add(statusHd);

        sizeHeading = statusHd.getPreferredSize();
        statusHd.setBounds(1520 + insetsHeading.left, 5 + insetsHeading.top,
        sizeHeading.width + 5, sizeHeading.height + 5);

        ImageIcon foot = new ImageIcon(getClass().getResource("footer.jpg"));
        footer = new JLabel();
        footer.setIcon(new 
        ImageIcon(foot.getImage().getScaledInstance(screenSize.width, 70,
        java.awt.Image.SCALE_SMOOTH)));
        secPanel.add(footer);

        size = footer.getPreferredSize();
        footer.setBounds(0 + insets.left, 760 + insets.top,
        size.width + 5, size.height + 5);

        todayDate = dayOfWeek() + "    "+ myDate();
        footerLeft = new JLabel(todayDate);
        footerLeft.setFont(new Font("Century Gothic",Font.BOLD, 30));
        footerLeft.setForeground(new Color(255,255,255));
        footer.add(footerLeft);

        size = footerLeft.getPreferredSize();
        footerLeft.setBounds(15 + insets.left, 15 + insets.top,
        size.width + 5, size.height + 5);

        footerMid = new JLabel();
        //footerMid.setPreferredSize(new Dimension(120, 70));
        footerMid.setFont(new Font("Century Gothic",Font.BOLD, 30));
        footerMid.setForeground(new Color(255,255,255));
        footer.add(footerMid);

        size = footerMid.getPreferredSize();
        footerMid.setBounds(450 + insets.left, 15 + insets.top,
        size.width + 5, size.height + 5);

        footerRight = new JLabel();
        footerRight.setFont(new Font("Century Gothic",Font.BOLD, 30));
        footerRight.setForeground(new Color(255,255,255));
        footer.add(footerRight);

        size = footerRight.getPreferredSize();
        footerRight.setBounds(1540 + insets.left, 15 + insets.top,
        size.width + 5, size.height + 5);


    }

    public String dayOfWeek(){
        Date now = new Date();

        SimpleDateFormat simpleDateformat = new SimpleDateFormat("EEEE"); // the 
        day of the week in full
        //SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); // the 
        day of the week abbreviated
        return simpleDateformat.format(now);
    }

    protected static String myDate(){
        Calendar myD = Calendar.getInstance();

        SimpleDateFormat d = new SimpleDateFormat("dd/MM/yyyy");
        String date = (d.format(myD.getTime()));

        return date;
    }

    public static void main(String args []){
        Departure departure = new Departure();
    }
}

When the application is lauched

After restoring a minimized window

Ответы [ 2 ]

0 голосов
/ 06 марта 2019

Спасибо всем, кто ответил на мой вопрос.Позже я обнаружил, что я не определил явно макет для каждого контейнера (панелей), который я объявил перед добавлением к ним некоторого содержимого (меток), таким образом, измерение имеет тенденцию разбрасываться при восстановлении окна.Хотя это может быть громоздким, но мне нравится иметь абсолютный контроль над позицией каждого элемента в окне.Еще раз спасибо

Ниже приведен пример того, как я решил это;

//After initializing the imgPanel

imgPanel.setLayout(null); //explicitly declare the imgPanel layout to null

JLabel lbl = new JLabel("STD");
imgPanel.add(lbl)

Insets imgPanelInsets = imgPanel.getInsets(); //define the components insets
Dimension sizeImg = lbl.getPreferredSize(); //define the components dimension
lbl.setBounds(100 + imgPanelInsets.left, 5 + imgPanelInsets.top,
             sizeImg.width + 5, sizeImg.height + 5);  

JLabel lbl2 = new JLabel("AIRLINE");
imgPanel.add(lbl2)

sizeImg = lbl2.getPreferredSize();
lbl2.setBounds(100 + imgPanelInsets.left, 5 + imgPanelInsets.top,
             sizeImg.width + 5, sizeImg.height + 5); 
0 голосов
/ 04 марта 2019

Используйте GridLayout на вашем imgPanel и добавьте метки, используя цикл.Обязательно центрируйте текст метки с помощью SwingConstants.CENTER.

Все метки будут равноудалены друг от друга, и вам не нужно устанавливать какие-либо вставки или поля.

List<String> labels = Arrays.asList("STD", "AIRLINE", "DESTINATION", "FLIGHT", "GATE", "STATUS");
imgPanel.setLayout(new GridLayout(1, labels.size())); // 1 row, 6 columns
labels.stream().forEach(s -> {
    JLabel label = new JLabel(s, SwingConstants.CENTER); // centered label text
    label.setFont(new Font("Century Gothic", Font.BOLD, 28));
    label.setForeground(new Color(255, 255, 255));
    imgPanel.add(label);
});

ВыМожно также просто установить макет перед тем, как начинать добавлять ярлыки, но это более громоздко и не динамично.

imgPanel.setLayout(new GridLayout(1, 6)); // Six labels tiled horizontally

И не забудьте центрировать текст ярлыка.

schedHd = new JLabel("STD", SwingConstants.CENTER);
airlineHd = new JLabel("AIRLINE", SwingConstants.CENTER);
// etc...
...