我正在尝试创建一个 GUI 界面来启动和停止具有不同返回字符串的 Jetty 服务器。目前我已经编程了一个开始和停止按钮,它将“Hello World”返回到 localhost:8080。我的代码发布在下面,是的,我有导入,删除以简化它。
public class JettyGUI extends AbstractHandler{
private static Server server = new Server(8080);
private static boolean running = false;
private static void gui() {
JFrame frame = new JFrame("Jetty");
JButton start_button = new JButton("Start");
JButton stop_button = new JButton("Stop");
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.add(start_button);
panel.add(stop_button);
frame.add(panel);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
start_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Start pressed.");
startServer();
}
});
stop_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Stop pressed.");
JettyGUI.stopServer();
}
});
}
private static void stopServer() {
if(running == false){
System.err.println("Server is already running!");
}
else{
try {
server.stop();
}
catch (Exception ex) {
System.out.println(ex);
}
}
System.out.println("Server stopped!");
}
private static void startServer() {
if(running == true){
System.err.println("Server is already running!");
}
else{
try{
server.setHandler(new JettyGUI());
server.start();
server.join();
}
catch(Exception ex){
System.out.println(ex);
}
System.out.println("Server started!");
}
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("Hello World!"); //print this text
}
public static void main(String[] args) {
gui();
}
}
当我按下“开始”按钮时,Jetty API 似乎接管了我的应用程序,我无法再按下“停止”按钮。谁能告诉我一种绕过这个或以不同方式编程的方法?
谢谢!:) -亨利哈里斯