【问题标题】:Java components does not appear when the window is centered窗口居中时不出现Java组件
【发布时间】:2015-07-28 21:43:08
【问题描述】:

我有一个奇怪的问题,我不知道是什么原因造成的。 我有一个对话框类,它只是在屏幕上显示错误/警告消息。有趣的是,当我设置窗口中心时,组件并没有出现(除非我重新调整它的大小)。

但是,当我更改屏幕位置时,JPanel 上会出现组件就好了。

我基本上把这条线改成int x = (dim.width - w) / 3;它就可以了。但是当宽度除以 2 时它不会。因此,对话框可以在除中心之外的任何地方工作。请让我知道我在这里缺少什么。

感谢您的帮助!

谢谢!

代码如下:


一个 MCVE:

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

@SuppressWarnings("serial")
public class UKDialog extends JDialog {

   private JButton button1;
   private JLabel message;

   public UKDialog(String message, String buttonText) {
       this.button1 = new JButton(buttonText);
       this.message = new JLabel(message);
       setWarning();
   }

   public void setWarning() {
       this.setModal(true);
       this.setAlwaysOnTop(true);
       if (this.message.getText().length() <= 30) {
           this.setMaximumSize(new Dimension(650, 300));
           this.setMinimumSize(new Dimension(650, 300));
           this.setPreferredSize(new Dimension(650, 300));
       } else if (this.message.getText().length() > 30) {
           this.setMaximumSize(new Dimension(870, 300));
           this.setMinimumSize(new Dimension(870, 300));
           this.setPreferredSize(new Dimension(870, 300));
       }

       this.setLayout(new BorderLayout());

       JPanel messagePanel = new JPanel();
       messagePanel.setBorder(BorderFactory.createEtchedBorder());

       JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
       buttonPanel.setBorder(BorderFactory.createEtchedBorder());
       buttonPanel.setPreferredSize(new Dimension(600, 100));

       this.message.setFont(new Font("Calibri", Font.BOLD, 40));

       this.button1.setPreferredSize(new Dimension(230, 80));
       this.button1.setFont(new Font("Calibri", Font.BOLD, 45));
       this.button1.setBackground(new java.awt.Color(139, 71, 137));
       this.button1.setForeground(java.awt.Color.white);
       this.button1.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
               okActionPerformed(evt);
           }
       });

       messagePanel.add(this.message, BorderLayout.CENTER);
       buttonPanel.add(this.button1);
       this.add(messagePanel, BorderLayout.CENTER);
       this.add(buttonPanel, BorderLayout.SOUTH);
       // calculate the new location of the window
       Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
       int w = this.getSize().width;
       int h = this.getSize().height;
       int x = (dim.width - w) / 2;
       int y = (dim.height - h) / 5;
       this.setLocation(x, y);
       this.setVisible(true);
   }

   protected void okActionPerformed(ActionEvent evt) {
      UKDialog.this.dispose();
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            final JFrame frame = new JFrame("Main GUI");
            JButton button = new JButton(new AbstractAction("Push Me") {

               @Override
               public void actionPerformed(ActionEvent e) {
                  String message = "Message is Long Enough???";
                  String buttonText = "Button";
                  UKDialog ukDialog = new UKDialog(message, buttonText);
               }
            });

            JPanel panel = new JPanel();
            panel.setPreferredSize(new Dimension(500, 400));
            panel.add(button);

            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(panel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
         }
      });    
   }
}

这是我的类用main方法调用警告类。

 import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import javax.imageio.ImageIO;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ScrollPaneLayout;
    import javax.swing.WindowConstants;

public class PAndDeliveryNotification extends JDialog {

    private JButton button1;
    private JLabel messageTitle;
    private JTextField text;
    private boolean reply;
    private String typedText;
    private ArrayList<String[]> remainingInvoices;
    private String stopNum = null;
    private String currentStopNum, lastStopNum;

    public PAndDeliveryNotification(ArrayList<String[]> rInvoices, String buttonText1) {
        this.button1 = new JButton(buttonText1);
        this.remainingInvoices = rInvoices;
    }

