我有一个java 应用程序( index.java
),如果我执行它,我会浏览它的不同JFrame
或JDialog
没有问题等。
我的疑问/问题/查询是:有什么方法不允许在index.java
另一个过程中打开index.java
吗?如果尝试重新打开它(如果它已打开),请显示一条消息:“它正在使用中”。
我希望我已经解释了自己。
代码:
public class Index extends javax.swing.JFrame {
public Index() {
initComponents();
//Fondo del JFrame en color gris.
getContentPane().setBackground(Color.gray);
//Código para confirmar el cierre de la ventana principal.
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt){
if (JOptionPane.showConfirmDialog(rootPane, "¿Desea salir de la aplicación?", "Salir de la aplicación",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
System.exit(0);
}
});
//Situamos el JDialog en el centro de la pantalla.
setLocationRelativeTo(null);
//No redimensionable.
setResizable(false);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Index().setVisible(true);
}
});
}
}
如果实例在两个不同的虚拟机中运行,则不是直接来自 java 端。但是,您可以使用锁定文件来解决问题。
在您开始的主要方法中:
简单地避免应用程序的第二个实例的替代方法是使用 a
ServerSocket
来保证没有两个实例正在运行,并将后续启动的参数传递给同一个应用程序:伪代码思想
我现在没有 java,但我可以在此页面上找到以下示例:
以下文字不是我创建的,您可以在此处访问源代码
关于用法的示例:http://www.w3api.com/wiki/Java:FileChannel.tryLock()
您好,您可以使用 junique-1.0.4 库来做到这一点 JUnique 库可用于防止用户同时运行同一 Java 应用程序的多个实例。JUnique 在同一用户启动的所有 JVM 实例之间实现共享锁和通信通道。您可以在互联网上搜索如何使用它。