窗口居中时不显示Java组件

窗口居中时不显示Java组件,java,swing,Java,Swing,我有一个奇怪的问题,我不知道这是什么原因。 我有一个对话框类,它只是在屏幕上显示一条错误/警告消息。有趣的是,当我设置窗口中心时,组件不会出现(除非我重新调整其大小) 但是,当我更改屏幕位置时,组件在JPanel上显示得很好 我基本上将这一行改为intx=(dim.width-w)/3并且它可以工作。但当宽度除以2时,情况并非如此。因此,该对话框可以在除中心以外的任何位置工作。请让我知道我错过了什么 谢谢你的帮助 谢谢大家! 代码如下: MCVE: import java.awt.*; i

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

但是,当我更改屏幕位置时,组件在JPanel上显示得很好

我基本上将这一行改为
intx=(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);
         }
      });    
   }
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
@抑制警告(“串行”)
公共类UKDALOG扩展JDialog{
私人按钮1;
私有JLabel消息;
公共对话框(字符串消息、字符串按钮文本){
this.button1=新的JButton(buttonText);
this.message=新的JLabel(消息);
setWarning();
}
公共无效设置警告(){
此.setModal(true);
此.setAlwaysOnTop(true);
if(this.message.getText().length()30){
此设置最大尺寸(新尺寸(870300));
此设置最小尺寸(新尺寸(870300));
此.setPreferredSize(新尺寸(870300));
}
此.setLayout(新的BorderLayout());
JPanel messagePanel=新的JPanel();
messagePanel.setboorder(BorderFactory.createtchedborder());
JPanel buttonPanel=newjpanel(newflowlayout(FlowLayout.CENTER));
buttonPanel.setBorder(BorderFactory.createEtchedBorder());
按钮面板设置首选尺寸(新尺寸(600100));
this.message.setFont(新字体(“Calibri”,Font.BOLD,40));
此.button1.setPreferredSize(新尺寸(230,80));
这个.button1.setFont(新字体(“Calibri”,Font.BOLD,45));
这个.button1.setBackground(新java.awt.Color(139,71137));
this.button1.set前台(java.awt.Color.white);
this.button1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
执行的操作(evt);
}
});
messagePanel.add(this.message,BorderLayout.CENTER);
buttonPanel.add(此按钮1);
添加(messagePanel,BorderLayout.CENTER);
添加(buttonPanel,BorderLayout.SOUTH);
//计算窗口的新位置
维度dim=Toolkit.getDefaultToolkit().getScreenSize();
int w=this.getSize().width;
int h=此.getSize()高度;
INTX=(尺寸宽度-w)/2;
int y=(尺寸高度-h)/5;
此设置位置(x,y);
此.setVisible(true);
}
已执行的受保护无效操作(ActionEvent evt){
UKDialog.this.dispose();
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
最终JFrame=新JFrame(“主GUI”);
JButton按钮=新JButton(新抽象动作(“推我”){
@凌驾
已执行的公共无效操作(操作事件e){
String message=“消息足够长吗?”;
字符串buttonText=“Button”;
UKDALOG UKDALOG=新建UKDALOG(消息,按钮文本);
}
});
JPanel面板=新的JPanel();
面板。设置首选尺寸(新尺寸(500400));
面板。添加(按钮);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
框架。添加(面板);
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
});    
}
}
这是我的类用main方法调用warning类

 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();

    }
}
导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.FlowLayout;
导入java.awt.Font;
导入java.awt.Toolkit;
导入java.awt.event.ActionEvent;
导入java.awt.image.buffereImage;
导入java.io.File;
导入java.io.IOException;
导入java.util.ArrayList;
导入javax.imageio.imageio;
导入javax.swing.BorderFactory;
导入javax.swing.JButton;
导入javax.swing.JDialog;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.JScrollPane;
导入javax.swing.JTextField;
导入javax.swing.ScrollPaneLayout;
导入javax.swing.WindowConstants;
公共类PAndDeliveryNotification扩展了JDialog{
私人按钮1;
私有JLabel消息标题;
私有JTextField文本;
私有布尔应答;
私有字符串类型文本;
私有阵列列表剩余文件;
私有字符串stopNum=null;
私有字符串currentStopNum,lastStopNum;
公共PAndDeliveryNotification(ArrayList、字符串按钮tex1){
this.button1=新的JButton(buttonext1);
this.remainingvoices=rInvoices;
}
public void setDeliverStopNo()引发IOException{
BuffereImage图像=空;
试一试{
image=ImageIO.read(新文件(“images/uk.png”);
}捕获(IOE异常){
}
此.setIconImage(图像);
//框架属性
此.setModal(true);
此.setAlwaysOnTop(true);
此.setDefaultCloseOperation(WindowConstants.DO\u NOTHING\u\u ON\u CLOSE);
此.setLayout(新的BorderLayout());
//帧大小
此.setPreferredSize(新尺寸(900600));
此设置最大尺寸(新尺寸(900600));
此设置最小尺寸(新尺寸(900600));
JPanel upperPanel=新的JPanel(新的WrapLayout());
upperPanel.setBorder(BorderFactory.createEtchedBorder());
for(int i=0;i