    public void setDelivStopNo() throws IOException {
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("images/uk.png"));
        } catch (IOException e) {
        }
        this.setIconImage(image);

        //frame properties
        this.setModal(true);
        this.setAlwaysOnTop(true);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.setLayout(new BorderLayout());
        //frame size
        this.setPreferredSize(new Dimension(900, 600));
        this.setMaximumSize(new Dimension(900, 600));
        this.setMinimumSize(new Dimension(900, 600));

        JPanel upperPanel = new JPanel(new WrapLayout());
        upperPanel.setBorder(BorderFactory.createEtchedBorder());

        for (int i = 0; i < this.remainingInvoices.size(); i++) {
            String[] invoice;
            invoice = (String[]) this.remainingInvoices.get(i);
            if (i == 0) {
                this.currentStopNum = invoice[0];
            }
            if (i == this.remainingInvoices.size() - 1) {
                this.lastStopNum = invoice[0];
            }
            StopItem item = new StopItem(invoice);
            item.setPreferredSize(new Dimension(770, 120));
            upperPanel.add(item);
        }
        upperPanel.repaint();
        upperPanel.revalidate();
        JScrollPane pane = new JScrollPane(upperPanel);
        pane.setPreferredSize(new Dimension(770, 600));
        pane.getVerticalScrollBar().setPreferredSize(new Dimension(50, 0));
        pane.setLayout(new ScrollPaneLayout());
        this.add(pane, BorderLayout.CENTER);

        JPanel lowerPanel = new JPanel(new BorderLayout());
        lowerPanel.setBorder(BorderFactory.createEtchedBorder());
        lowerPanel.setPreferredSize(new Dimension(600, 100));

        JPanel messagePanel = new JPanel(new FlowLayout());
        messagePanel.setPreferredSize(new Dimension(600, 80));
        JPanel buttonPanel = new JPanel();
        buttonPanel.setPreferredSize(new Dimension(240, 80));

        this.messageTitle = new JLabel("Enter Delivery Stop Number:");
        this.messageTitle.setFont(new Font("Calibri", Font.BOLD, 40));
        this.messageTitle.setPreferredSize(new Dimension(480, 80));
        this.text = new JTextField(3);
        this.text.setPreferredSize(new Dimension(100, 80));
        this.text.setFont(new Font("Calibri", Font.BOLD, 40));
        this.text.setHorizontalAlignment(JTextField.CENTER);
        this.text.requestFocus();
        Runtime.getRuntime().exec("cmd /c tabtip.exe");

        this.button1.setPreferredSize(new Dimension(230, 80));
        this.button1.setFont(new Font("Calibri", Font.BOLD, 45));
        this.button1.setBackground(new java.awt.Color(139, 71, 137));
        this.button1.setForeground(java.awt.Color.white);
        this.button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveStopNumActionPerformed(evt);
            }
        });

        messagePanel.add(this.messageTitle);
        messagePanel.add(this.text);
        buttonPanel.add(this.button1);
        lowerPanel.add(messagePanel, BorderLayout.WEST);
        lowerPanel.add(buttonPanel, BorderLayout.EAST);
        this.add(pane, BorderLayout.CENTER);
        this.add(lowerPanel, BorderLayout.SOUTH);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // calculate the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;

        int x = (dim.width - w) / 2;
        int y = 0;

        this.setLocation(x, y);
        this.setVisible(true);
    }

    private void saveStopNumActionPerformed(ActionEvent evt) {
        this.stopNum = this.text.getText();
        try {
            if (stopNum == null) {
                new UKDialog("Fields cannot be empty!", "OK");
                return;
            } else if (Integer.parseInt(stopNum) < Integer.parseInt(this.currentStopNum)) {
                new UKDialog("Delivery cannot be before pick up!", "OK");
                return;
            } else if (Integer.parseInt(stopNum) > Integer.parseInt(this.lastStopNum) + 1) {
                new UKDialog("Enter stop number between " + this.currentStopNum + 1 + " and "
                        + this.lastStopNum, "OK");
                return;
            }
        } catch (NumberFormatException e) {
            new UKDialog("Please enter numeric values!", "OK");
            return;
        }

        System.out.println(this.stopNum);
        this.setVisible(false);
        this.dispose();
    }

    public String getStopNum() {
        return this.stopNum;
    }

    private class StopItem extends JPanel {

        private JPanel numPanel = new JPanel();
        private JLabel itemNumber = new JLabel();
        private JPanel leftPanel = new JPanel();
        private JLabel invNoLbl = new JLabel();
        private JLabel consigneeLbl = new JLabel();
        private JLabel locationLbl = new JLabel();
        private final String pUStopNo;
        private final String invoiceNo;
        private final String consignee;
        private final String location;

        public StopItem(String[] invoice) {
            this.pUStopNo = invoice[0];
            this.invoiceNo = invoice[1];
            this.consignee = invoice[2];
            this.location = invoice[3];
            //Left and numberpanels
            this.numPanel.setLayout(new BorderLayout());
            this.numPanel.setPreferredSize(new Dimension(80, 80));
            this.leftPanel.setLayout(new BorderLayout());
            this.leftPanel.setPreferredSize(new Dimension(200, 90));
            //number panel
            this.itemNumber.setFont(new java.awt.Font("Lucida Grande", Font.BOLD, 45));
            this.itemNumber.setText(String.valueOf("  " + pUStopNo));
            //this.numPanel.setBorder(BorderFactory.createEtchedBorder());
            this.numPanel.add(this.itemNumber);
            //Main panel
            this.setLayout(new BorderLayout());
            this.setBorder(BorderFactory.createLineBorder(Color.black, 2));
            this.invNoLbl.setText("Invoice #: " + this.invoiceNo);
            this.invNoLbl.setFont(new java.awt.Font("Calibri", Font.PLAIN, 35));
            this.consigneeLbl.setText("Consignee: " + this.consignee);
            this.consigneeLbl.setFont(new java.awt.Font("Calibri", Font.PLAIN, 35));
            this.locationLbl.setText("Location: " + this.location);
            this.locationLbl.setFont(new java.awt.Font("Calibri", Font.PLAIN, 35));
            this.leftPanel.add(this.invNoLbl, BorderLayout.NORTH);
            this.leftPanel.add(this.consigneeLbl, BorderLayout.CENTER);
            this.leftPanel.add(this.locationLbl, BorderLayout.SOUTH);
            // add all the components to the frame
            this.add(this.numPanel, BorderLayout.WEST);
            this.add(this.leftPanel, BorderLayout.CENTER);
        }
    }

    public static void main(String[] args) throws IOException {
        String[] array1 = {"6", "444555", "Ali Murtaza Sumer", "Carson, Ca 90746"};
        String[] array2 = {"7", "444666", "Hasan Huseyin Karabiber", "Los Angeles, Ca 90746"};
        String[] array3 = {"8", "444777", "Mustafa Tinaztepe", "Macomb, IL 61455"};
        String[] array4 = {"9", "444888", "Berkay Surmeli", "Chicago, IL 60625"};
        String[] array5 = {"6", "444555", "Ali Murtaza Sumer", "Carson, Ca 90746"};
        String[] array6 = {"7", "444666", "Hasan Huseyin Karabiber", "Los Angeles, Ca 90746"};
        String[] array7 = {"8", "444777", "Mustafa Tinaztepe", "Macomb, IL 61455"};
        String[] array8 = {"9", "444888", "Berkay Surmeli", "Chicago, IL 60625"};
        ArrayList<String[]> aL = new ArrayList<>();
        aL.add(array1);
        aL.add(array2);
        aL.add(array3);
        aL.add(array4);
        PAndDeliveryNotification question = new PAndDeliveryNotification(aL, "SAVE");
        question.setDelivStopNo();

    }
}

