我正在构建一个应用程序,我遇到的最大问题是重新打开该应用程序。
我可以正常启动我的应用程序。 它创建主窗口。 我也在使用
setDefaultCloseOperation(HIDE_ON_CLOSE)
我也尝试过 DISPOSE_ON_CLOSE
但它们都有相同的效果。 所以当我关闭它时,窗口就会关闭。 但是,当我单击停靠栏中的图标时,窗口将不会重新打开。
我希望应用程序像 Safari 一样打开,您可以关闭 Safari,但它仍然在后台运行,当您单击破折号中的图标时,如果您还没有打开任何窗口,它会创建一个新窗口。
要最小化而不是关闭,请使用
JFrame.DO_NOTHING_ON_CLOSE
并处理关闭请求
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
frame.setExtendedState(JFrame.ICONIFIED);
}
});
这会将框架最小化,然后用户可以单击任务栏上的图标来恢复
如上所述,听起来您需要两个进程,一个用于渲染,一个用于处理数据
为了演示这一点,我整理了一些示例代码
在同一文件夹中编译并运行 TestClient
TestClient.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestClient
{
public static void main(String[] args) throws Exception
{
Socket socket = null;
try
{
System.out.println("Connecting to backend");
socket = new Socket("localhost", 28000); //check if backend is running
}
catch(IOException e) //backend isn't running
{
System.out.println("Backend isn't running");
System.out.println("Starting backend");
Runtime.getRuntime().exec("cmd /c java TestServer"); //start the backend
for(int i = 0; i < 10; i++) //attempt to connect
{
Thread.sleep(500);
System.out.println("Attempting connection " + i);
try
{
socket = new Socket("localhost", 28000);
break;
}
catch(IOException ex){}
}
}
if(socket == null)
{
System.err.println("Could not start/connect to the backend");
System.exit(1);
}
System.out.println("Connected");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line = reader.readLine();
System.out.println("read " + line);
if(line.equals("refused")) //already a client connected
{
System.err.println("Already a client connected to the backend");
System.exit(1);
}
//set up the GUI
JFrame frame = new JFrame("TestClient");
frame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel(line);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
frame.add(label, c);
String[] buttonLabels = {"A", "B", "Quit"};
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
try
{
switch(e.getActionCommand())
{
case "A":
writer.write("A");
writer.newLine();
writer.flush();
break;
case "B":
writer.write("B");
writer.newLine();
writer.flush();
break;
case "Quit":
writer.write("Quit");
writer.newLine();
writer.flush();
System.exit(0);
break;
}
}
catch(IOException ex)
{
ex.printStackTrace();
System.exit(1);
}
}
};
c.gridy = 1;
c.gridx = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
for(String s : buttonLabels)
{
JButton button = new JButton(s);
button.addActionListener(listener);
frame.add(button, c);
}
//start a thread to listen to the server
new Thread(new Runnable()
{
public void run()
{
try
{
for(String line = reader.readLine(); line != null; line = reader.readLine())
label.setText(line);
}
catch(IOException e)
{
System.out.println("Lost connection with server (probably server closed)");
e.printStackTrace();
System.exit(0);
}
}
}).start();
//display the gui
System.out.println("Displaying");
frame.pack();
frame.setResizable(false);
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
测试服务器.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class TestServer
{
private static boolean multipleClients = true;
private static List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) throws Exception
{
System.out.println("did the thing");
ServerSocket ss = new ServerSocket(28000, 0, InetAddress.getByName(null));
int[] index = {0}; //array so threads can access
char[] data = {'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'};
//start accepting connections
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Client c = new Client(ss.accept());
if(multipleClients || clients.isEmpty())
{
System.out.println("writing " + new String(data));
c.write(displayData(data, index[0])); //write initial data
synchronized(clients)
{
clients.add(c);
}
}
else
c.write("refused");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}).start();
//read and write to clients
String msg = null;
while(true)
{
//read changes
synchronized(clients)
{
for(Client c : clients)
if((msg = c.read()) != null)
{
switch(msg)
{
case "A":
data[index[0]++] = 'A';
break;
case "B":
data[index[0]++] = 'B';
break;
case "Quit":
System.exit(0);
break;
}
index[0] %= data.length;
for(Client C : clients)
C.write(displayData(data, index[0]));
}
}
Thread.sleep(50);
}
}
private static String displayData(char[] data, int i)
{
return "<html>" + new String(data, 0, i) + "<u>" + data[i] + "</u>" + new String(data, i + 1, data.length - i - 1) + "</html>";
}
private static class Client
{
private BufferedReader reader;
private BufferedWriter writer;
private Queue<String> readBuffer;
private Client me;
public Client(Socket s) throws IOException
{
reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
readBuffer = new LinkedList<String>();
me = this;
new Thread(new Runnable()
{
public void run()
{
try
{
for(String line = reader.readLine(); line != null; line = reader.readLine())
readBuffer.add(line);
}
catch(IOException e)
{
System.out.println("Client disconnected");
e.printStackTrace();
synchronized(clients)
{
clients.remove(me); //remove(this) attempts to remove runnable from clients
}
System.out.println("removed " + clients.isEmpty());
}
}
}).start();
}
public String read()
{
return readBuffer.poll();
}
public void write(String s)
{
try
{
writer.write(s);
writer.newLine();
writer.flush();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
当您点击窗口中的“X”按钮时,您可以将框架设置为 HIDE_ON_CLOSE
您需要创建类似这样的代码:
检查我们是否有 2 个具有不同操作的按钮(其中之一是在关闭框架后设置框架可见)
try {
Main_view frame = new Main_view();
frame.setVisible(true);
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
TrayIcon trayIcon = null;
//Listener for exit button
ActionListener ExitListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
//Listener for display button
ActionListener DisplayListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
};
//Menu when you right click the icon
PopupMenu popup = new PopupMenu();
//Buttons to show
MenuItem displayButton = new MenuItem("Display");
MenuItem exitButton = new MenuItem("Exit");
//add the previous actions made it
exitButton.addActionListener(ExitListener);
displayButton.addActionListener(DisplayListener);
//add to the popup
popup.add(displayButton);
popup.add(exitButton);
// URL: MyProject/src/MyGUI/check.png
// Small icon on secondary taskbar
Image image= ImageIO.read(getClass().getResource("/MyGUI/check.png"));
trayIcon = new TrayIcon(image, "App name", popup);
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(DisplayListener);
trayIcon.addActionListener(ExitListener);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
} else {
// disable tray option in your application or
// perform other actions
}
} catch (Exception e) {
e.printStackTrace();
}