GVKun编程网logo

在java / swing中关闭Windows时应采取的正确措施是什么?(java swing关闭当前窗口)

19

对于在java/swing中关闭Windows时应采取的正确措施是什么?感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解javaswing关闭当前窗口,并且为您提供关于JavaSwing中的

对于在java / swing中关闭Windows时应采取的正确措施是什么?感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解java swing关闭当前窗口,并且为您提供关于Java Swing中的控制器是什么?、java – Swing在减少Windows时间后忽略第一次单击、MySQL运行内存不足时应采取的措施、powershell – 如何在Windows 10中从命令行打开/关闭Windows功能?的宝贵知识。

本文目录一览:

在java / swing中关闭Windows时应采取的正确措施是什么?(java swing关闭当前窗口)

在java / swing中关闭Windows时应采取的正确措施是什么?(java swing关闭当前窗口)

我刚刚在CustomUIPanel类中编写了以下测试代码:

public static void main(String[] args) {    final JDialog dialog = CustomUIPanel.createDialog(null,        CustomUIPanel.selectFile());    dialog.addWindowListener(new WindowAdapter() {        @Override public void windowClosing(WindowEvent e) {            System.exit(0);        }    });}

它是否CustomUIPanel.main()是程序的入口点,它可以正常工作,但是让我感到奇怪:如果另一个类需要CustomUIPanel.main()进行测试,该怎么办?那我打给我System.exit(0)是不正确的。

如果没有顶层窗口,是否有办法告诉Swing事件分配线程自动退出?

如果不是,如果目标是在所有顶级窗口都关闭时退出程序,那么JDialog / JFrame在关闭时应该做什么呢?

答案1

小编典典

您可以使用的setDefaultCloseOperation()方法JDialog,指定DISPOSE_ON_CLOSE

setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

另请参见12.8程序退出。

附录:包含@camickr的有用答案,当关闭窗口或按下关闭按钮时,此示例退出。

import java.awt.EventQueue;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.WindowEvent;import javax.swing.AbstractAction;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;/** @see http://stackoverflow.com/questions/5540354 */public class DialogClose extends JDialog {    public DialogClose() {        this.setLayout(new GridLayout(0, 1));        this.add(new JLabel("Dialog close test.", JLabel.CENTER));        this.add(new JButton(new AbstractAction("Close") {            @Override            public void actionPerformed(ActionEvent e) {                DialogClose.this.setVisible(false);                DialogClose.this.dispatchEvent(new WindowEvent(                    DialogClose.this, WindowEvent.WINDOW_CLOSING));            }        }));    }    private void display() {        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);        this.pack();        this.setLocationRelativeTo(null);        this.setVisible(true);    }    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            @Override            public void run() {                new DialogClose().display();            }        });    }}

Java Swing中的控制器是什么?

Java Swing中的控制器是什么?

我想以有意义的方式使用Swing将MVC设计应用于Java应用程序。因此,我的问题是,如何在Java Swing中构造控制器?

我有两个选择:

  1. 每个组件侦听器都是自己的类,作为控制器包的一部分
  2. 每个组件侦听器都是视图包中的一个匿名类,该类将其调用委托给具有控制器方法的类。

两者都有可能吗?是偏好问题还是明确定义的?

答案1

小编典典

Controller构成了组件接口的另一半,主要是交互的一半。控制器负责鼠标和键盘事件。

在Swing JButton等组件中是控制器。所有侦听器类都将事件重定向到具有您的业务逻辑的模型

例如:

主程序