【问题讨论】:

  • 请发布您的minimal reproducible example
  • 请阅读minimal reproducible example 链接以确切了解我们要求的是什么以及为什么。此外,您应该避免设置组件大小或边界。而是在你的对话框上调用pack(),调用上面提到的每个@LuxxMiner 的方法,你的对话框的大小应该正确并居中。
  • 什么时候设置Dialog的值?也许有一个 repaint() 问题。尝试在显示对话框之前设置值。
  • 生气了?一个简单的单行请求的有趣解释。但说真的,请阅读链接以了解我们需要什么——一个我们可以实际编译和运行的小程序,它可以重现您的问题。发布此内容,我们将快速了解您的问题,因此我们可能会为您提供快速有效的帮助。没有你的代码不是“完整的”。我不能将它粘贴到我的 IDE 中并编译或运行它,可以吗?而且我并不是想“教”你任何东西。我和其他人一样——我试图更好地理解你的问题,仅此而已。
  • 好的,我明白我的问题不完整。老实说,我以为您在谈论我应该使用最少的代码并直截了当。这就是我删除该方法并留下有问题的代码行的原因。我为此道歉。现在,我认为我的问题已经完成,如果您将其复制并粘贴到您的 IDE 中,它应该可以工作。 @HovercraftFullOfEels

标签: java swing


【解决方案1】:

编辑:

您使用了两个 JDialog 扩展类。他们都有 setAlwaysOnTop(true) 和 setModal(true) 因此两者都在争夺视图。也许你应该使用 JFrame 和 JDialog

【讨论】:

  • 在调用setVisible(true) 之后,在这种情况下永远不需要调用repaint()。您提出此建议的依据是什么??
  • 我也是这么想的,但是当我添加 repaint() 调用时问题就解决了。我仍然认为调用 Dialog 的 Class 正在与 Dialog 竞争,因此在完成 setVisible() 之后 MainFrame 立即接收视图,因此对话框无法完成其绘制。但是由于setAlwaysOnTop(),它位于MainFrame 的前面。如果我错了,请纠正我。
  • 没错!我使用this.setAlwaysOnTop(true) 将两个JDialogs 放在一起,导致第二个不加载面板组件。我只是从两者中删除了 setAlwaysOnTop 行,它工作得很好。 this.setModal(true) 无论如何都可以满足我的需求。非常感谢!
猜你喜欢
  • 2013-10-16
  • 2012-08-17
  • 2016-05-10
  • 1970-01-01
  • 2011-09-18
  • 2015-05-04
  • 1970-01-01
  • 2014-10-26
相关资源
最近更新 更多