SWT inside of Swing?

Simply put, can I use an SWT component inside of a JDialog, JFrame, or JInternalFrame?
I've been searching for this answer all over and while apparently I can use a Swing component in SWT I cant find any example of using SWT inside of Swing.

SWT only provides a way to embed swing and not the other way around (as far as I know of) so you might have a problem.
If you want to embed a native browser look at the JDIC project which has this ability.
https://jdic.dev.java.net/
1 small warning though, I have played around with this and when switching between visible and non visible panels (some contain this brower) I saw some native code errors and the entire app crashed so just be carefull how you use it.

Similar Messages

  • I want to find if the user is inactive inside my swing application

    i want to find if the user is inactive inside my swing application i.e he has not used the keyboard or mouse over a period of time

    Hai,
    This is code to notify you when the keyboard is left inactive for 10 seconds it will throw a message then the sytem will get exit.
    For mouse event i don't how to do the same process.
    import java.awt.KeyEventDispatcher;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.KeyEvent;
    import javax.swing.JOptionPane;
    * InactiveTest.java
    * Created on October 9, 2006, 12:33 PM
    public class InactiveTest extends javax.swing.JFrame {
        int timeCnt = 0;
        Thread th;
        /** Creates new form InactiveTest */
        public InactiveTest() {
            initComponents();
            th = new Thread() {
                public void run() {
                    while(true) {
                        try {
                            th.sleep(1000);
                            timeCnt++;
                            System.out.println("Time Cnt"+timeCnt);
                            if(timeCnt == 10) {
                                JOptionPane.showMessageDialog(objInactiveTest,"Inactive for 10 seconds");
                                System.exit(0);
                                th.stop();                           
                                break;
                        }catch(Exception e){}
            th.start();
            KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
                public boolean dispatchKeyEvent(KeyEvent event) {
                    timeCnt=0;
                    //th.stop();
                    //th.start();
                    return false;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jPanel1.setLayout(new java.awt.GridLayout());
            jLabel1.setText("Enter the Name  :");
            jPanel1.add(jLabel1);
            jPanel1.add(jTextField1);
            getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
            pack();
        // </editor-fold>
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    objInactiveTest = new InactiveTest();
                    objInactiveTest.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
        private static InactiveTest objInactiveTest;
    }rgds,
    rdRose

  • PDF Display INSIDE a SWING app.

    Is there a way to display PDF inside a JPanel (or whatever ;-) ? I know Adobe made a Bean but no support was added since two years (if i am right). PDFGo could be a solution but it seems slow and not really nice...
    Other solutions ?
    Anyone has already done such thing ?
    Thanks.
    Phil

    Hi,
    we are using the bean in an 1.3.1 environment and it works pretty well...
    you can see how we implemented it by looking into the code a bit...Don't worry about the maintainer class..its just part of our gui framework.
    Regards.,
    rookie_no2
    package de.fiscus.sfs.akte;
    import com.adobe.acrobat.*;
    import com.adobe.acrobat.gui.*;
    import de.fiscus.sfs.akte.internal.AkteHelpset;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.FocusEvent;
    import java.awt.*;
    import java.io.StringWriter;
    import java.io.PrintWriter;
    import java.util.*;
    import javax.swing.*;
    import de.fiscus.mw.bnof.*;
    import de.fiscus.mw.transfer.*;
    import de.fiscus.sfs.druck.druckauftrag.TODruckAuftrag;
    * Diese Form realisiert die Anzeige eines einzelnen Aktenelementes in einer Nur-Lese-Ansicht.
    * Dazu zeigt die Form die PDF-Viewer-Bean, deren Inhalt durch ein an den Viewer �bergebenes
    * Byte-Array bestimmt wird, an.
    * <p>
    * @version %version: 7 %
    * @see BNOForm
    public class AkteneintragPDFForm extends AkteneintragBNOForm implements ViewerCommand{
      Viewer ivViewer = null;
      // Komponenten, die vom JBuilder erzeugt wurden
      BorderLayout borderLayout1 = new BorderLayout();
      BorderLayout borderLayout2 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      JPanel jPanelButtonBar = new JPanel();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      GridLayout gridLayout1 = new GridLayout();
      /** Konstruktor. Initialisiert die Form. Es wird lediglich die Methode
       *  <code>jbInit</code> gerufen, um die grafische Repr�sentation der Form zu
       *  erzeugen.
       *  @see jbInit
      public AkteneintragPDFForm() {
        try  {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      /** Definiert die grafische Repr�sentation der Form.
       *  @return void
       *  @exception Exception : technischer Fehler aufgetreten
      private void jbInit() throws Exception {
        this.setComponentName("Druckvorschau"+AkteHelpset.cvARBEITS_BESTANDSANZEIGE);
        //Funktionalit�t der pdf-Bean
        try{
          ivViewer = new Viewer();
          //Setzen der Skalierung auf die Breite des Frames
          ivViewer.setProperty("Default_Zoom_Type","FitWidth");
          //Abschalten der gesamten Shortcut-Funktionalit�t
          Properties prop = CommandRegistry.getKeymaps();
          prop.clear();
          //Einschalten bestimmter Shortcut-Funkionalit�ten
          prop.putAll(getAllowedShortcuts());
          //Nicht ben�tigte Commands abschalten
          CommandRegistry.setDisallowedCommands(getDisallowedCommands());
        catch (Exception e) {
          e.printStackTrace();
        this.setMaintainer(new AkteneintragPDFForm.FormMaintainer(ivViewer));
        this.setPreferredSize(new Dimension(700, 600));
        this.setLayout(borderLayout1);
        this.add(ivViewer, borderLayout1.CENTER);
        jPanelButtonBar.setLayout(borderLayout2);
        jPanelButtonBar.add(getButtonBar(), borderLayout2.EAST);
        //this.add(this.getButtonBar(), borderLayout1.SOUTH);
        this.add(jPanelButtonBar, borderLayout1.SOUTH);
        Die nicht ben�tigten Commands (ViewerCommand) werden hier in einem String-Array zusammengefa�t und zur�ckgegeben
        @return String [] gesammelte Commands
      private String [] getDisallowedCommands () {
        return new String [] {PageOnly_K, Thumbnails_K, ShowBookmarks_K, HideBookmarks_K, ToggleBookmarks_K,
                              Window_K, Open_K, OpenURL_K, Close_K, GeneralPrefs_K, About_K, Reload_K, Find_K,
                              FindAgain_K, DocInfo_K, ListBindings_K, PrintSetup_K, FirstPage_K,
                              PrevPage_K, NextPage_K, LastPage_K, PageUp_K, PageDown_K, LineUp_K, LineDown_K,
                              SinglePage_K, OneColumn_K, TwoColumn_K, TwoColumnLeft_K, TwoColumnRight_K,
                              ActualSize_K, FitPage_K, FitVisible_K, FitWidth_K, FitVisibleWidth_K, FitHeight_K,
                              FitVisibleHeight_K, FitVisibleHeight_K, FullScreen_K, ToFullScreen_K, FromFullScreen_K,
                              ToggleFullScreen_K, OpenHelpFile_K, OpenLicenseFile_K, EditUndo_K, EditDelete_K,
                              EditCopy_K, EditCut_K, EditPaste_K, EditSelectAll_K, Print_K};
        Erlaubte Shortcuts werden hier in einer Properties zur�ckgegeben. Die existierenden Commands sind
        durch den Aufruf CommandRegistry.getKeymaps() ersichtlich.
        @return Properties gesammelte Shortcuts
      private Properties getAllowedShortcuts () {
        Properties prop = new Properties();
        prop.put("Page_Down", "PageDown");
        prop.put("Page_Up", "PageUp");
        return prop;
      public Viewer getPDFViewer () {
        return ivViewer;
      * INNER CLASS - FormMaintainer --- Beginn                                   *
      public class FormMaintainer extends AkteneintragBNOFormMaintainer {
        private Viewer ivViewer = null;
        public FormMaintainer (Viewer ivViewer) {
          this.ivViewer = ivViewer;
         * F�gt den Inhalt des �bergebenen Byte-Arrays in den Viewer ein.
         * @param byte [] Byte-Array mit dem Inhalt des darzustellenden pdf-Files
        public void setPdfContent (byte [] bArray) {
          try{
            ivViewer.setDocumentByteArray(bArray);
          catch (Exception e) {
            e.printStackTrace();
         * CALLBACK: Diese Methode wird vom BNOFramework nach der Initialisierung
         * der Form gerufen. Diese Implementierung initialisiert die Toolbar der
         * Form. Anschlie�end wird die Methode <code>refresh</code> gerufen, um
         * die Form neu darzustellen.
         * @return void
         *  @see refresh
        protected void handleSetup() {
          super.handleSetup();
          refresh();
         * �berschreibt die Methode der Superklasse. Sorgt daf�r, da� bei einem Klick auf den
         * Schlie�en-Button die pdf-Bean ordnungsgem�� beendet wird.
         * @param ActionEvent e
        protected void handleCancel (ActionEvent e){
          ivViewer.deactivate();
          super.handleCancel(e);
         * �berschreibt die Methode in der Superklasse. Dient dazu, den Event f�r einen vorhandenen
         * Drucken-Button in der AkteneintragPDFForm entsprechend zu behandeln
         * @param e ActionEvent, das das ausgel�ste Ereignis enth�lt
         * @exception Exception
        protected void handleActionPerformed (ActionEvent e) throws java.lang.Exception {
          if (e.getActionCommand().equals(BNOActionEvent.cvPRINT)){
            //ALT:
            //ivViewer.execMenuItem(ViewerCommand.Print_K);
            BNOFormMaintainer bnoFM = this.getParentMaintainer();
            final AkteneintragBearbeiten ab = (AkteneintragBearbeiten)this.getDataSource();
            final TODokumentDruckInfo toDruckInfo = ab.getDruckInformation();
            TOAkteneintrag toAE = null;
            //Abfangen der Exception notwendig. Tritt auf, wenn eine Druckvorschau vorhanden ist,
            //der Akteneintrag gel�scht wird und versucht wird, auf der ge�ffnetten Druckvorschau
            //diesen gel�schten Akteneintrag zu drucken
            try{
              toAE = ab.getAkteneintrag();
            catch (AkteException ae){
              throw new AkteException (true, "AkteneintragNotFoundException", new Object [] {"M�glicherweise wurde der Akteneintrag gel�scht"});
            final TOAkteneintrag selectedTO = toAE;
            AkteneintragDruckDialogForm form = new AkteneintragDruckDialogForm(ab.provideDienstpostenBefragen());
            BNODataAccessor data = new BNODataAccessor("", "") {
              public Object handleGetData () throws de.fiscus.mw.util.FiscusException, java.rmi.RemoteException {
                return toDruckInfo;
              public void handleSetData (Object o) throws de.fiscus.mw.util.FiscusException, java.rmi.RemoteException {
                TODokumentDruckInfo toDruckInfo = (TODokumentDruckInfo)o;
                ab.printDokument(toDruckInfo);
                if (selectedTO.getStatus()==(AkteneintragStatus.IM_BESTAND.getValue())){
                  ab.printDokumentImBestand(toDruckInfo);
                else {
                  ab.printDokumentPreview(toDruckInfo);
            //form.setButtonBar(AkteneintragBNOForm.cvDRUCKVORSCHAU_OK_ABBRECHEN);
            form.setButtonBar(AkteneintragBNOForm.cvOK_ABBRECHEN);
            BNOOpenWindowParameters owp = BNOOpenWindowParameters.createForSecondaryWindow(form, data, this, null, true);
            BNOWindow w = BNOFactory.createWindow(owp);
          else super.handleActionPerformed(e);
        * Initialisiert die Maintainerhierarchie richtungsm��ig von den
        * �bergeordneten Maintainern zu den untergeordneten Maintainern.
        public void reInitialize() {
          super.reInitialize();
          refresh();
        /** Diese Methode wird verwendet, um die Form neu darzustellen. Dazu wird die
         *  zuvor erzeugte Viewer-Bean aktiviert, soda� sie dargestellt werden kann.
         *  @return void
        public void refresh() {
          try{
            ivViewer.activate();
          catch (Exception e) {
            e.printStackTrace();
      * INNER CLASS - FormMaintainer --- Ende                                     *
    }

  • Want to draw some rectangles inside a swing panel object

    HI,
    I want to draw some rectangles inside one JPanel object in swing. The JPanel object should also hold some buttons, labels, etc.. I can add simple buttons, label etc. easily to the panel object but how do I add graphics (like lines, rectangles) to it ??
    an immediate response would be highly appreciated!!

    I am not sure why you are talking about the rectangle.
    To repeat I fill in a bit of code (subject to compiler errors since I Do not have a machine where I can compile or test on at the moment):
      private class ColourCube extends JPanel 
         // The size of each rectangle with colour
         private static final int ROWS = 10;
         private static final int COLS = 10;
         // To store current selection
         private int selectedIndex[] = null;
         public ColourCube()
             addMouseListener( new MouseAdapter() {
                public void mouseReleased(MouseEvent me)
                   // Find the rectangle index by dividing
                   // x and y positions then set selectedIndex
                   // unless it is the same positions as previous
                   // then set it to be null
                   fireActionEvent();
         // needed listener methods for firing events
         public void addActionListener( ActionListener al)
            // add to list
         // remove etc....
         protected void fireActionEvent()
            // Construct action event
            // call actionPerformed( ae ) on all listeners
         public void paintComponent(Graphics g)
             // Depending on size and height of this component
             // calculate out colWidth and rowHeight
             // Loop and paint the rectangles in their different colours
             for(int i = 0; i < ROWS; i++)
                for(int j = 0; j < COLS; j++)
                   // set the colour to the graphics object here from the list of colours available
                   g.setColor( ... );
                   // Added a little bit extra to have some space between
                   // each rectangle
                   g.fillRect( i * rowHeight + 1, j * colWidth + 1, colWidth - 2, rowHeight - 2 );
             if( selectedIndex != null )
                // We have a selection, lets paint the selection
                g.setColor( Color.white ); // Selection colour
                // The index contains the row in index 0 and the col in index 1
                g.drawRect( selectedIndex[0] * rowHeight, selectedIndex[1] * colWidth, colWidth, rowHeight );
      }Lacking from the above component is lacking stuff like preferedSize.
    Now, all you do is instantiate the ColourChooser, add it to your applet iether by drag and drop if you have an WYSIWYG editor, or by hand if you are so inclined.
    Voila! A composite component appears, doing the stuff it needs to be doing.
    Regards,
    Peter Norell

  • How to Converting SWT application  to Swing jdialog?

    How hard is to convert an exising dialog writen in Eclipse SWT to Swing
    import java.io.*;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import javax.swing.*;
    import java.awt.*;
    import my.base.Action;
    import my.base.ActionQueue;
    import my.base.Location;
    import my.base.Task;
    import my.base.TaskTree;
    import my.buffer.BlockBuffer;
    import my.fs.File;
    import my.impl.FillBufferActionQueue;
    //import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.MouseAdapter;
    import org.eclipse.swt.events.MouseEvent;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.events.SelectionListener;
    import org.eclipse.swt.graphics.GC;
    import org.eclipse.swt.graphics.Image;
    import org.eclipse.swt.graphics.ImageData;
    import org.eclipse.swt.graphics.PaletteData;
    import org.eclipse.swt.graphics.RGB;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Button;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Menu;
    import org.eclipse.swt.widgets.MenuItem;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Table;
    import org.eclipse.swt.widgets.TableColumn;
    import org.eclipse.swt.widgets.TableItem;
    public class SynchLogWindow extends org.eclipse.swt.widgets.Composite {
    private Button buttonGo;
    private TableColumn tableColumn1;
    private TableColumn tableColumnDestination;
    private TableColumn tableColumnAction;
    private TableColumn tableColumnSource;
    private TableColumn tableColumnExplanation;
    private Table tableLogLines;
    private Hashtable actionImages;
    private Image locationSource;
    private Image locationDestination;
    private Image locationBoth;
    private Image nodeFile;
    private Image nodeDirectory;
    private TaskTree taskTree;
    public SynchLogWindow(Composite parent, int style)
    super(parent, style);
    initGUI();
    initializeImages();
    * Initializes the GUI.
    * Auto-generated code - any changes you make will disappear.
    public void initGUI(){
    try {
    preInitGUI();
    tableLogLines = new Table(this,SWT.FULL_SELECTION);
    tableColumn1 = new TableColumn(tableLogLines,SWT.NULL);
    tableColumnExplanation = new TableColumn(tableLogLines,SWT.NULL);
    tableColumnSource = new TableColumn(tableLogLines,SWT.NULL);
    tableColumnAction = new TableColumn(tableLogLines,SWT.NULL);
    tableColumnDestination = new TableColumn(tableLogLines,SWT.NULL);
    buttonGo = new Button(this,SWT.PUSH| SWT.CENTER);
    this.setSize(new org.eclipse.swt.graphics.Point(711,225));
    GridData tableLogLinesLData = new GridData();
    tableLogLinesLData.verticalAlignment = GridData.FILL;
    tableLogLinesLData.horizontalAlignment = GridData.FILL;
    tableLogLinesLData.widthHint = -1;
    tableLogLinesLData.heightHint = -1;
    tableLogLinesLData.horizontalIndent = 0;
    tableLogLinesLData.horizontalSpan = 1;
    tableLogLinesLData.verticalSpan = 1;
    tableLogLinesLData.grabExcessHorizontalSpace = true;
    tableLogLinesLData.grabExcessVerticalSpace = true;
    tableLogLines.setLayoutData(tableLogLinesLData);
    tableLogLines.setHeaderVisible(true);
    tableLogLines.setLinesVisible(true);
    tableLogLines.setSize(new org.eclipse.swt.graphics.Point(690,179));
    tableLogLines.addMouseListener( new MouseAdapter() {
    public void mouseUp(MouseEvent evt) {
    tableLogLinesMouseUp(evt);
    tableColumn1.setResizable(false);
    tableColumn1.setText("tableColumn1");
    tableColumnExplanation.setText("Explanation");
    tableColumnExplanation.setWidth(150);
    tableColumnSource.setText("Source");
    tableColumnSource.setWidth(220);
    tableColumnAction.setResizable(false);
    tableColumnAction.setText("Action");
    tableColumnAction.setWidth(50);
    tableColumnDestination.setText("Destination");
    tableColumnDestination.setWidth(220);
    GridData buttonGoLData = new GridData();
    buttonGoLData.verticalAlignment = GridData.CENTER;
    buttonGoLData.horizontalAlignment = GridData.END;
    buttonGoLData.widthHint = -1;
    buttonGoLData.heightHint = -1;
    buttonGoLData.horizontalIndent = 0;
    buttonGoLData.horizontalSpan = 1;
    buttonGoLData.verticalSpan = 1;
    buttonGoLData.grabExcessHorizontalSpace = false;
    buttonGoLData.grabExcessVerticalSpace = false;
    buttonGo.setLayoutData(buttonGoLData);
    buttonGo.setText("Go");
    buttonGo.addSelectionListener( new SelectionAdapter() {
    public void widgetSelected(SelectionEvent evt) {
    buttonGoWidgetSelected(evt);
    GridLayout thisLayout = new GridLayout(1, true);
    this.setLayout(thisLayout);
    thisLayout.marginWidth = 2;
    thisLayout.marginHeight = 2;
    thisLayout.numColumns = 1;
    thisLayout.makeColumnsEqualWidth = false;
    thisLayout.horizontalSpacing = 2;
    thisLayout.verticalSpacing = 2;
    this.layout();
    postInitGUI();
    } catch (Exception e) {
    e.printStackTrace();
    /** Add your pre-init code in here      */
    public void preInitGUI(){
    /** Add your post-init code in here      */
    public void postInitGUI(){
    public static void show( final TaskTree task )
    final Display display = Display.getDefault();
    display.syncExec( new Runnable() {
    public void run()
    try {
    Shell shell = new Shell(display);
    SynchLogWindow inst = new SynchLogWindow(shell, SWT.NULL);
    inst.setTaskTree( task );
    inst.rebuildActionList();
    shell.setLayout(new org.eclipse.swt.layout.FillLayout());
    Rectangle shellBounds = shell.computeTrim(0,0,663,225);
    shell.setSize(shellBounds.width, shellBounds.height);
    shell.setText( "Synchronization Actions" );
    shell.setImage( new Image( null, "images/Location_Both.gif" ) );
    shell.open();
    } catch( Exception ex ) {
    ex.printStackTrace();
    public void setTaskTree( TaskTree task )
    this.taskTree = task;
    public static Image loadImage( String filename )
    try {
    //System.out.println("crrent path:"+System.getProperty("user.dir"));
    return new Image( null, new FileInputStream( "images/"+filename) );
    } catch( FileNotFoundException e ) {
    e.printStackTrace();
    return null;
    public void initializeImages()
    nodeFile = loadImage( "Node_File.gif" );
    nodeDirectory = loadImage( "Node_Directory.gif" );
    locationSource = loadImage( "Location_Source.gif" );
    locationDestination = loadImage( "Location_Destination.gif" );
    locationBoth = loadImage( "Location_Both.gif" );
    actionImages = new Hashtable();
    for( int i = 0; i < Action.names.length; i++ )
    actionImages.put( new Integer( i ), loadImage( "Action_"+Action.names[i]+".gif" ) );
    for( int i = 0; i < Action.errorNames.length; i++ )
    actionImages.put( new Integer( i+10 ), loadImage( "Action_"+Action.errorNames[i]+".gif" ) );
    protected void drawSide( GC g, Task t, Action a, int location )
    File n = location==Location.Source?t.getSource():t.getDestination();
    int x = location==Location.Source?2:2*16+2;
    if( n.exists() )
    if( n.isDirectory() )
    g.drawImage( nodeDirectory, x, 0 );
    else g.drawImage( nodeFile, x, 0 );
    // TODO draw some not-existing image ?
    if( (a.getLocation() & location) > 0 )
    Image actionImage = (Image)actionImages.get( new Integer( a.getType() ) );
    if( actionImage != null )
    g.drawImage( actionImage, x, 0 );
    if( location == Location.Source )
    g.drawImage( locationSource, x+16, 0 );
    else g.drawImage( locationDestination, x-16, 0 );
    protected void drawLocation( GC g, Action a )
    switch( a.getLocation() )
    case Location.Source:
    g.drawImage( locationSource, 16+2, 0 );
    break;
    case Location.Destination:
    g.drawImage( locationDestination, 16+2, 0 );
    break;
    case Location.Both:
    g.drawImage( locationBoth, 16+2, 0 );
    break;
    protected Image buildTaskImage( Task t, Action a )
    ImageData data = new ImageData( 16*3+2, 16, 8, new PaletteData( 0, 0, 0 ) );
    data.transparentPixel = data.palette.getPixel( new RGB( 0, 0, 0 ) );
    Image image = new Image( null, data );
    GC g = new GC(image);
    drawSide( g, t, a, Location.Source );
    drawSide( g, t, a, Location.Destination );
    drawLocation( g, a );
    g.dispose();
    return image;
    protected Image buildTaskImage( Task t )
    return buildTaskImage( t, t.getCurrentAction() );
    protected void addTaskChildren( Task t )
    for( Enumeration e = t.getChildren(); e.hasMoreElements(); )
    addTask( (Task)e.nextElement() );
    protected void addTask( Task t )
    if( !t.getCurrentAction().isBeforeRecursion() )
    addTaskChildren( t );
    Image image = buildTaskImage( t );
    TableItem item = new TableItem( tableLogLines, SWT.NULL );
    item.setImage( 3, image );
    item.setText( new String[] {
    t.getCurrentAction().getExplanation(),
    t.getSource().getPath(),
    t.getDestination().getPath()
    item.setData( t );
    if( t.getCurrentAction().isBeforeRecursion() )
    addTaskChildren( t );
    public void rebuildActionList()
    tableLogLines.clearAll();
    tableLogLines.setItemCount(0);
    addTaskChildren( taskTree.getRoot() );
    //tableLogLines.redraw();
    protected void showPopup( int x, int y )
    System.out.println( "Contextmenu at: "+x+", "+y );
    SelectionListener selListener = new SelectionAdapter() {
    public void widgetSelected( SelectionEvent e )
    Integer i = (Integer)e.widget.getData();
    TableItem item = tableLogLines.getSelection()[0];
    ((Task)item.getData()).setCurrentAction( i.intValue() );
    item.setImage( 3, image );
    item.setText( 1, action.getExplanation() );
    item.setData( action );
    tableLogLines.redraw();
    int top = tableLogLines.getTopIndex();
    rebuildActionList();
    tableLogLines.setTopIndex( top );
    TableItem[] items = tableLogLines.getSelection();
    if( items.length == 0 )
    return;
    Task t = (Task)items[0].getData();
    Menu m = new Menu( this );
    MenuItem mi;
    int curr = t.getCurrentActionIndex();
    Action[] actions = t.getActions();
    for( int i = 0; i < actions.length; i++ )
    if( i == curr )
    continue;
    Action al = actions;
    Image image = buildTaskImage( t, al );
    mi = new MenuItem( m, SWT.NULL );
    mi.setImage( image );
    mi.setText( Action.toString( al.getType() )+" - "+al.getExplanation() );
    mi.setData( new Integer( i ) );
    mi.addSelectionListener( selListener );
    Action al = new Action( Action.Nothing, Location.None, "Ignore" );
    Image image = buildTaskImage( t, al );
    mi = new MenuItem( m, SWT.NULL );
    mi.setImage( image );
    mi.setText( "Ignore" );
    mi.setData( al );
    mi.addSelectionListener( selListener );
    m.setLocation( toDisplay( x, y ) );
    m.setVisible( true );
    protected void performActions()
    try {
    //Logger logger = Logger.getRootLogger();
    //logger.addAppender( new FileAppender( new PatternLayout( "%d{ISO8601} [%p] %c %x - %m%n" ), "log/log.txt" ) );
    // Logger logger = Logger.getLogger( "FullSync" );
    // logger.info( "Synchronizing "+taskTree.getSource().getUri().toString()+" and "+taskTree.getDestination().getUri().toString() );
    // BlockBuffer buffer = new BlockBuffer( logger );
    // buffer.load();
    // ActionQueue queue = new FillBufferActionQueue(buffer);
    TableItem[] items = tableLogLines.getItems();
    for( int i = 0; i < items.length; i++ )
    Task t = (Task)items[i].getData();
    // queue.enqueue( t.getCurrentAction(), t.getSource(), t.getDestination() );
    // queue.flush();
    // buffer.unload();
    taskTree.getSource().flush();
    taskTree.getDestination().flush();
    taskTree.getSource().close();
    taskTree.getDestination().close();
    // logger.info( "finished synchronization" );
    } catch( IOException e ) {
    e.printStackTrace();
    /** Auto-generated event handler method */
    protected void tableLogLinesMouseUp(MouseEvent evt)
    if( evt.button == 3 )
    showPopup( evt.x, evt.y );
    /** Auto-generated event handler method */
    protected void buttonGoWidgetSelected(SelectionEvent evt)
    performActions();
    getShell().dispose();

    Give it a try and let us know.

  • Working with objects \ beans inside a Swing.JTextPane

    javax.swing.text.html
    specifically
    javax.swing.text.html.ObjectVeiw Class
    Is it possible to set the size of on object, which is an instance of type Component
    Example
    Although these beans work fine, I can not set the width and height properties while they are embedded in the JTextPane. Attempts to give initial values of height & width within the object tag also fail.
    <HTML><BODY bgcolor="#00A0A0">
    Test This <P>page
    <p>This next object is a Simple Bean that extends Canvas
    <object classid="SimpleBean" width="150" height="150">
    <param name="width" value="10">               <! Does not work in JTextPane>
    <param name="height" value="200">     
    <param name="underText" value="Text for the Canvas">
    </object>
    <p>This next object is a JTextPane
    <object classid="javax.swing.JTextPane">
    <param name="text" value="Embeded JTextPane">
    <param name="size" value"150,150">
    </object>
    </BODY></HTML>
    Also could you show me more HTML examples of use

    if there is
    a LayoutManager in use, it will overwrite the size you
    attempt to set. Only if the layout manager is null
    will doing a setSize() work properly.true

  • How to embed SWT to swings

    I have found information regarding how to embed Swings in SWT.
    But i have to embed Swt browser in swings
    Please see the links for examples:
    http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Bringupabrowser.htm
    http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/EmbedSwingandAWTinSWT.htm
    I have to show two browsers in same window which i have partially done by embeding swings in swt. but need the otherway.
    Here is that code:
    import java.awt.Color;
    import java.awt.Frame;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.awt.SWT_AWT;
    import org.eclipse.swt.browser.Browser;
    import org.eclipse.swt.browser.LocationEvent;
    import org.eclipse.swt.browser.LocationListener;
    import org.eclipse.swt.browser.ProgressEvent;
    import org.eclipse.swt.browser.ProgressListener;
    import org.eclipse.swt.browser.StatusTextEvent;
    import org.eclipse.swt.browser.StatusTextListener;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.ProgressBar;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Text;
    import org.eclipse.swt.widgets.ToolBar;
    import org.eclipse.swt.widgets.ToolItem;
    import com.jgoodies.forms.layout.CellConstraints;
    import com.jgoodies.forms.layout.FormLayout;
    public class BringUpBrowser {
    public static void main(String[] args) {
         BringUpBrowser browser= new BringUpBrowser();
         browser.showBrowser();
    public void showBrowser(){
    Display display = new Display();
    final Shell shell = new Shell(display);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    shell.setLayout(gridLayout);
    shell.setMaximized(true);
    final Browser browser1 = new Browser(shell, SWT.NONE);
    GridData data1 = new GridData();
    data1.horizontalAlignment = GridData.FILL;
    data1.verticalAlignment = GridData.FILL;
    data1.horizontalSpan = 3;
    data1.grabExcessHorizontalSpace = true;
    data1.grabExcessVerticalSpace = true;
    browser1.setLayoutData(data1);
    browser1.setUrl("www.indussoftware.com");
    ToolBar toolbar = new ToolBar(shell, SWT.NONE);
    ToolItem itemBack = new ToolItem(toolbar, SWT.PUSH);
    itemBack.setText("Back");
    ToolItem itemForward = new ToolItem(toolbar, SWT.PUSH);
    itemForward.setText("Forward");
    ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
    itemStop.setText("Stop");
    ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
    itemRefresh.setText("Refresh");
    ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
    itemGo.setText("Go");
    GridData data = new GridData();
    data.horizontalSpan = 3;
    toolbar.setLayoutData(data);
    Label labelAddress = new Label(shell, SWT.NONE);
    labelAddress.setText("Address");
    final Text location = new Text(shell, SWT.BORDER);
    data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.horizontalSpan = 2;
    data.grabExcessHorizontalSpace = true;
    location.setLayoutData(data);
    final Browser browser = new Browser(shell, SWT.NONE);
    data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.verticalAlignment = GridData.FILL;
    data.horizontalSpan = 3;
    data.grabExcessHorizontalSpace = true;
    data.grabExcessVerticalSpace = true;
    browser.setLayoutData(data);
    final Label status = new Label(shell, SWT.NONE);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    status.setLayoutData(data);
    final ProgressBar progressBar = new ProgressBar(shell, SWT.NONE);
    data = new GridData();
    data.horizontalAlignment = GridData.END;
    progressBar.setLayoutData(data);
    Composite composite = new Composite(shell, SWT.EMBEDDED);
    data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.verticalAlignment = GridData.CENTER;
    data.horizontalSpan = 3;
    composite.setLayoutData(data);
    Frame frame = SWT_AWT.new_Frame(composite);
    JPanel panel = new JPanel();
    panel.setLayout(new FormLayout("0:grow(0.4),0:grow(0.2),0:grow(0.4)","5dlu,5dlu,16dlu"));
    frame.add(panel);
    CellConstraints cc = new CellConstraints();
    JButton button = new JButton("Close");
    panel.add(new JSeparator(),cc.xyw(1, 1, 3));
    panel.add(button,cc.xy(2, 3));
    button.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                   //this = null;
    //end of chakri
    /* event handling */
    Listener listener = new Listener() {
    public void handleEvent(Event event) {
    ToolItem item = (ToolItem) event.widget;
    String string = item.getText();
    if (string.equals("Back"))
    browser.back();
    else if (string.equals("Forward"))
    browser.forward();
    else if (string.equals("Stop"))
    browser.stop();
    else if (string.equals("Refresh"))
    browser.refresh();
    else if (string.equals("Go"))
    browser.setUrl(location.getText());
    browser.addProgressListener(new ProgressListener() {
    public void changed(ProgressEvent event) {
    if (event.total == 0)
    return;
    int ratio = event.current * 100 / event.total;
    progressBar.setSelection(ratio);
    public void completed(ProgressEvent event) {
    progressBar.setSelection(0);
    browser.addStatusTextListener(new StatusTextListener() {
    public void changed(StatusTextEvent event) {
    status.setText(event.text);
    browser.addLocationListener(new LocationListener() {
    public void changed(LocationEvent event) {
    if (event.top)
    location.setText(event.location);
    public void changing(LocationEvent event) {
    itemBack.addListener(SWT.Selection, listener);
    itemForward.addListener(SWT.Selection, listener);
    itemStop.addListener(SWT.Selection, listener);
    itemRefresh.addListener(SWT.Selection, listener);
    itemGo.addListener(SWT.Selection, listener);
    location.addListener(SWT.DefaultSelection, new Listener() {
    public void handleEvent(Event e) {
    browser.setUrl(location.getText());
    shell.open();
    browser.setUrl("http://google.co.in");
    while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
    display.sleep();
    display.dispose();
    Here Iam facing problems while adding Listeners.
    Can u help me in this?

    GANGINENI wrote:
    hi i developed a program for timer in applet, i want to include it in to jFrame, can some one help me,i am developing program in netbeansYes.
    1) ....
    h1. Edit:
    in light of camickr's note, I am deleting my post. The original poster is now on my DNH list and will remain there until his behavior changes.
    Edited by: Encephalopathic on Oct 31, 2008 2:20 PM

  • Get the duration of all mp3 files inside a directory

    Hello everyone,
    I am working on a little project done with swing. Since I need an mp3 player inside my swing application, I found a really good solution with JavaFX 2. I have never worked with JavaFX before, therefor it seems to me a little bit strange on some parts.
    Anyway.
    I created a button on my application and as soon as somebody presses that button, the application should scan recursivly a unique directory for mp3 files and store the information of artist, title and track length into a database.
    The mp3 player I created is based on the example from this page:
    http://www.java2s.com/Code/Java/JavaFX/Mp3playerwithmetadataviewandcontrolpanel.htm
    I understand the source code for most parts, but some behaivors are not really clear to me. My thoughts about getting the complete length of the mp3 file was
    media.getDuration
    or
    mediaplayer.getTotalDuration
    but both results are NaN if I call .toMillis();
    Instead I need to create a listener (why?)
    private class TotalDurationListener implements InvalidationListener {
        @Override
        public void invalidated(Observable observable) {
          final MediaPlayer mediaPlayer = songModel.getMediaPlayer();
          final Duration totalDuration = mediaPlayer.getTotalDuration();
          totalDurationLabel.setText(formatDuration(totalDuration));
      }and register this listener on the mediaplayer
    mp.totalDurationProperty().addListener(new TotalDurationListener());I can image that the mediaplayer can "host" several media objects somewho and the listener is called as soon as a new media will be added to the mediaplayer in order
    the calculate the overall duration.
    When is this listener exactly called and is there no other ways to get the total length of the mp3 file?
    Here is a minimal example which should work without any external libs
    package de.hauke.schwimmbad.application.playground;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import javafx.application.Platform;
    import javafx.beans.property.ReadOnlyObjectWrapper;
    import javafx.embed.swing.JFXPanel;
    import javafx.scene.Scene;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaPlayer;
    import javafx.scene.paint.Color;
    import javafx.util.Duration;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    public class Testing10 extends JFrame {
         private MediaPlayer mediaPlayer;
         private final ReadOnlyObjectWrapper<MediaPlayer> mediaPlayerWrapper = new ReadOnlyObjectWrapper<MediaPlayer>(
                   this, "mediaPlayer");
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                   new Testing10();
              } catch (Exception ex) {
                   System.out.println(ex);
         public Testing10() {
              super();
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(null);
              setSize(500, 500);
              setTitle("Testing");
              setLocationRelativeTo(null);
              setResizable(false);
              JButton button = new JButton("Scan");
              button.setBounds(10, 10, 150, 30);
              add(button);
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent arg0) {
                        scan();
              final JFXPanel fxPanel = new JFXPanel();
              fxPanel.setBounds(30, 80, 300, 300);
              add(fxPanel);
              Platform.runLater(new Runnable() {
                   public void run() {
                        initFX(fxPanel);
              setVisible(true);
         private void scan() {
              File directory = new File("C:\\dev\\mp3");
              List<File> mp3Files = new ArrayList<File>();
              for (File file : directory.listFiles()) {
                   if(file.getName().endsWith("mp3")) {
                        mp3Files.add(file);
              for (File file : mp3Files) {
                   System.out.println(file.getAbsoluteFile());
                   getLength(file);
         private Duration getLength(File file) {
              if(mediaPlayer != null) {
                   mediaPlayer.stop();
              final Media media = new Media(file.toURI().toString());
              mediaPlayer = new MediaPlayer(media);
              mediaPlayerWrapper.setValue(mediaPlayer);
              if(media.durationProperty()==null) System.out.println("durationProperty ist null");
              if(media.durationProperty().get()==null) System.out.println(".get() ist null");
              System.out.println("---> " + media.durationProperty().get().toMillis());
              return media.getDuration();
         private void initFX(JFXPanel fxPanel) {
              BorderPane root = new BorderPane();
              Scene scene = new Scene(root, Color.ALICEBLUE);
              fxPanel.setScene(scene);
    }The other question is why do I need a listener for the meta data to be changed in order to get the meta data?
    media.getMetadata().addListener(new MapChangeListener<String, Object>()Why can't I call something like
    media.getMetadata() --> returns a filled map?
    The metadata problem is not included inside the example from above.
    Sorry for my english but I hope everybody can understand the issue.
    Many greetings,
    Hauke

    The nature of the Media class is that it accesses it asynchronously. This means that when you create an instance of it, and then immediately query it, the data you want may not be available yet. This is all in the Javadoc, see the doc for Media:
    The media information is obtained asynchronously and so not necessarily available immediately after instantiation of the class. All information should however be available if the instance has been associated with a MediaPlayer and that player has transitioned to MediaPlayer.Status.READY statusSo you could associate the Media with a MediaPlayer, and then wait until it goes to the Status READY, and then read the length of the Media.
    As for your 2nd question, getMetadata() returns a Map. You can just loop through it:
      for(Map.Entry<String, Object> entry : media.getMetadata()) {
        // etc
      }However, the same restrictions apply as with Media -- you will probably need to wait before the information is available -- that's why the Listener approach works, because it will notify you as soon as the information is added to the map.

  • Bind variable value to a Swing component

    I'm totally lost in this one. I've been reading Swing tutorials and books and cant figure it out.
    I have an array of objects and their value is constantly changing as the program runs. What I want is their value reflected inside some Swing componentes. Let's say a bunch of JTextFields and on each one I want to display the value of the objects inside the array and when some of the objects value change, that change is reflected in the value displayed in the corresponding JTextField. Of course the JTextFields could be changed to lets say a JTable. Also the code responsable for changing the displayed value must be independent of the code that change the value of the objects (so the GUI part is independent of the main program)
    Can this be done somehow?? if so, could someone point me in the right direction, maybe with some tutorial/book/url ???
    Thanks a lot, and if something makes no sense, I'll try to explain better.

    Do you know about MVC (Mode View Controller) design? This is exactly what it is all about. There are many different types of implementations of MVC out there (of course in Swing also, before people start to yell at me) but all in all the spirit is pretty much the same.
    Now, for your particular problem, you have different solutions that really depends on what these objects are, what they should look like in the view and whether or not they should be editable in the view. Could you be a little bit more explicit on the matter.
    I can at least give you the idea in general terms. Let's call your objects Entry instances. They should be contained in some kind of a container class, called EntryContainer for example. The EntryContainer should act as a Facade (see the corresponding design pattern) for the rest of your application (that is, the code that change the values of the entries).
    Now, provided you have chosen a internal container (Set, List...). An Entry[] will do fine if you know that the number of entries will not change. In the opposite case, I would suggest a List instance. Then, you add the add/remove/update/whatever public methods to your EntryContainer class.
    What you have now is your model.
    Then, on to the Controller. In Java, it is easy to have a controller subclass its corresponding model. So you create EntryContainerCtrl for instance and EntryCtrl as well. Each controller should hold a reference on its presentation. The best way is to have your presentation hidden behind a generic interface (to guarantee independance from a given implementation as you pointed out in your post).
    The presentation itself should be given a link to its corresponding Controller in order to refresh.
    What you can do now is override the accessors of your model in the controller class. In each of these methods, you call super.method() of course and you add interaction with the presentation to take into account the changes.
    This is just to give you an idea of how it can be done in theory. With such a "design pattern" you can even come to a point where you can dynamically change the presentation.
    Right now, the best for you is to explain a little bit more about your specific problem and I'll be happy to help you design it in a <humble opinion>nice and efficient</humble opinion>

  • How to show a html page in a swing applet -- URGENT!!!

    Hi All,
    I'm trying to show a html page inside a swing applet... is it possible to do that?? if so is there any built-in classes available for that?? If anyone have some examples, plz help me with that....
    Thanks,
    Ragu

    i havent tested.. but this should work. i am no expert on these either, just to give you an example.. :-)
    JEditorPane ePane = new JEditorPane();
    HTMLEditorKit html = new HTMLEditorKit();
    ePane.setEditorKit(html);
    HTMLDocument htmld = new HTMLDocument();
    try{
    URL url = new URL("http://hcs.harvard.edu/~undercon/");
    InputStream ins = url.openStream();
    ePane.setDocument(htmld);
    html.read(ins,htmld, 0);
    this.getContentPane().add(new JScrollPane(ePane),BorderLayout.CENTER);
    catch(Exception e)
    e.printStackTrace();
    }

  • Progress bar on Applet using swing

    Not sure if this is Swing related or applet related, so I'll post it here... :-)
    Long work should be done on a Worker thread an not inside the Swing Dispacher thread .
    So normally I create a Runnable object that calls something like doWork(), and pass the runnable object as a parameter to the Sing utilities invokelater() function.
    My question is inside the worker thread how to update the GUI, in this case the progress bar?
    Can I just call from inside doWork() with no problems the progressbar.setValue(X)?
    Do I need to create another thread and use it too update the UI?
    Is something like this valid ?
    public void doWork() {
    // work work work
    progressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so on
    Thanks for the help!

    Not sure if this is Swing related or applet related,
    so I'll post it here... :-)It's definitely Swing related.
    Long work should be done on a Worker thread an not
    inside the Swing Dispacher thread . This is true.
    So normally I create a Runnable object that calls
    something like doWork(), and pass the runnable object
    as a parameter to the Sing utilities invokelater()
    function.This does not start a worker thread but rather schedules your Runnable object to be run on the EDT.
    My question is inside the worker thread how to update
    the GUI, in this case the progress bar?SwingUtilities or EventQueue have invokeLater and invokeAndWait specifically for this purpose.
    Can I just call from inside doWork() with no problems
    the progressbar.setValue(X)?
    Do I need to create another thread and use it too
    update the UI?No. Here's where you could use invokeLater.
    Is something like this valid ?
    public void doWork() {
    // work work work
    rogressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so onNo.
    >
    Thanks for the help!Like pete has pointed out, this seems to be a job for SwingWorker.

  • SWT: Passing text value to Mouse Event

    I am a little new to java and I am having problems passing the value from Text to mouseDown to be used in the event. When I try to place the name variable into mouseDown it says it must be declared final to do this, but if I declare it final then I can't receive the user input, what do I need to change?
    public class SearchForm {
         public SearchForm(Composite parent)
              GridLayout layout = new GridLayout();
         parent.setLayout(layout);
         Label l = new Label(parent, SWT.NONE);
         l.setText("Please Enter a Name: ");
         l.pack();
         Text name = new Text(parent, SWT.BORDER);
         name.pack();
         Button b = new Button(parent, SWT.PUSH);
         b.setText("Search");
         b.setLocation(0,0);
         b.pack();
         b.addMouseListener(new MouseAdapter()
              public void mouseDown(MouseEvent e)
                   /*Ch4_Contributions sw = new Ch4_Contributions();
                   sw.open();*/
         parent.pack();
    }

    I'm not familiar with SWT, but using Swing, the following example works just fine.
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Test {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setLayout(new GridLayout(2, 1));
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    final JTextField testField = new JTextField("Some text");
                    frame.add(testField);
                    JButton testButton = new JButton("Test");
                    testButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println(testField.getText());
                    frame.add(testButton);
                    frame.pack();
                    frame.setVisible(true);
    }

  • JDeveloper ADF and SWT

    We are considering using JDeveloper 10g (with ADF for the business layer) for a large application. But we would also like to have the option of using SWT rather than Swing for a rich client. Is this possible, and does anybody out there have any tips on how to approach this?
    Thanks.
    Chris

    It might be possible, but you'll e loosing all the automatic binding that you get when using Swing and JClient.
    Any reason why not to use Swing?

  • Embedding applets in Swing GUI?

    I'm pretty new to developing with Swing.
    I want to know what I would need to do in order to embed an applet inside a Swing GUI (if this is possible). I've looked around, but can't seem to find anything with an answer to my question.
    Any help would be greatly appreciated.

    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.Label;
    /** Simplistic example of putting an Applet in a JFrame. */
    public class AppletInSwingGui extends Applet {
      public void init() {
        add( new Label("I am an applet!") );
      public static void main(String[] args) {
        final AppletInSwingGui applet = new AppletInSwingGui();
        // very important!
        applet.init();
        Runnable r = new Runnable() {
          public void run() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add( applet );
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        SwingUtilities.invokeLater(r);
    }Note that if the applet uses the functionality of the AppletContext, the programmer needs to implement it. Some of the Applet specific methods (like getDocumentBase() and getCodeBase()) are also a bit tricky.
    Edited by: AndrewThompson64 on May 20, 2008 12:37 PM

  • Death of Swing

    Hello,
    How to other programmers who have looked inside the Swing java code feel about it?
    It seems to me that this package has developed into spaghetti programming with objects.
    <......................................................................>
    <......................................................................>
    <......................................................................>
    <......................................................................>
    <......................................................................>
    One possible reason I can think of are that the developers have tried too hard to reuse classes.
    Whatever happened to the idea of encapsulation sun?

    I have to agree with you on this one, I cannot stand when I have to look through the Swing code for help. Its convoluded and disgusting. The resued of classes and functionality pays NO attention to performance but rather to the "end result" so they can have a longer feature list.
    Granted Swing is no easy feat, but jesus christ, try and trim it down a little. I wouldn't mind a Toolkit rewrite that got rid of AWT and Swing, but I suppose that's like asking for trees that grow gold... not to mention the cost to the company.

Maybe you are looking for

  • ICal / MobileMe To Dos & iPhone syncing over mobile networks: Solution!!!

    I have been after a solution to use the to do list in iCal on my Mac @ home and the MobileMe Calendar web page while at work & away from home AND have it sync OTA with my iPhone. There hasn't been a solution that I have found for this until now! I ha

  • What video card should I purchase for old iMac?

    I have an old Mac 24 inch, and it seems that the video card is not working. How do I find which video card to purchase? I have a serial number.

  • Update Rules in ABAP to consolidate two InfoSources into one ODS?

    Hello experts, I want to solve the following problem with ABAP update rules (I am a novice in ABAP): In an Oracle DB I have two tables TRANSACTIONS and PARTICIPANTS with an 1:n relationship: One or many PARTICIPANTS can be assigned to one TRANSACTION

  • Replication of Sales organizational data to CRM

    Hi All, I am jus out of cocoon in this CRM world. My query is I run report CRMC_R3_ORG_GENERATE  to replicate Organizational data From ERP to CRM but i dont see any data on the screen. This obliviois ther are lots of things missing probably to call E

  • Aperture to Lightroom Nightmares

    With Apple pulling the plug on Aperture, I reluctantly went over to Amazon and bought a copy of Lightroom 5.5. (If you go to Adobe's site, you can buy only the Cloud version and pay $10/month for all eternity.) I'm hitting snags at everything I attem