Foros del Web » Programación para mayores de 30 ;) » Java »

cargar una clase sin main ??

Estas en el tema de cargar una clase sin main ?? en el foro de Java en Foros del Web. obtuve un codigo de una clase que se llama a traves de un menu con muchas otras opciones y a mi solo me interesa esta. ...
  #1 (permalink)  
Antiguo 29/04/2006, 22:37
 
Fecha de Ingreso: diciembre-2004
Mensajes: 59
Antigüedad: 19 años, 4 meses
Puntos: 0
cargar una clase sin main ??

obtuve un codigo de una clase que se llama a traves de un menu con muchas otras opciones y a mi solo me interesa esta. luego de obtener todas las fuentes cuando la compilo, reclama que no hay main. luego intente probando con todo lo que se me ocurrio y fui incapaz de hacer que cargue, ya que compila bien.

si la clase es del tipo:

public class s extends ...
{
....
public s(Window parent)
{
super(parent);
}

public void initialize() throws Exception
{
a = new Jlabel("a");
....
super.initialize();
}

public static void main(String[] args)
{

?????????????

}


que debo poner en el main para que cargue ??

debe ser super sencillo, pero no estoy muy habituado a la OO de java.

Gracias
  #2 (permalink)  
Antiguo 29/04/2006, 23:03
Avatar de chuidiang
Colaborador
 
Fecha de Ingreso: octubre-2004
Mensajes: 3.774
Antigüedad: 19 años, 7 meses
Puntos: 454
Hola:

Al compilar no debería protestar de que no hay main(). La protesta se debería producir si intentas ejecutar esa clase y no lleva main.

En el main simplmente debes poner esto

s ventana = new s(null);
s.initialize();
s.setVisible(true);

De todas formas, es una deduccion que puede no ser acertada.
Supongo que es una ventana porque admite un Window parent en el constructor. De todas formas, ayudaría si completaras el extends y dijeras de quién hereda.
Supongo que hay que llamar al initizliace(), puesto que en el constructor que has puesto no se le llama.
Lo de setVisible(true) es correcto si la clase es realmente una ventana, si no no valdría.

Se bueno.
__________________
Apuntes Java
Wiki de Programación
  #3 (permalink)  
Antiguo 30/04/2006, 10:12
 
Fecha de Ingreso: diciembre-2004
Mensajes: 59
Antigüedad: 19 años, 4 meses
Puntos: 0
gracias, la clase es asi:

public class s extends LazyPanel implements ActionListener, FileSystemEventListener, PropertyChangeListener

cuando segui el consejo, salen los siguentes errores:

s.java:225: non-static method setVisible(boolean) cannot be referenced from a static context
s.setVisible(true);

no pongo el codigo completo porque es enorme y ademas necesita de como 8 archivos para compilarlo, reconstruirlo fue una tarea titanica.

gracias
  #4 (permalink)  
Antiguo 30/04/2006, 13:57
Avatar de chuidiang
Colaborador
 
Fecha de Ingreso: octubre-2004
Mensajes: 3.774
Antigüedad: 19 años, 7 meses
Puntos: 454
Hola:
Fallo mio, el código es así

s ventana = new s(null);
ventana.initialize();
ventana.setVisible(true);

De todas formas, es buena cosa seguir un criterio que hay más o menos standard para nombres de clases y variables.

Las clases deberían tener nombres un poco más largos (no sólo s) y las clases suelen empezar con la primera letra mayúscula. Por eso en parte mi fallo, s parece según esta convención más el nombre de una variable que de una clase.

Se bueno.
__________________
Apuntes Java
Wiki de Programación
  #5 (permalink)  
Antiguo 30/04/2006, 14:14
 
Fecha de Ingreso: diciembre-2004
Mensajes: 59
Antigüedad: 19 años, 4 meses
Puntos: 0
gracias, veo que es mas complejo de lo previsto, asi que pondre el codigo completo, aunque no se puede compilar ya que usa como 10 .class externos, que me costo un mundo conseguirlos. ademas destaco en negritas lo que creo que es mas importante para hallar el problema.

Cita:

import com.jniwrapper.win32.io.FileSystemEvent;
import com.jniwrapper.win32.io.FileSystemEventListener;
.....

import javax.swing.*;
import java.awt.*;
....

public class FileSystemWatcherSample extends LazyPanel implements ActionListener, FileSystemEventListener, PropertyChangeListener
{
private static FileSystemWatcherSample fileSystemWatcherSample = null;
private static final Logger LOG = Logger.getInstance(FileSystemWatcherSample.class);

static final String[] ACTION_NAMES = new String[]{"added", "removed", "modified", "renamed"};
static final String MESSAGE_TEMPLATE = "File ''{0}'' was {1}";

static final String SHORT_DATE_FORMAT = "HH:mm:ss";
static final String LONG_DATE_FORMAT = "dd/MM/yyyy HH:mm:ss";

private JLabel lblAdvisoryText;
private JLabel lblSelectedFolderCaption;
private SelectFolderField _selectFolderField;
private JCheckBox chkWatchSubtree;
private JCheckBox chkChangeFileName;
private JCheckBox chkChangeDirName;
private JCheckBox chkChangeAttributes;
private JCheckBox chkChangeSize;
private JCheckBox chkChangeLastWrite;
private JList lstEvents;
private DefaultListModel _listModel;
private JLabel lblEvents;
private FileSystemWatcher _fileSystemWatcher;
private JButton btnStart;
private JButton btnStop;

public FileSystemWatcherSample(Window parent)
{
super(parent);
}

public void initialize() throws Exception
{
lblAdvisoryText = new HTMLText("This sample demonstrates FileSystemWatcher class features.");
lblSelectedFolderCaption = new JLabel("Watching Folder:");
chkWatchSubtree = new JCheckBox("Watch Subtree", true);
chkChangeFileName = new JCheckBox("Watch File Name Change", true);
chkChangeDirName = new JCheckBox("Watch Dir Name Change", true);
chkChangeAttributes = new JCheckBox("Watch Attributes Change", true);
chkChangeSize = new JCheckBox("Watch Size Change", true);
chkChangeLastWrite = new JCheckBox("Watch Last Write Change", true);
_selectFolderField = new SelectFolderField();
_selectFolderField.addPropertyChangeListener(Selec tFolderField.PROPERTY_FOLDER, this);

lblEvents = new JLabel("File System Events:");
_listModel = new DefaultListModel();
lstEvents = new JList(_listModel);
btnStart = new JButton("Start");
btnStart.setEnabled(false);
btnStart.addActionListener(this);
btnStop = new JButton("Stop");
btnStop.setEnabled(false);
btnStop.addActionListener(this);

setLayout(new GridBagLayout());

add(lblAdvisoryText, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0));

add(lblSelectedFolderCaption, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0));

add(_selectFolderField, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0));