import javax.swing.*;public class CalcMVC {    //... Create model, view, and controller.  They are    //    created once here and passed to the parts that    //    need them so there is only one copy of each.    public static void main(String[] args) {        CalcModel      model      = new CalcModel();        CalcView       view       = new CalcView(model);        CalcController controller = new CalcController(model, view);        view.setVisible(true);    }}

视图

import java.awt.*;import javax.swing.*;import java.awt.event.*;class CalcView extends JFrame {    //... Constants    private static final String INITIAL_VALUE = "1";    //... Components    private JTextField m_userInputTf = new JTextField(5);    private JTextField m_totalTf     = new JTextField(20);    private JButton    m_multiplyBtn = new JButton("Multiply");    private JButton    m_clearBtn    = new JButton("Clear");    private CalcModel m_model;    //======================================================= constructor    /** Constructor */    CalcView(CalcModel model) {        //... Set up the logic        m_model = model;        m_model.setValue(INITIAL_VALUE);        //... Initialize components        m_totalTf.setText(m_model.getValue());        m_totalTf.setEditable(false);        //... Layout the components.              JPanel content = new JPanel();        content.setLayout(new FlowLayout());        content.add(new JLabel("Input"));        content.add(m_userInputTf);        content.add(m_multiplyBtn);        content.add(new JLabel("Total"));        content.add(m_totalTf);        content.add(m_clearBtn);        //... finalize layout        this.setContentPane(content);        this.pack();        this.setTitle("Simple Calc - MVC");        // The window closing event should probably be passed to the         // Controller in a real program, but this is a short example.        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    }    void reset() {        m_totalTf.setText(INITIAL_VALUE);    }    String getUserInput() {        return m_userInputTf.getText();    }    void setTotal(String newTotal) {        m_totalTf.setText(newTotal);    }    void showError(String errMessage) {        JOptionPane.showMessageDialog(this, errMessage);    }    void addMultiplyListener(ActionListener mal) {        m_multiplyBtn.addActionListener(mal);    }    void addClearListener(ActionListener cal) {        m_clearBtn.addActionListener(cal);    }}

控制者

import java.awt.event.*;public class CalcController {    //... The Controller needs to interact with both the Model and View.    private CalcModel m_model;    private CalcView  m_view;    //========================================================== constructor    /** Constructor */    CalcController(CalcModel model, CalcView view) {        m_model = model;        m_view  = view;        //... Add listeners to the view.        view.addMultiplyListener(new MultiplyListener());        view.addClearListener(new ClearListener());    }    ////////////////////////////////////////// inner class MultiplyListener    /** When a mulitplication is requested.     *  1. Get the user input number from the View.     *  2. Call the model to mulitply by this number.     *  3. Get the result from the Model.     *  4. Tell the View to display the result.     * If there was an error, tell the View to display it.     */    class MultiplyListener implements ActionListener {        public void actionPerformed(ActionEvent e) {            String userInput = "";            try {                userInput = m_view.getUserInput();                m_model.multiplyBy(userInput);                m_view.setTotal(m_model.getValue());            } catch (NumberFormatException nfex) {                m_view.showError("Bad input: ''" + userInput + "''");            }        }    }//end inner class MultiplyListener    //////////////////////////////////////////// inner class ClearListener    /**  1. Reset model.     *   2. Reset View.     */        class ClearListener implements ActionListener {        public void actionPerformed(ActionEvent e) {            m_model.reset();            m_view.reset();        }    }// end inner class ClearListener}

模型

import java.math.BigInteger;public class CalcModel {    //... Constants    private static final String INITIAL_VALUE = "0";    //... Member variable defining state of calculator.    private BigInteger m_total;  // The total current value state.    //============================================================== constructor    /** Constructor */    CalcModel() {        reset();    }    //==================================================================== reset    /** Reset to initial value. */    public void reset() {        m_total = new BigInteger(INITIAL_VALUE);    }    //=============================================================== multiplyBy    /** Multiply current total by a number.    *@param operand Number (as string) to multiply total by.    */    public void multiplyBy(String operand) {        m_total = m_total.multiply(new BigInteger(operand));    }    //================================================================= setValue    /** Set the total value.     *@param value New value that should be used for the calculator total.     */    public void setValue(String value) {        m_total = new BigInteger(value);    }    //================================================================= getValue    /** Return current calculator total. */    public String getValue() {        return m_total.toString();    }}

java – Swing在减少Windows时间后忽略第一次单击

java – Swing在减少Windows时间后忽略第一次单击

我有一个处理日期和时间的Swing应用程序,所以很多测试都在改变系统的日期和时间设置.
在测试期间,我们注意到在减少时钟后,应用程序将忽略第一次单击.

这是Swing / Java / Windows的错误吗?这有解决方法吗?

有趣的是,只有在减少日期/时间设置时才会出现此问题.如果我增加它,应用程序行为正常.

情况:

> Swing应用程序正在运行.
>减少Windows日期和时间设置(例如,将时间从15:00更改为14:00).
>请注意,Swing应用程序中的第一次单击不会触发任何操作.

代码示例(您可以使用它来证明情况):

import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;

    import javax.swing.JButton;
    import javax.swing.JFrame;

    public class Main {

        public static void main(String[] args) {
            final JFrame frame = new JFrame("frame");
            final JButton button = new JButton("button");
            button.addActionListener(new ActionListener() {

                public void actionPerformed(final ActionEvent e) {
                    System.out.println("Button pressed!");
                }
            });

            frame.add(button);
            frame.setSize(200,200);
            frame.setVisible(true);
            frame.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosing(final WindowEvent e) {
                    System.exit(0);
                }
            });
        }

    }

解决方法

如 here所示,Swing使用日期来检查事件何时发生.因此,在某种程度上,通过放弃您的操作,处理程序在此处起作用,因为它发生在“最后一个操作之前”.我不能确认你这个,但是有些布局管理器或其他处理程序在这里搞乱了一些东西,以防止延迟事件搞乱当前流程.

MySQL运行内存不足时应采取的措施

MySQL运行内存不足时应采取的措施

导读

排除故障指南:MySQL运行内存不足时应采取的措施?

原文出处:《What To Do When MySQL Runs Out of Memory: Troubleshooting Guide》

https://www.percona.com/blog/2018/06/28/what-to-do-when-mysql-runs-out-of-memory-troubleshooting-guide/

原文作者:Alexander Rubin

关键词:memory、memory leaks、Memory Usage、MySQL server memory usage、MySQL Troubleshooting、Troubleshooting MySQL、troubleshooting tips

Troubleshooting crashes is never a fun task, especially if MySQL does not report the cause of the crash. For example, when MySQL runs out of memory. Peter Zaitsev wrote a blog post in 2012: Troubleshooting MySQL Memory Usage with a lots of useful tips. With the new versions of MySQL (5.7+) and performance_schema we have the ability to troubleshoot MySQL memory allocation much more easily。
崩溃故障诊断绝不是一个有趣的任务,尤其如果MySQL没有报告崩溃的原因时,例如MySQL运行时内存溢出。Peter Zaitsev 在2012年写了一篇文章Troubleshooting MySQL Memory Usage 里面有很多有用的提示,使用新版本MySQL(5.7+)结合performance_schema,我们可以更轻松地解决MySQL内存分配问题。

In this blog post I will show you how to use it.

First of all, there are 3 major cases when MySQL will crash due to running out of memory:

  1. MySQL tries to allocate more memory than available because we specifically told it to do so. For example: you did not set innodb_buffer_pool_size correctly. This is very easy to fix

  2. There is some other process(es) on the server that allocates RAM. It can be the application (java, python, php), web server or even the backup (i.e. mysqldump). When the source of the problem is identified, it is straightforward to fix.

  3. Memory leaks in MySQL. This is a worst case scenario, and we need to troubleshoot.

在这篇博文中,我将向你展示如何使用它。

首先,MySQL因为内存溢出发生崩溃主要有以下三种情况:

  1. MySQL试图分配比可用内存更多的内存,因为我们特意告诉它这样做;比如你没有正确的设置innodb_buffer_pool_size,那这种情况很好解决。

  2. 服务器上有其他一些进程分配了RAM内存,可能是应用程序(java/python/php)、web服务器,或者甚至备份(比如mysqldump),确定问题的根源后,可以直接修复。

  3. MySQL内存泄漏,这是最糟糕的情况,这时需要我们进行故障诊断。

 

Where to start troubleshooting MySQL memory leaks

 

从哪里开始诊断MySQL内存泄漏的问题

Here is what we can start with (assuming it is a Linux server):

假设是一个linux服务器,我们可以从以下开始:

Part 1: Linux OS and config check

  1. Identify the crash by checking mysql error log and Linux log file (i.e. /var/log/messages or /var/log/syslog). You may see an entry saying that OOM Killer killed MySQL. Whenever MySQL has been killed by OOM “dmesg” also shows details about the circumstances surrounding it.

  2. Check the available RAM:

    1. free -g

    2. cat /proc/meminfo

  3. Check what applications are using RAM: “top” or “htop” (see the resident vs virtual memory)

  4. Check mysql configuration: check /etc/my.cnf or in general /etc/my* (including /etc/mysql/* and other files). MySQL may be running with the different my.cnf (run ps ax| grep mysql )

  5. Run vmstat 5 5 to see if the system is reading/writing via virtual memory and if it is swapping

  6. For non-production environments we can use other tools (like Valgrind, gdb, etc) to examine MySQL usage

第一部分: Linux 系统和配置检查

  1. 通过检查mysql error日志和linux日志(比如,/var/log/messages 或者 /var/log/syslog)确认崩溃。你可能会看到一条条目说OOM Killer杀死了MySQL,每当MySQL被OOM杀死时,“dmesg”也会显示有关它周围情况的详细信息。

  2. 检查可用的RAM内存:

    1. free -g

    2. cat /proc/meminfo

  3. 检查什么程序在使用内存:"top"或者htop(看resident和virtual列)

  4. 检查mysql的配置:检查/etc/my.cnf或者一般的/etc/my*(包括/etc/mysql/*和其他文件);
    MySQL 可能跟着不同的my.cnf运行(用ps ax | grep mysql)

  5. 运行vmstat 5 5 查看系统是否通过虚拟内存进行读写以及是否正在进行swap交换

  6. 对于非生产环境,我们可以使用其他工具(如Valgrind、gdb等)来检查MySQL的使用情况。

Part 2: Checks inside MySQL
Now we can check things inside MySQL to look for potential MySQL memory leaks.
MySQL allocates memory in tons of places. Especially:

  1. Table cache

  2. Performance_schema (run: show engine performance_schema status and look at the last line). That may be the cause for the systems with small amount of RAM, i.e. 1G or less

  3. InnoDB (run show engine innodb status and check the buffer pool section, memory allocated for buffer_pool and related caches)

  4. Temporary tables in RAM (find all in-memory tables by running: select * from information_schema.tables where engine=''MEMORY'' )

  5. Prepared statements, when it is not deallocated (check the number of prepared commands via deallocate command by running show global status like ‘ Com_prepare_sql'';show global status like ''Com_dealloc_sql'' )

第二部分: 检查MySQL内部

现在我们可以检查MySQL内部的东西来寻找潜在的MySQL内存泄漏情况:
MySQL在很多地方分配内存,尤其:

  1. 表缓存

  2. Performance_schema(运行:show engine performance_schema status 然后看最后一行),这可能在系统RAM比较少(1G或更少)时的可能原因。

  3. InnoDB(运行show engine innodb status 检查 buffer pool部分,为buffer pool及相关缓存分配的内存)

  4. 内存中的临时表(查看所有内存表:select * from information_schema.tables where engine=''MEMORY'')

  5. 预处理语句,当他们没有被释放时(通过运行show global status like ''Com_prepare_sql''和show global status like ''Com_dealloc_sql''来检查通过deallocate命令释放的预处理语句)

The good news is: starting with MySQL 5.7 we have memory allocation in performance_schema. Here is how we can use it.
好消息是,从5.7开始我们可以通过performance_schema查看内存的分配情况。下面就展示如何使用它:

  • First, we need to enable collecting memory metrics. Run:

UPDATE setup_instruments SET ENABLED = ''YES'' WHERE NAME LIKE ''memory/%'';
  • Run the report from sys schema:

select event_name, current_alloc, high_alloc from sys.memory_global_by_current_bytes where current_count > 0;
  • Usually this will give you the place in code when memory is allocated. It is usually self-explanatory. In some cases we can search for bugs or we might need to check the MySQL source code.

  • 首先,我们需要启用收集内存指标,运行如下语句:

UPDATE setup_instruments SET ENABLED = ''YES'' WHERE NAME LIKE ''memory/%'';
  • 运行sys schema里面的报告

select event_name,current_alloc,high_alloc from sys.memory_global_by_current_bytes where current_count > 0;
  • 通常,这将在分配内存时为你提供代码,它通常是不言自明的。在某些情况下,我们可以搜索错误,或者我们可能需要检查MySQL源代码。

For example, for the bug where memory was over-allocated in triggers (https://bugs.mysql.com/bug.php?id=86821) the select shows:

例如,有一个过度为触发器分配内存的bug:

https://bugs.mysql.com/bug.php?id=86821

查询的显示如下:

The largest chunk of RAM is usually the buffer pool but ~3G in stored procedures seems to be too high.
分配最大一块内存通常是buffer pool,但是约3G的存储过程似乎有点太高了.

According to the MySQL source code documentation, sp_head represents one instance of a stored program which might be of any type (stored procedure, function, trigger, event). In the above case we have a potential memory leak.
根据MySQL source code documentation,sp_head表示存储程序里面的一个实例(比如存储过程、函数、触发器,及事件)。在上面的例子,我们有潜在的内存泄漏的风险。

In addition we can get a total report for each higher level event if we want to see from the birds eye what is eating memory:
另外,我们想要鸟瞰什么吃掉了内存,我们可以获得每个事件更高级别活动的总体报告。

I hope those simple steps can help troubleshoot MySQL crashes due to running out of memory.
我希望这些简单的步骤可以帮助解决由于内存溢出导致的MySQL崩溃问题。

powershell – 如何在Windows 10中从命令行打开/关闭Windows功能?

powershell – 如何在Windows 10中从命令行打开/关闭Windows功能?

在 Windows 10和“程序和功能”中,您可以打开或关闭Windows功能,然后启动下载和安装.我希望打开“.Net Framework 3.5”,并将其下载并安装,但我需要通过例如一个Powershell脚本或通过命令.我需要使用命令行.

怎么能实现这一目标?

以管理员身份运行命令提示符并使用:
dism /online /Get-Features

这将显示功能名称,因为它们并不总是与您在该可视功能列表中看到的内容相匹配.它还将显示当前启用/禁用的内容.找到要启用的功能(本例中为NetFx3)后,运行以下命令:

dism /online /Enable-Feature /FeatureName:NetFx3

正如理查德所说,你可以通过简单地将“启用”切换为“禁用”来禁用某项功能.

dism /online /disable-Feature /FeatureName:NetFx3

注意:有时需要重新启动才能查看Windows功能的更改.

关于在java / swing中关闭Windows时应采取的正确措施是什么?java swing关闭当前窗口的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Java Swing中的控制器是什么?、java – Swing在减少Windows时间后忽略第一次单击、MySQL运行内存不足时应采取的措施、powershell – 如何在Windows 10中从命令行打开/关闭Windows功能?的相关信息,请在本站寻找。

本文标签: