java frame中打开frame_java – 我需要从另一个JFrame启动一个JFrame...

您可能能够调整使用的基于Swing的Launcher

ProcessBuilder在单独的JVM中运行程序.

4d59dca7b1180178c506f73a22951f03.png

package gui;

import java.awt.EventQueue;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.IOException;

import javax.swing.BorderFactory;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

/**

* @see https://stackoverflow.com/a/5696404/230513

*/

public class Launcher extends JPanel implements Runnable {

private final JLabel label = new JLabel();

private final JButton launch = new JButton();

ProcessBuilder pb = new ProcessBuilder(

"java", "-cp", "build/classes", "gui.Launcher$DialogTest");

private volatile Process proc;

public static void main(String[] args) {

EventQueue.invokeLater(new Launcher()::createGUI);

}

private void createGUI() {

final JFrame frame = new JFrame();

frame.setLayout(new GridLayout(0, 1));

frame.add(new Launcher());

frame.add(new Launcher());

frame.add(new Launcher());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

public Launcher() {

this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

this.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

launch.setAlignmentX(0.5f);

label.setAlignmentX(0.5f);

launch.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

if (proc == null) {

launch.setText("Terminate");

label.setText("Status: run");

new Thread(Launcher.this).start();

} else {

proc.destroy();

reset();

}

}

});

this.add(launch);

this.add(label);

reset();

}

@Override

public void run() {

try {

proc = pb.start();

proc.waitFor();

} catch (IOException | InterruptedException ex) {

ex.printStackTrace(System.err);

}

EventQueue.invokeLater(this::reset);

}

private void reset() {

proc = null;

launch.setText("Launch");

label.setText("Status: idle");

}

private static class DialogTest {

public static void main(String[] args) {

EventQueue.invokeLater(() -> {

JOptionPane.showMessageDialog(null, "Running",

"Test", JOptionPane.INFORMATION_MESSAGE);

System.exit(0);

});

}

}

}

根据作者的要求更新到Java 8.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值