java 自定义窗口

简介

简单 java 核心编程

code

/*
 * @Author: your name
 * @Date: 2020-11-08 14:44:58
 * @LastEditTime: 2020-11-08 14:45:24
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: /java/dialog/AboutDialog.java
 */
package dialog;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * A sample modal dialog that displays a message and waits for the user to click
 * the OK button.
 */
public class AboutDialog extends JDialog {
   public AboutDialog(JFrame owner) {
      super(owner, "About DialogTest", true);

      // add HTML label to center

      add(new JLabel("<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"), BorderLayout.CENTER);

      // OK button closes the dialog

      var ok = new JButton("OK");
      ok.addActionListener(event -> setVisible(false));

      // add OK button to southern border

      var panel = new JPanel();
      panel.add(ok);
      add(panel, BorderLayout.SOUTH);

      pack();
   }
}

package dialog;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 * A frame with a menu whose File->About action shows a dialog.
 */
public class DialogFrame extends JFrame {
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 200;
   private AboutDialog dialog;

   public DialogFrame() {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // construct a File menu

      var menuBar = new JMenuBar();
      setJMenuBar(menuBar);
      var fileMenu = new JMenu("File");
      menuBar.add(fileMenu);

      // add About and Exit menu items

      // the About item shows the About dialog

      var aboutItem = new JMenuItem("About");
      aboutItem.addActionListener(event -> {
         if (dialog == null) // first time
            dialog = new AboutDialog(DialogFrame.this);
         dialog.setVisible(true); // pop up dialog
      });
      fileMenu.add(aboutItem);

      // the Exit item exits the program

      var exitItem = new JMenuItem("Exit");
      exitItem.addActionListener(event -> System.exit(0));
      fileMenu.add(exitItem);
   }
}

/*
 * @Author: your name
 * @Date: 2020-11-08 14:44:58
 * @LastEditTime: 2020-11-08 14:45:17
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: /java/dialog/DialogTest.java
 */
package dialog;

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

/**
 * @version 1.35 2018-04-10
 * @author Cay Horstmann
 */
public class DialogTest {
   public static void main(String[] args) {
      EventQueue.invokeLater(() -> {
         var frame = new DialogFrame();
         frame.setTitle("DialogTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

上一篇:gridview中添加新item


下一篇:Qt 模态对话框和非模态对话框