add(chkWatchSubtree, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 10, 0, 0), 0, 0));

add(chkChangeFileName, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 5, 0, 10), 0, 0));

add(chkChangeDirName, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 10, 0, 0), 0, 0));

add(chkChangeAttributes, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 5, 0, 10), 0, 0));

add(chkChangeSize, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 10, 0, 0), 0, 0));

add(chkChangeLastWrite, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 5, 0, 10), 0, 0));

add(lblEvents, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0
, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 0, 10), 0, 0));

JScrollPane eventPane = new JScrollPane(lstEvents);
Dimension preferredSize = new Dimension(200, 100);
eventPane.setPreferredSize(preferredSize);
eventPane.setMinimumSize(preferredSize);

add(eventPane, new GridBagConstraints(0, 6, 2, 1, 1.0, 1.0
, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 10, 10, 10), 0, 0));

JPanel buttonsPanel = new JPanel();

buttonsPanel.add(btnStart);
buttonsPanel.add(btnStop);

add(buttonsPanel, new GridBagConstraints(1, 7, 1, 1, 0.0, 0.0
, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 10, 0, 10), 0, 0));

add(new JPanel(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0
, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
super.initialize();
}

public void actionPerformed(ActionEvent e)
{
if (e.getSource().equals(btnStart))
{
startWatching();
}
else if (e.getSource().equals(btnStop))
{
stopWatching();
}
}

private void startWatching()
{
_listModel.clear();
_fileSystemWatcher = new FileSystemWatcher(_selectFolderField.getFolder(), chkWatchSubtree.isSelected());
_fileSystemWatcher.addFileSystemListener(this);
FileSystemWatcher.WatcherOptions options = _fileSystemWatcher.getOptions();
options.setNotifyChangeAttributes(chkChangeAttribu tes.isSelected());
options.setNotifyChangeDirName(chkChangeDirName.is Selected());
options.setNotifyChangeFileName(chkChangeFileName. isSelected());
options.setNotifyChangeSize(chkChangeSize.isSelect ed());
options.setNotifyLastModified(chkChangeLastWrite.i sSelected());
btnStart.setEnabled(false);
btnStop.setEnabled(true);
try
{
_fileSystemWatcher.start();
_listModel.addElement("Started at " + getDateTime(true));
lstEvents.setSelectedIndex(0);
}
catch (FileSystemException e1)
{
LOG.error("", e1);
JOptionPane.showMessageDialog(this, "Unable to start watcher.\n" + e1, "File System Watcher", JOptionPane.WARNING_MESSAGE);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
}
}

private void stopWatching()
{
_listModel.addElement("Stopped at " + getDateTime(true));
final int size = _listModel.getSize() - 1;
lstEvents.setSelectedIndex(size);
lstEvents.ensureIndexIsVisible(size);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
try
{
_fileSystemWatcher.stop();
}
catch (FileSystemException e1)
{
LOG.error("", e1);
}
}

public void deactivate()
{
if (_fileSystemWatcher != null && _fileSystemWatcher.isWatching())
{
stopWatching();
}
}

public void handle(FileSystemEvent event)
{
String actionName = ACTION_NAMES[event.getAction() - 1];
String message = MessageFormat.format(MESSAGE_TEMPLATE, new Object[]{event.getFileInfo(), actionName});
if (event.getAction() == FileSystemEvent.FILE_RENAMED)
message += " from '" + event.getOldFileInfo() + "'";
message += " at " + getDateTime(false);

_listModel.addElement(message);
final int size = _listModel.getSize() - 1;
lstEvents.setSelectedIndex(size);
lstEvents.ensureIndexIsVisible(size);
}

String getDateTime(boolean longFormat)
{
SimpleDateFormat dateFormat = new SimpleDateFormat(longFormat ? LONG_DATE_FORMAT : SHORT_DATE_FORMAT);
return dateFormat.format(new Date());
}

public void propertyChange(PropertyChangeEvent evt)
{
btnStart.setEnabled(true);
}


public static void main(String[] args)
{
FileSystemWatcherSample ventana = new FileSystemWatcherSample(null);
ventana.initialize();
ventana.setVisible(true);

}
}
el error final es:

