我正在尝试编写应用程序,该应用程序将在按下按钮时创建新窗口,显示当前窗口计数并在关闭窗口时关闭窗口和线程。
所以基本上,功能是这样的(其中一些正在工作):
- 启动应用程序时显示窗口(确定)
- 按下按钮创建新窗口(确定)
- 按下按钮时显示当前窗口计数(创建时确定,关闭窗口时确定)
- 按下“X”时销毁窗口(确定)
- 关闭原始窗口时销毁主线程(NOK)
这是我的代码:
package projectpackage;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
class MyMouseEvent extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
MyWindowThread.incrementMyWindowThreadCount();
MyWindowThread obj1 = new MyWindowThread();
Thread thr1 = new Thread(obj1);
thr1.start();
}
}
class MyWindowThread extends JFrame implements Runnable
{
private int height;
private int width;
private static int MyWindowThreadCount = 1;
public static int getMyWindowThreadCount()
{
return MyWindowThreadCount;
}
public static void incrementMyWindowThreadCount()
{
MyWindowThreadCount++;
}
public static void decrementMyWindowThreadCount()
{
MyWindowThreadCount--;
}
public MyWindowThread()
{
super("Frame "+getMyWindowThreadCount());
this.setHeight(300);
this.setWidth(400);
this.setBounds(100,100,getWidth(),getHeight());
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
MyWindowThread.decrementMyWindowThreadCount();
//Thread.currentThread().interrupt();
return;
}
}
);
JPanel panel1 = new JPanel();
JButton button1 = new JButton("New window");
JButton button2 = new JButton("Count running windows");
this.getContentPane().add(panel1);
panel1.add(button1);
panel1.add(button2);
button1.addMouseListener(new MyMouseEvent());
button2.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
javax.swing.JOptionPane.showMessageDialog(null,"Window count = " + MyWindowThread.getMyWindowThreadCount());
}
}
);
this.setVisible(true); // show frame
}
public int getHeight()
{
return this.height;
}
public void setHeight(int h)
{
this.height = h;
}
public int getWidth()
{
return this.width;
}
public void setWidth(int w)
{
this.width = w;
}
public void run()
{
}
}
public class MyApp
{
public static void main(String[] args)
{
// Creating objects START
MyWindowThread obj1 = new MyWindowThread();
Thread thr1 = new Thread(obj1);
thr1.start();
}
}
清单.mf:
清单版本:1.0 主类:projectpackage.MyApp
我希望您知道如何在控制台中编译和运行 Java 应用程序。如果你不这样做,这里是:
(在 CLI 中导航到包含“projectpackage”目录的目录。*.java 文件必须在“projectpackage”目录中)
javac 项目包\*.java jar cfm MyApp.jar manifest.mf projectpackage\* java -jar MyApp.jar
谁能告诉我我做错了什么,或者我需要做什么才能使代码正常工作?还是我只是有基本的误解?