Adding Graphics2D to swing

Hi,
I have a few classes / threads that take and write to a graphics2d object. I want to be able to stick a graphics2d object in a swing gui then pass it to these objects and let them do their work. However, everything I find doesn't say I can't do it, but goes about doing all the work in one object and method. How would I go about adding something with a graphics2d object to a window, then drawing all over that?
Thanks

camickr -- how would I paint to the component from other objects though? Your a fast reader. I'm amazed you read the tutorial in less than 5 minutes.
i have a thread that updates and draws a timer on the graphics object
and one that updates and draws a spriteWhy don't you work on solving one problem at a time. Your questions are all over the place. I have no idea why you think you need to do custom painting.
For the timer you create a JLabel and then you change the value of the label at some interval controlled by a Swing Timer (see the tutorial). No need for custom painting.
Not sure what a sprite is. I think its just a custom graphic. So you do the custom painting like I showed you in the example. Then you add the panel with the custom painting to another panel.
So now you have a panel with you timer and a sprite and you use a Layout Manager to postion the components appropriately.

Similar Messages

  • How to change the cursor type when a TableView class was added to a Swing application?

    We can resize column width by dragging the column divider in the table header. This is a built-in feature of the TableView class.
    Normally, the cursor will become to east-resize (or west-resize) type with positioning the cursor just to the right of a column header.
    However, I found that the cursor is remaining the default type at the same position if I integrate JavaFX into Swing Application. That is adding the TableView to a Scene, and then adding this Scene to a JFXPanel, finally, adding this JFXPanel to the JFrame.
    The sample codes are listing below:
    public class Run extends JFrame {
        Run() {
            setSize(600, 450);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            initComponents();
        private void initComponents() {
            final JFXPanel fxPanel = new JFXPanel();
            this.getContentPane().add(fxPanel);
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    initFX(fxPanel);
        private void initFX(JFXPanel fxPanel) {
            Scene scene = null;
            try {
                scene = FXMLLoader.load(
                    new File("res/fxml_example.fxml").toURI().toURL()
            } catch (Exception ex) {
                ex.printStackTrace();
            fxPanel.setScene(scene);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Run().setVisible(true);
    fxml_example.fxml:
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.Scene?>
    <?import javafx.scene.control.TableView?>
    <?import javafx.scene.control.TableColumn?>
    <Scene xmlns:fx="http://javafx.com/fxml">
        <TableView fx:id="tableView"
                   editable="true">
            <columns>
                <TableColumn text="COL1">
                </TableColumn>
                <TableColumn text="COL2">
                </TableColumn>
                <TableColumn text="COL3">
                </TableColumn>
                <TableColumn text="COL4">
                </TableColumn>
                <TableColumn text="COL5">
                </TableColumn>
            </columns>
        </TableView>
    </Scene>
    So, are there anyone can advise how to fix these codes; make the cursor can change to east-resize (or west-resize) type when this TableView class was added to a Swing application?

    Thanks for the report. I've just filed a JIRA issue: https://javafx-jira.kenai.com/browse/RT-34009
    //Anton.

  • Alternative to Anonymous/Inner when Adding Behavior to Swing Elements?

    Hello! I am new to Java and have been trying to teach myself the basics by writing a Swing "JApplet". In adding mouse-click behavior to elements, I have been able to get the desired results by using anonymous "inner" classes. However, I am wondering if there is an alternative way to do this, that may be neater. For example, is there a way to make a non-inner class to apply the behavior, and then use it multiple times? The catch is that I need to apply this behavior to dynamically generated elements, to it has to be able to access certain variables.
    But enough talk, here is a link to the working applet:
    [http://brockfanning.com/RandomCells.html|http://brockfanning.com/RandomCells.html]
    And here is the working code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class RandomCells extends JApplet
         private JPanel mainPanel;
         public void init()
              // Set up main grid
              mainPanel = new JPanel();
              mainPanel.setLayout(new GridLayout(0,2));
              getContentPane().add(mainPanel);
              // add a specific mouse-click behavior for each of a random number of 1 to 10 cells
              int randomNumber = (int)(10 * Math.random()) + 1;
              for (int cell = 1; cell <= randomNumber; cell++)
                   JPanel newCell = new JPanel();
                   mainPanel.add(newCell);
                   newCell.add(new JLabel("Click to dislay the number " + Integer.toString(cell)));
                   // Make the "cell" variable "final" so it can be used in the following anonymous method
                   final int cellFinal = cell;
                   // Add mouseclick behavior to the cell
                   newCell.addMouseListener(new MouseAdapter()
                        public void mouseClicked(MouseEvent me)
                             JOptionPane.showMessageDialog(mainPanel, Integer.toString(cellFinal), "", JOptionPane.PLAIN_MESSAGE);
    }Any help in an alternative to this anonymous inner class technique would be greatly appreciated!

    One more question if possible:
    How would I reference the RandomCells class from the new separated class?
    I'll post what I have below. But notice the "???????" in the new CellClick class. I'm not sure what to put here, as I need to reference the "mainPanel" field of the RandomCells class. Is there any way to do this without explicitly passing the mainPanel as a parameter?
    RandomCells class:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class RandomCells extends JApplet
         private JPanel mainPanel;
         public void init()
              // Set up main grid
              mainPanel = new JPanel();
              mainPanel.setLayout(new GridLayout(0,2));
              getContentPane().add(mainPanel);
              // add a specific mouse-click behavior for each of a random number of 1 to 10 cells
              int randomNumber = (int)(10 * Math.random()) + 1;
              for (int cell = 1; cell <= randomNumber; cell++)
                   JPanel newCell = new JPanel();
                   mainPanel.add(newCell);
                   newCell.add(new JLabel("Click to dislay the number " + Integer.toString(cell)));
                   // Make the "cell" variable "final" so it can be used in the following anonymous method
                   final int cellFinal = cell;
                   // Add mouseclick behavior to the cell
                   newCell.addMouseListener(new CellClick(cellFinal));
    }CellClick class:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CellClick extends MouseAdapter
         // Fields
         private int var1;
         // Constructor
         public CellClick(int var1)
              this.var1 = var1;
         // Methods
         public void mouseClicked(MouseEvent me)
              JOptionPane.showMessageDialog(???????, Integer.toString(this.var1), "", JOptionPane.PLAIN_MESSAGE);
    }

  • Graphics2D + Java Swing

    Hello,
    I am having difficulty in displaying graphics2d(bufferedImage) with Java Swing - The Swing does not show, unless it is a button and you move your mouse over it. The problem disappears when the "public void paint(Graphics g) {.." is employed.
    Can anyone suggest an article to read about solving this?
    regards
    david55

    hi and thanks for your reply and help.
    I got it to work but have another strange problem. Im sure it involves updating or repainting. Basically i create from 1 - 100 images on a JPanel, but the only way they will "appear" is if i manually resize the whole application (dragging). Ive tried repaint() update() etc in multiple locations.
    Am i on the right track and just need to find the right line to insert the code?
    regards,
    david55

  • How to access the Swing Conponents in different Classes

    Hi
    In swing based application, Parent Frame filled with multiple Panels, for each panel i created separate class and added the required swing component.
    components in one panel class require to update/modify components in another panel class.
    For solving this problem i made the components & required methods in a class as STATIC and directly access from another class.
    Is it right approach?
    is there any other approach to solve this issue?
    Thanks
    nidhi

    knidhi wrote:
    Hi
    In swing based application, Parent Frame filled with multiple Panels, for each panel i created separate class and added the required swing component.
    components in one panel class require to update/modify components in another panel class.
    For solving this problem i made the components & required methods in a class as STATIC and directly access from another class.
    Is it right approach? No.
    is there any other approach to solve this issue?Yes. Learn about the MVC design pattern.
    You already implemented the V(iew)-part.
    Now you have to create a M(odel) to hold the Information you want to manipulate and display and a C(ontroller) that changes this information upon the user input (could be combined...)
    Usually the display components register themselves as Listeners to the model and the model publishes state changes to who ever has been registered...
    bye
    TPD

  • Swing in J2ME

    Witch JSR must be added to make swing applications in j2me?
    I know not alle the facilities will be avalible, but any way it must be posible.....or am I wrong?

    Hi,
    It is currently impossible to use Swing in J2ME applications. And I believe that Swing would be too comprehensive for the current latest generation of mobile phones.
    Use the default MIDP 1.0 or 2.0 (depending on your target device) components for your application or try Polish J2ME, which can be used for giving your application a unique look and feel.
    Cheers

  • Swing, Drog and Drop, Transfer Handlers...

    I am writing a game that involves dragging and dropping pegs into various holes. Right now I have a bunch of JLabels that act as bins and a bunch of JLabels that act as holes. All the JLabels have a TransferHandler of type icon set:
    xxx.setTransferHandler(new TransferHandler("icon"));
    The bins have a mouse listener set following the example for adding dnd to swing components without default dnd support:
    MouseListener ml = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    JComponent c = (JComponent)e.getSource();
    TransferHandler th = c.getTransferHandler();
    th.exportAsDrag(c, e, TransferHandler.COPY);
    binsxxx.addMouseListener(ml);
    The transfer handler sets up both source and target capabilities, which I dont want for the bins so I created a DropTarget, disabled it and set the bins droptarget to that:
    DropTarget dt = new DropTarget();
    dt.setEnable(false);
    binsxxx.setDropTarget(dt);
    With these few snippets of code, I can drag a peg (an icon) from bin to hole.
    Finally, onto my question. I know from browsing through he awt.dnd package that there is the capablity of adding an icon to follow the cursor on a drag event. Can I easily add this feature to my program without nullifying the default transferHandler behavior (ie requiring me to go and muck around with the awt.dnd stuff directly)?

    I was wondering if you got to the bottom of this exception?
    I'm implementing dnd between two JTrees in a splitpane & I'm seeing the same exception when the drag leaves a tree. Any suggestions would be greatly appreciated.
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTreeUI$TreeDropTargetListener.restoreComponentState(Unknown Source)
         at javax.swing.plaf.basic.BasicDropTargetListener.dragExit(Unknown Source)
         at javax.swing.TransferHandler$SwingDropTarget.dragExit(Unknown Source)
         at sun.awt.dnd.SunDropTargetContextPeer.processExitMessage(Unknown Source)
         at sun.awt.dnd.SunDropTargetContextPeer.access$700(Unknown Source)
         at sun.awt.dnd.SunDropTargetContextPeer$EventDispatcher.dispatchExitEvent(Unknown Source)
         at sun.awt.dnd.SunDropTargetContextPeer$EventDispatcher.dispatchEvent(Unknown Source)
         at sun.awt.dnd.SunDropTargetEvent.dispatch(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)

  • Calling java swing from c

    Hi
    Is there any difference between calling a java swing application from c and calling a java class that uses no user interface components?
    Do you have to add any extra paths to the classpath variable in the virtual machine structure to make swing work when calling from c?
    To learn how to call java from c I wrote a simple hello world java program and got this working. As soon as I added a JFrame swing component and tried to run the c program then it crashes.
    Thanks for you help.

    Is there any difference between calling a java swing application from c and calling a java class that uses no user interface components?
    No.
    As soon as I added a JFrame swing component and tried to run the c program then it crashes.
    Sounds like you've got a bug in your JNI. Are you making sure to check all the return codes from the JNI functions?
    God bless,
    -Toby Reyelts

  • Waiting for a mouse click in a single thread

    Here's my problem:
    I'm working on a program I didn't initially create, and I picked it up from the rough midpoint of its evolution. It is a single thread AWT program, with a mouseListener interface already implemented.
    Here's my problem. In a game setting, we have two players. It is no problem when both are computer controlled. When player one is controlled by a human, I need to wait for a mouse event before returning, because upon returning player two moves (regardless of its player configuration).
    I can't do any kind of busy waiting because it is a single thread. I'm looking for some kind of option besides making the program multithreaded. This also makes it difficult to use some sort of boolean variable, though I don't think it's impossible.
    Thanks in advance for any help.
    Eric

    #9 - You are correct in your assumptions. I agree it's
    not the best model, but it worked for the original
    purpose, which was to have one player always
    controlled by the computer, and the option of
    selecting a second player as being either human or
    computer. Since each move is made manually - that is,
    for a move to be made, it requires user input - there
    was no harm in returning from a function, because it
    had no immediate computation. The requirements have
    just changed, and now I must allow both players to be
    selectable. This presents a problem in that I have to
    wait for the move actions to finish before
    proceeding.Understood.
    >
    My only question is, how can I access the AWT thread?You mentioned in an earlier post that you have action listeners. As triggered by user events, these are always called on the AWT thread. For example:
    import javax.swing.*;
    import javax.awt.event.*;
    JButton button = new JButton( new AbstractAction {
            public void actionPerformed(ActionEvent e) {
                synchronized (myMonitor) {
                    myMonitor.notifyAll();
        });This button can be added to some swing UI. If clicked on, then actionPerformed will be called on the AWT thread, and any threads waiting on myMonitor will be notified.
    I see what you are saying - it's almost exactly what
    my coworkers told me - but I don't have the knowledge
    to implement it, which is why I'm here. Creating a
    monitor object isn't a problem (makeMove() would need
    to be synchronized, otherwise you wouldn't be able to
    call wait()),I recommend using a separate object for the monitor, especially if you are already using synchronized, so that you know exactly how each object's lock is being used. If you're sure it is safe, then there is nothing wrong with using the object itself as the monitor, as you suggest, however.
    but I'm not sure what you mean by the
    action handling method should be called on the AWT
    thread.Just that any action listener method is always called on the AWT thread in response to user action.
    Dave

  • How to change an applet to an application ?

    My new applet (used to be a working application) has no error messages but does nothing !
    any advice is appreciated
    StanSteve
    steps taken so far to change an application to an applet:
    1) added      import javax.swing.JApplet;2) removed the constructor and replaced it with public void init()[/code
    3)removed public static void main(String[] args) method
    4) created an html file with
    <html>
    <head>
    <title> Pick a Program !</title>
    <body>
    <h3>Adventures in Learning</h3>
    <applet
    archive = "objectdraw.jar"
    codeBase = "."
    code = "TryGridLayout.class" width = 400 height = 400 >
    </applet>
    </body>
    </html>5)added all the classes
    In the ActionListener anonymous class it is supposed to (at the click of a button) call
    one of 3 applications or another applet. Below is the top level class (used to be the main() driver class)
    import objectdraw.*;
    import javax.swing.JApplet;
    import objectdraw.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class ChooseProgram1 extends JApplet
        private JLabel invalidInputLabel;
        JButton myJButtonSketcher;
        JButton myJButtonCalculator;
        JButton myJButtonInfo;
        JButton myJButtonVideo;
          public void init()
          JFrame myJFrame = new JFrame("Choose your program ! !");
          Toolkit myToolkit = myJFrame.getToolkit();
          Dimension myScreenSize = myToolkit.getDefaultToolkit().getScreenSize();
          //  center on screen and set size of frame  to half the screen size
          myJFrame.setBounds(myScreenSize.width / 4, myScreenSize.height / 4,
                          myScreenSize.width / 2, myScreenSize.height / 2);  //(position, size)
            //change the background color
             myJFrame.getContentPane().setBackground(Color.yellow);
            //create the layout manager
            GridLayout myGridLayout = new GridLayout(2,2);
            //get the content pane
            Container myContentPane = myJFrame.getContentPane();
            //set the container layout manager
            myContentPane.setLayout(myGridLayout);
            //create an object to hold the button's style
            Border myEdge = BorderFactory.createRaisedBevelBorder();
          //create the button size
          Dimension buttonSize =  new Dimension(50,50);
          //create the button's font object
          Font myFont = new Font("Arial", Font.BOLD,18);
          //create 1st button's object
          myJButtonCalculator = new JButton("Calculator");
          myJButtonCalculator.setBackground(Color.red);
          myJButtonCalculator.setForeground(Color.black);
          //set the button's border and size and font
          myJButtonCalculator.setBorder(myEdge);
          myJButtonCalculator.setPreferredSize(buttonSize);
          myJButtonCalculator.setFont(myFont);
          //create 2nd button's object
           myJButtonSketcher = new JButton("Sketcher");
          myJButtonSketcher.setBackground(Color.pink);
          myJButtonSketcher.setForeground(Color.black);
          //set the button's border and size and font
          myJButtonSketcher.setBorder(myEdge);
          myJButtonSketcher.setPreferredSize(buttonSize);
          myJButtonSketcher.setFont(myFont);
          //create 3rd button's object
          myJButtonVideo = new JButton("Airplane-Blimp Video");
          myJButtonVideo.setBackground(Color.green);
          myJButtonVideo.setForeground(Color.black);
          //set the button's border and size and font
          myJButtonVideo.setBorder(myEdge);
          myJButtonVideo.setPreferredSize(buttonSize);
          myJButtonVideo.setFont(myFont);
          //create 4th button's object
          myJButtonInfo = new JButton(" Information Directory");
          myJButtonInfo.setBackground(Color.white);
          myJButtonInfo.setForeground(Color.black);
          //set the button's border and size and font
          myJButtonInfo.setBorder(myEdge);
          myJButtonInfo.setPreferredSize(buttonSize);
          myJButtonInfo.setFont(myFont);
         //add the buttons to the content pane
          myContentPane.add(myJButtonCalculator);
          myContentPane.add(myJButtonSketcher);
          myContentPane.add(myJButtonVideo);
          myContentPane.add(myJButtonInfo);
              //add behaviors
              ActionListener l = new ActionListener()
                 public void actionPerformed(ActionEvent e)
                  if(e.getSource() == myJButtonCalculator)
                    new Calculator6();
                    System.out.println("The calculator program executed");
                  else
                    if(e.getSource() == myJButtonSketcher)
                        new Sketcher().init();
                       System.out.println("The Sketcher program executed");
                      else
                        if(e.getSource() == myJButtonVideo)
                          new Grass().init();
                          System.out.println("The applet executed");
                         else
                           if(e.getSource() == myJButtonInfo)
                             TryInfo.main(new String[]{});
                             System.out.println("The Information Directory program executed");
                             else
                               invalidInputLabel.setText("input invalid");
              //add the object listener to listen for the click event on the buttons
              myJButtonCalculator.addActionListener(l);
              myJButtonSketcher.addActionListener(l);
              myJButtonVideo.addActionListener(l);
              myJButtonInfo.addActionListener(l);
          //myJFrame.setVisible(true);
      } //end init() method

    TItle should read " How to change an application to an applet"
    sorry about that

  • Here the SSCCE code for the prvious problem posted by me.

    Following is the SSCCE code for the program of search which is having the problem i have asked before.
    here when you run it will show a form which have a search button on it and when you press it a panel will shown below which have a table( it is just a bounded area without any column or row as i have removed the database functionality and we dont have to do with it).
    the problem is the same that firstly i want to make the panel invisible.
    (the blue and yellow colors are just to seperate the panel and the container) Secondly i want to remove the extra large space added below the last table and thirdly i want that on each press of the search button the scrollbar will focus on the new table added.
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Temp extends JFrame implements ActionListener
         Container c;
         Toolkit tk;
         JLabel l1; int y=30;
         JPanel p1,p2,p3;     
         JRadioButton rbByName,rbBySirName,rbByID,rbByCity,rbByState;
         JButton btSearch,btView;
         ButtonGroup bgSearch;
         JTextField txtSearch; BoxLayout boxl;
         ImageIcon i1;JScrollPane sp1;JViewport vp;
         public Temp()
              super("Search-Address Management System");
              c=getContentPane();
              tk=Toolkit.getDefaultToolkit();
              setSize(1024,768);
              c.setBackground(Color.BLUE);c.setLayout(null);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              defineComponents();
              settingBounds();
              addListeners();
              addComponents();
              setVisible(true);
         public void defineComponents()
              p1=new JPanel();
              p1.setLayout(null);
              p1.setOpaque(false);
              p2=new JPanel();
              p2.setLayout(null);
              p2.setOpaque(false);
              p3=new JPanel();
              boxl=new BoxLayout(p3,BoxLayout.Y_AXIS);
              p3.setLayout(boxl);
              rbByName=new JRadioButton("First Name");
              rbByName.setOpaque(false);
              rbBySirName=new JRadioButton("Last Name");
              rbBySirName.setOpaque(false);
              rbByState=new JRadioButton("State");
              rbByState.setOpaque(false);
              rbByCity=new JRadioButton("City");
              rbByCity.setOpaque(false);
              rbByID=new JRadioButton("ID");
              rbByID.setOpaque(false);
              btSearch=new JButton("Search");
              bgSearch=new ButtonGroup();
              txtSearch=new JTextField();
              btSearch=new JButton("Search");
              TitledBorder tb=new TitledBorder("Search Criteria");
              TitledBorder tb1=new TitledBorder("Search");
              p1.setBorder(tb);
              p2.setBorder(tb1);
         public void settingBounds()
              rbByID.setBounds(20,30,50,20);
              rbByName.setBounds(120,30,100,20);
              rbByState.setBounds(20,70,80,20);
              rbByCity.setBounds(120,70,50,20);
              rbBySirName.setBounds(240,30,100,20);
              p1.setBounds(30,40,400,110);
              p2.setBounds(30,180,400,80);
              p3.setBackground(Color.ORANGE);
              txtSearch.setBounds(50,210,250,25);
              btSearch.setBounds(320,210,80,25);
              rbByID.setSelected(true);
         public void addListeners()
              btSearch.addActionListener(this);
         public void addComponents()
              p1.add(rbByName);
              p1.add(rbBySirName);
              p1.add(rbByState);
              p1.add(rbByCity);
              p1.add(rbByID);
              c.add(txtSearch);
              c.add(btSearch);
              c.add(p1);
              c.add(p2);
              bgSearch.add(rbByID);
              bgSearch.add(rbByName);
              bgSearch.add(rbBySirName);
              bgSearch.add(rbByCity);
              bgSearch.add(rbByState);
         public void drawtable()
              JTable t1=new JTable()
                  public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
              if(y==30) //as temporay variable only to add the scrollpane once
                   sp1=new JScrollPane(p3,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   sp1.setBounds(30,300,660,380);
                   c.add(sp1); 
              JScrollPane sp=new JScrollPane(t1);
              sp1.getViewport().setOpaque(false); // to make the scrollpane transparent but not worked
              sp.setMaximumSize(new Dimension(600,100));
              p3.add(Box.createRigidArea(new Dimension(600,20)));//  invisible filler to add space between two tables
              p3.add(sp);
              p3.revalidate();
              y=y+110;
         public void actionPerformed(ActionEvent e)
              if(e.getSource()==btSearch)
              drawtable();
         public static void main(String args[])
              new Temp();
    }Please reply with the code required to be added.

    the problem is the same that firstly i want to make the panel invisible.If I remember you other postings I think you mean to say transparent, which means the background of its parent component will be painted. If you make the panel invisible, then all the component added to the panel will also be invisible.
    You have a structure something like this:
    main panel
        - scroll pane
            - viewport
                - table panel
                    - table1
                    - table 2As you where told in one of you many other posting on this topic, if you want the background of the main panel to show through then you need to make all the component on top of the pane non-opaque, not just the viewport. So, the scroll pane and table panel also need to be changed.
    And don't forget to reply to all your other postings on this topic stating that those postings are "closed" so people don't waste time answering in those postings. Keep the conversation in one posting so everybody knows what has been suggested.

  • Best Practice: Executing the same code from different triggers

    Swing supports the idea of Actions, which seems to be an implementation of the "Command" pattern. One can create an instance of an Action implementation and set it to several JComponents, like JButton and JMenuItem. Whenever the button or the menu item is triggered, the action gets executed. So far, so good.
    But there are more triggers in Swing that cannot get configured to trigger an action, namely Drops and pressing the window's [X] Close icon. Certainly these fire events, but they do not automatically trigger actions.
    Certainly one can react to importData(TransferSupport) and windowClosing() by manually calling the action's actionPerformed(ActionEvent) method, but as there is no setAction(Action) method at neither the TransferHandler class nor the WindowAdapter class, the question is: Where to take that Action instance from, and what command name to pass to it's constructor, and what to provide as the event source?
    It just seems like the Action framework has a gap here, as it nicely covers these questions for JComponents, but not for JFrame and JDialog.
    So unless there are JFrame.setDropAction(Action) and JFrame.setCloseAction(Action) methods added to the Swing framework (and I doubt they will get added any time near), my question is whether there have been establed some widely accepted best practices (i. e. something that 75% of the programmers will do, not something ONE programmer always does but just he does). Any Swing expert here answering this?

    The window decorations are handled by the OS. That [X] close button isn't a JButton at all.
    JFrame's and JDialog's, however, do have a root panes. And you can ask the root pane to take over window decorations via JFrame#setDefaultLookAndFeelDecorated(true). JDialog has a similar method. When the root pane takes over window decorations, then the [X] icon is a JButton and you could, in theory, set its action to an Action object.
    The the metal LAF window decorations, however, are ugly (I think at least) and I'm not sure how many programs actually use it.

  • HOW DO I MAKE A FRAME TO VIEW THE PROGRESS OF A PROCESS

    hi there,
    I have a frame with a javax.swing.JTextPane, I read a file, line to line to make a query to insert in a database.
    I want, when the app read a line, this line is added to javax.swing.JTextPane and show it.
    i have this code.
    lblProceso.setText( lblProceso.getText() + "Linea : " + linea);
    System.out.println( lblProceso.getText() + "Linea : " + linea);The app show the lines, but when the app finished.
    the second line in code, print the line in the output window, I want this in the app.
    can help me, I want this frame like the "output of netbeans"
    tks

    You will have more chance at a suitable response if you post this Swing related question at the Swing forum at a normal manner. Thus not with the topic title all in uppercase, it is considered as shouting which is very rude. Make yourself familiar with the netiquette.

  • How to get start CDC with Windows Mobile 5

    i have bought new PDA (imate K-JAM) and want to develop CDC on it but i don't know what i need for develop it
    i found this site (http://home.elka.pw.edu.pl/~pboetzel/) i need to download all require software ? if no please tell me what i need to download ?
    thank you!!
    Message was edited by:
    ekkapop

    Hi ekkapop,
    First you need to find a JVM that support CDC, here are 2 of them for Pocket PC:
    -IBM J9
    -Creme
    Then choose the IDE of your preference (Eclipse, Netbeans...)
    I order to keep the best compability use only AWT components and compile with javac 1.4 or lower and jar your project.
    It should run just fine on thoses JVMs.
    Now this is the way to keep simple, then you can try adding swt or swing libraries to enrich your project and try other packs for IDE.
    But using awt components and compiling with javac 1.4 have worked just fine for me.
    Now I am also beggining with the J2ME so this is just the first feedback I can give for now.
    Regards,
    Romain

  • Access fo Method parameters to Anonymous Class ?

    Can somebody please provide some more information on the statement below? I am also searching for some sample code implementations of it. It would help the cause better.
    +"Methods of the object of the anonymous class need access to final local variables and method parameters belonging to the method in which the anonymous class is defined. "+
    Thanks in Advance

    We're concerned here with "local" classes, i.e. classes defined inside methods (not all anonymous classes are local, and not all local classes are anonymous).
    The thing about local classes is that, unlike local variables etc., instances of a local class may survive the method returning. For example a local class might be a listener which gets added to a swing component, it could be a Runnable that get's launched as a thread.
    Local classes get to access local variables and parameters of the method in which they are declared but the variables or parameters have to be declared final because, since the class needs to be able to access the value of the local variable even after the method exits, and the variable ceases to exist, what actually happens it that the value of the variable is copied into a special field of the anonymous class, and if the variable could be changed after the class was defined, the two copies would then disagree.

Maybe you are looking for