C:\java>javac FileSystemWatcherSample.java
FileSystemWatcherSample.java:224: unreported exception java.lang.Exception; must
be caught or declared to be thrown
ventana.initialize();


gracias.
  #6 (permalink)  
Antiguo 30/04/2006, 21:10
Avatar de TolaWare
Colaborador
 
Fecha de Ingreso: julio-2005
Mensajes: 4.352
Antigüedad: 18 años, 10 meses
Puntos: 24
Tienes que interceptar la Excepcion que puede llegar a largar la ejecución del codigo:
Código:
ventana.initialize();
Esto lo puedes hacer de 2 maneras:
a) Agregar al public static void main(String[] args) lo siguiente: throws Exception

b) encerrar la linea ventana.initialize(); en un bloque try-catch de la siguiente manera:

try {
ventana.initialize();
}
catch(Exception e) {//codigo de manejo de la excepción}


Saludos
__________________
http://blog.tolaware.com.ar -> Blog de Java, Ruby y Linux
  #7 (permalink)  
Antiguo 30/04/2006, 21:31
 
Fecha de Ingreso: diciembre-2004
Mensajes: 59
Antigüedad: 19 años, 4 meses
Puntos: 0
tengo esto

FileSystemWatcherSample ventana = new FileSystemWatcherSample(null);
try {
ventana.initialize();
}
catch(Exception e) {}
ventana.setVisible(true);



compila bien, pero cuando voy a ejecutar sale esto


Exception in thread "main" java.lang.NoClassDefFoundError: com/jniwrapper/util/a at FileSystemWatcherSample.<clinit>(FileSystemWatcher Sample.java:24)
  #8 (permalink)  
Antiguo 30/04/2006, 22:51
Avatar de chuidiang
Colaborador
 
Fecha de Ingreso: octubre-2004
Mensajes: 3.774
Antigüedad: 19 años, 7 meses
Puntos: 454
Hola:

Aparentemente al compilar te falta añadir algun jar. Echa un ojo en el siguiente enlace http://www.chuidiang.com/java/classpath/classpath.html

Se bueno.
__________________
Apuntes Java
Wiki de Programación
  #9 (permalink)  
Antiguo 30/04/2006, 23:26
 
Fecha de Ingreso: diciembre-2004
Mensajes: 59
Antigüedad: 19 años, 4 meses
Puntos: 0
gracias. halle el error, pero creo que jodi. ahora cargo el programa, se queda unos 3 segundos la consola como ejecutando y sale

creo que el initialize esta creando la grafica en el aire, como esto lo saque de una aplicacion, alli seguro que estaba construido el "formulario" por decirlo de alguna forma
  #10 (permalink)  
Antiguo 01/05/2006, 03:08
Avatar de chuidiang
Colaborador
 
Fecha de Ingreso: octubre-2004
Mensajes: 3.774
Antigüedad: 19 años, 7 meses
Puntos: 454
Hola:

Comprueba la jerarquía de herencia de s a ver si hereda de JDialog o JFrame. Si no es así, construye la ventana de esta forma, en el main (las líneas con puntos suspensivos son las que ya tienes).

JFrame v = new JFrame();
s ventana = new s (...);
v.getContentPane().add (ventana);
try ... s.initialize(); ... catch ...
v.setVisible(true);


y quita el setVisible de ventana.

Se bueno.
__________________
Apuntes Java
Wiki de Programación
  #11 (permalink)  
Antiguo 01/05/2006, 11:04
 
Fecha de Ingreso: diciembre-2004
Mensajes: 59
Antigüedad: 19 años, 4 meses
Puntos: 0
MIL GRACIAS ¡¡¡¡

lo logre, agregando lo que me recomendaste. al ppio. no funciono, pero se me ocurrio ponerle v.show() y ahi salio una ventana muy pequeña, luego le setee el tamaño y listo :D:D:D

gracias otra vez

Última edición por Klaudioz; 01/05/2006 a las 11:17
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:30.