Search Results

Search found 57 results on 3 pages for 'mouselistener'.

Page 1/3 | 1 2 3  | Next Page >

  • Need Help: adding MouseListeners to JComponents (Drawing a JComponent and then attaching a MouseListener)

    - by user1074574
    Drawing a JComponent and then attaching a MouseListener seems very simple to me, but not in this case: I'm having a problem with a MouseListener attached to a child JComponent; here's some brief code to help describe it: Note: The BGT class has implemented ActionListers/MouseListeners that do not have any code in them, and 'figures' is an array of SwingThings. public class GC extends BGT{ public GC(){ super(); buildJMenu(); drawPanel.addMouseListener(this); //drawPanel being the panel that draws the JComponents (it is a public variable in the BGT class) drawPanel.addMouseMotionListener(this); this.addMouseListener(this); } public static void main(String[] args){ GC a = new GC(); }... public void mouseClicked(MouseEvent e) { System.out.println(e.getSource()); //This only seems to print out the DrawPanel's information }... public void mouseReleased(MouseEvent e) { repaint(); ... tempMyJTextField = new MyJTextField(startX, startY, width, height); tempMyJTextField.addMouseListener(this); tempMyJTextField.addMouseMotionListener(this); figures.add(tempMyJTextField); for(int i = 0; i < figures.size(); i++) figures.get(i).addTo(drawPanel); } This is the addTo method in the MyJTextField class: public class MyJTextField extends JTextField implements SwingThing{ ... public void addTo(JPanel p) { p.add(myTextField); } ... } In the MouseClicked event it never registers that the JComponent was clicked. (The drawing/painting works fine) Thanks.

    Read the article

  • Java MouseListener

    - by ikurtz
    I have a bunch of JLabels and i would like to trap mouse click events. at the moment i am having to use: public void mouseClicked(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mouseEntered(MouseEvent arg0) { } public void mousePressed(MouseEvent arg0) { } public void mouseReleased(MouseEvent arg0) { System.out.println("Welcome to Java Programming!"); } I was wondering if there is a tidier way of doing this instead of having a bunch of events I do not wish trap?

    Read the article

  • how to remove MouseListener / ActionListener on a JTextField

    - by mithun1538
    Hello everyone, I have the following code adding an ActionListener to a JTextField: chatInput.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { chatInputMouseClicked(evt); } }); Now how do I remove this MouseListener using chatInput.removeMouseListener(), since this function needs an argument?

    Read the article

  • How to click through JGlassPane With MouseListener to UI behind it

    - by Epicmaster
    I have a JFrame and a bunch of JComponents on top of the JFrame. I need to make use of the JGlassPane and I used this implementation to set it up. JPanel glass = new JPanel(); frame.setGlassPane(glass); glass.setVisible(true); glass.setOpaque(false); After doing so I can't select any JButtons or other JComponents under the JGlassPane. Is there a way to have only the components on the GlassPane selectable while still having the ability to select components under the GlassPane? Edit I forgot to mention (not knowing this would be relevant) that I did attach both a MouseListener and a MouseMotionListener to the glass pane. Is there a way to pass the Mouse Events to other components and only use them when needed?

    Read the article

  • Implementing Drag and Drop using MouseListener for custom Components

    - by Chris Lieb
    I am working on a school assignment that requires me to be able to pick up a tile, drag it to a location, then drop it there. I was able to get this working using TransferHandler and a bunch of stuff from the dnd package, but this is not an acceptable way to perform this action for this assignment according to the professor. So, I am trying to achieve the same effect using the MouseListener interface. The basic setup is this: I have a JPanel-derived class called LocationView that contains JLabel-dervived instances of TileView. I need to get events that give me the LocationView that has the mouse pressed on and the LocationView that has the mouse released on. I am proxying mouse events through the TileView to its containing LocationView so that I can properly handle the mousePressed event. I added System.out.println()'s to the mouse listeners for mousePressed and mouseReleased to both LocationView and TileView so that I could observe the events that were being generated. To my surprise, pressing the mouse on Tile A in Location A, then dragging to Location B and releasing would generate a mouse released event for both Tile A and Location A, but not for Location B. I need the mouse released event triggered for only Location B. To try to work around this, I tried implementing a glass pane based off of the FinalGlassPane found at http://weblogs.java.net/blog/2006/09/20/well-behaved-glasspane. After adding the glass pane and adding an event listener for it, I can see that the mouse events are indeed filtering through the glass pane, but the mouse released event is still only being called on the item the mouse was clicked on. Is there a way to have mousePressed and mouseReleased events associated with the same drag action be called on separate components?

    Read the article

  • MouseListener fired without checking JCheckBox

    - by Morinar
    This one is pretty crazy: I've got an AppSight recording (for those not familiar, it's a recording of what they did including keyboard/mouse input + network traffic, etc) of a customer reproducing a bug. Basically, we've got a series of items listed on the screen with JCheckBox-es down the left side. We've got a MouseListener set for the JPanel that looks something like this: private MouseAdapter createMouseListener() { return new MouseAdapter(){ public void mousePressed( MouseEvent e ) { if( e.getComponent() instanceof JCheckBox ) { // Do stuff } } }; } Based on the recording, it appears very strongly that they click just above one of the checkboxes. After that, it's my belief that this listener fired and the "Do stuff" block happened. However, it did NOT check the box. The user then saw that the box was unchecked, so they clicked on it. This caused the "Do stuff" block to fire again, thus undoing what it had done the first time. This time, the box was checked. Therefore, the user thinks that the box is checked, and it looks like it is, but our client thinks that the box is unchecked as it was clicked twice. Is this possible at all? For the life of me, I can't reproduce it or see how it could be possible, but based on the recording and the data the client sent to the server, I can't see any other logical explanation. Any help, thoughts, and or ideas would be much appreciated.

    Read the article

  • How do I make a rectangle move in an image?

    - by alicedimarco
    Basically I have an image loaded, and when I click a portion of the image, a rectangle (with no fill) shows up. If I click another part of the image again, that rectangle will show up once more. With each click, the same rectangle should appear. So far I have this code, now I don't know how to make the image appear. My image from my file directory. I have already made the code to get the image from my file directory. import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class MP2 extends JPanel implements MouseListener{ JFrame frame; JPanel panel; int x = 0; int y = 0; String input; public MP2(){ } public static void main(String[] args){ JFrame frame = new JFrame(); MP2 panel = new MP2(); panel.addMouseListener(panel); frame.add(panel); frame.setSize(200,200); frame.setVisible(true); } public void mouseClicked(MouseEvent event) { // TODO Auto-generated method stub this.x = event.getX(); this.y = event.getY(); this.repaint(); input = JOptionPane.showInputDialog("Something pops out"); System.out.println(input); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } public void paintComponent(Graphics g){ super.paintComponent(g); // this.setBackground(Color.white); *Sets the bg color of the panel g.setColor(new Color(255,0,0)); g.drawRect(x, y, 100, 100); } }

    Read the article

  • Is there any way to add a MouseListener to a Graphic object ?

    - by Fahad
    Hi, Is there any way to add a MouseListener to a Graphic object. I have this simple GUI that draw an oval. What I want is handling the event when the user clicks on the oval import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public class Gui2 extends JFrame { JFrame frame = new JFrame(); MyDrawPanel drawpanel = new MyDrawPanel(); public static void main(String[] args) { Gui2 gui = new Gui2(); gui.go(); } public void go() { frame.getContentPane().add(drawpanel); // frame.addMouseListener(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } } class MyDrawPanel extends JComponent implements MouseListener { public void paintComponent(Graphics g) { int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); Color startrandomColor = new Color(red, green, blue); red = (int) (Math.random() * 255); green = (int) (Math.random() * 255); blue = (int) (Math.random() * 255); Color endrandomColor = new Color(red, green, blue); Graphics2D g2d = (Graphics2D) g; this.addMouseListener(this); GradientPaint gradient = new GradientPaint(70, 70, startrandomColor, 150, 150, endrandomColor); g2d.setPaint(gradient); g2d.fillOval(70, 70, 100, 100); } @Override public void mouseClicked(MouseEvent e) { if ((e.getButton() == 1) && (e.getX() >= 70 && e.getX() <= 170 && e.getY() >= 70 && e .getY() <= 170)) { this.repaint(); // JOptionPane.showMessageDialog(null,e.getX()+ "\n" + e.getY()); } } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } } This Works Except it fires when the click is within a virtual box around the oval. Could anyone help me to have it fire when the click is EXACTLY on the oval. Thanks in advance.

    Read the article

  • Possible to manipulate UI elements via dispatchEvent()?

    - by rinogo
    Hi all! I'm trying to manually dispatch events on a textfield so I can manipulate it indirectly via code (e.g. place cursor at a given set of x/y coordinates). However, my events seem to have no effect. I've written a test to experiment with this phenomenon: package sandbox { import flash.display.Sprite; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.TextFieldType; import flash.text.TextFieldAutoSize; import flash.utils.setTimeout; public class Test extends Sprite { private var tf:TextField; private var tf2:TextField; public function Test() { super(); tf = new TextField(); tf.text = 'Interact here'; tf.type = TextFieldType.INPUT; addChild(tf); tf2 = new TextField(); tf2.text = 'Same events replayed with five second delay here'; tf2.autoSize = TextFieldAutoSize.LEFT; tf2.type = TextFieldType.INPUT; tf2.y = 30; addChild(tf2); tf.addEventListener(MouseEvent.CLICK, mouseListener); tf.addEventListener(MouseEvent.DOUBLE_CLICK, mouseListener); tf.addEventListener(MouseEvent.MOUSE_DOWN, mouseListener); tf.addEventListener(MouseEvent.MOUSE_MOVE, mouseListener); tf.addEventListener(MouseEvent.MOUSE_OUT, mouseListener); tf.addEventListener(MouseEvent.MOUSE_OVER, mouseListener); tf.addEventListener(MouseEvent.MOUSE_UP, mouseListener); tf.addEventListener(MouseEvent.MOUSE_WHEEL, mouseListener); tf.addEventListener(MouseEvent.ROLL_OUT, mouseListener); tf.addEventListener(MouseEvent.ROLL_OVER, mouseListener); } private function mouseListener(event:MouseEvent):void { //trace(event); setTimeout(function():void {trace(event); tf2.dispatchEvent(event);}, 5000); } } } Essentially, all this test does is to use setTimeout to effectively 'record' events on TextField tf and replay them five seconds later on TextField tf2. When an event is dispatched on tf2, it is traced to the console output. The console output upon running this program and clicking on tf is: [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=0 localY=1 stageX=0 stageY=1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="rollOver" bubbles=false cancelable=false eventPhase=2 localX=0 localY=1 stageX=0 stageY=1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseOver" bubbles=true cancelable=false eventPhase=3 localX=0 localY=1 stageX=0 stageY=1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=2 localY=1 stageX=2 stageY=1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=2 localY=2 stageX=2 stageY=2 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=2 localY=3 stageX=2 stageY=3 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=3 localY=3 stageX=3 stageY=3 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=5 localY=3 stageX=5 stageY=3 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=6 localY=5 stageX=6 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=7 localY=5 stageX=7 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=9 localY=5 stageX=9 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=10 localY=5 stageX=10 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=11 localY=5 stageX=11 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=12 localY=5 stageX=12 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseDown" bubbles=true cancelable=false eventPhase=3 localX=12 localY=5 stageX=12 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseUp" bubbles=true cancelable=false eventPhase=3 localX=12 localY=5 stageX=12 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="click" bubbles=true cancelable=false eventPhase=3 localX=12 localY=5 stageX=12 stageY=5 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=10 localY=4 stageX=10 stageY=4 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=9 localY=2 stageX=9 stageY=2 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseMove" bubbles=true cancelable=false eventPhase=3 localX=9 localY=1 stageX=9 stageY=1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="mouseOut" bubbles=true cancelable=false eventPhase=3 localX=-1 localY=-1 stageX=-1 stageY=-1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] [MouseEvent type="rollOut" bubbles=false cancelable=false eventPhase=2 localX=-1 localY=-1 stageX=-1 stageY=-1 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0] As we can see, the events are being captured and replayed successfully. However, no change occurs in tf2 - the mouse cursor does not appear in tf2 as we would expect. In fact, the cursor remains in tf even after the tf2 events are dispatched. Please help! Thanks, -Rich

    Read the article

  • How do I get my character to move after adding to JFrame?

    - by A.K.
    So this is kind of a follow up on my other JPanel question that got resolved by playing around with the Layout... Now my MouseListener allows me to add a new Board(); object from its class, which is the actual game map and animator itself. But since my Board() takes Key Events from a Player Object inside the Board Class, I'm not sure if they are being started. Here's my Frame Class, where SideScroller S is the player object: package OurPackage; //Made By A.K. 5/24/12 //Contains Frame. import java.awt.BorderLayout; import java.awt.Button; import java.awt.CardLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener; public class Frame implements MouseListener { public static boolean StartGame = false; JFrame frm = new JFrame("Action-Packed Jack"); ImageIcon img = new ImageIcon(getClass().getResource("/Images/ActionJackTitle.png")); ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png")); public Image Title; JLabel TitleL = new JLabel(img); public JPanel TitlePane = new JPanel(); public JPanel BoardPane = new JPanel(); JPanel cards; JButton StartB = new JButton(StartImg); Board nBoard = new Board(); static Sound nSound; public Frame() { frm.setLayout(new GridBagLayout()); cards = new JPanel(new CardLayout()); nSound = new Sound("/Sounds/BunchaJazz.wav"); TitleL.setPreferredSize(new Dimension(970, 420)); frm.add(TitleL); frm.add(cards); cards.setSize(new Dimension(150, 45)); cards.setLayout(new GridBagLayout ()); cards.add(StartB); StartB.addMouseListener(this); StartB.setPreferredSize(new Dimension(150, 45)); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(1200, 420); frm.setVisible(true); frm.setResizable(false); frm.setLocationRelativeTo(null); frm.pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new Frame(); } }); } public void mouseClicked(MouseEvent e) { nSound.play(); StartB.setContentAreaFilled(false); cards.remove(StartB); frm.remove(TitleL); frm.remove(cards); frm.setLayout(new GridLayout(1, 1)); frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200 nBoard.setPreferredSize(new Dimension(1200, 420)); cards.revalidate(); frm.validate(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }

    Read the article

  • JList - deselect when clicking an already selected item

    - by Peter
    If a selected index on a JList is clicked, I want it to de-select. In other words, clicking on the indices actually toggles their selection. Didn't look like this was supported, so I tried list.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { java.awt.Point point = evt.getPoint(); int index = list.locationToIndex(point); if (list.isSelectedIndex(index)) list.removeSelectionInterval(index, index); } }); The problem here is that this is being invoked after JList has already acted on the mouse event, so it deselects everything. So then I tried removing all of JList's MouseListeners, adding my own, and then adding all of the default listeners back. That didn't work, since JList would reselect the index after I had deselected it. Anyway, what I eventually came up with is MouseListener[] mls = list.getMouseListeners(); for (MouseListener ml : mls) list.removeMouseListener(ml); list.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { java.awt.Point point = evt.getPoint(); final int index = list.locationToIndex(point); if (list.isSelectedIndex(index)) SwingUtilities.invokeLater(new Runnable() { public void run() { list.removeSelectionInterval(index, index); } }); } }); for (MouseListener ml : mls) list.addMouseListener(ml); ... and that works. But I don't like it. Is there a better way?

    Read the article

  • Set the amount of rows JList show (Java)

    - by Alex Cheng
    Hi all. Problem: I have a method that creates a list from the parsed ArrayList. I manage to show the list in the GUI, without scrollbar. However, I am having problem setting it to show only the size of ArrayList. Meaning, say if the size is 6, there should only be 6 rows in the shown List. Below is the code that I am using. I tried setting the visibleRowCount as below but it does not work. I tried printing out the result and it shows that the change is made. private void createSuggestionList(ArrayList<String> str) { int visibleRowCount = str.size(); System.out.println("visibleRowCount " + visibleRowCount); listForSuggestion = new JList(str.toArray()); listForSuggestion.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listForSuggestion.setSelectedIndex(0); listForSuggestion.setVisibleRowCount(visibleRowCount); System.out.println(listForSuggestion.getVisibleRowCount()); listScrollPane = new JScrollPane(listForSuggestion); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { JList theList = (JList) mouseEvent.getSource(); if (mouseEvent.getClickCount() == 2) { int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { Object o = theList.getModel().getElementAt(index); System.out.println("Double-clicked on: " + o.toString()); } } } }; listForSuggestion.addMouseListener(mouseListener); textPane.add(listScrollPane); repaint(); } To summarize: I want the JList to show as many rows as the size of the parsed ArrayList, without a scrollbar. Any ideas? Please help. Thanks. Please let me know if a picture of the problem is needed in case I did not phrase my question correctly.

    Read the article

  • abstract class MouseAdapter vs. interface

    - by Stefano Borini
    I noted this (it's a java.awt.event class). public abstract class MouseAdapter implements MouseListener, MouseWheelListener, MouseMotionListener { .... } Then you are clearly forced to extend from this adapter public class MouseAdapterImpl extends MouseAdapter {} the class is abstract and implements no methods. Is this a strategy to combine different interfaces into a single "basically interface" ? I assume in java it's not possible to combine different interfaces into a single one without using this approach. In other words, it's not possible to do something like this in java public interface MouseAdapterIface extends MouseListener, MouseWheelListener, MouseMotionListener { } and then eventually public class MouseAdapterImpl implements MouseAdapterIface {} Is my understanding of the point correct ? what about C# ?

    Read the article

  • Problem with JPopupMenu in a JTree

    - by Alex
    Hi guys I have this issue. In a custom JTree I implemented a JPopupMenu to display different JMenuItem according to the node selected using a MouseListener. The JPopupMenu is shown when the mouse right button is clicked. The problem is that if I don’t choose an Item from the PopupMenu but instead I select another node in the tree, either with right or left buttons, this event is never caught by the tree MouseListener Could anyone point me in the right direction to solve this? In case an example is available I’ll appreciate it. Thanks.

    Read the article

  • Can't remove JPanel from JFrame while adding new class into it

    - by A.K.
    Basically, I have my Frame class, which instantiates all the properties for the JFrame, and draws a JLabel with an image (my title screen). Then I made a separate JPanel with a start button on it, and made a mouse listener that will allow me to remove these objects while adding in a new Board() class (Which paints the main game). *Note: The JLabel is SEPARATE from the JPanel, but it still gets moved to the side by it. Problem: Whenever I click the button though, it only shows a little square of what I presume is my board class trying to run. Code below for the Frame Class: package OurPackage; //Made By A.K. 5/24/12 //Contains Frame. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener; public class Frame implements MouseListener { public static boolean StartGame = false; ImageIcon img = new ImageIcon(getClass().getResource("/Images/ActionJackTitle.png")); ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png")); public Image Title; JLabel TitleL = new JLabel(img); public JPanel panel = new JPanel(); JButton StartB = new JButton(StartImg); JFrame frm = new JFrame("Action-Packed Jack"); public Frame() { TitleL.setPreferredSize(new Dimension(1200, 420)); frm.add(TitleL); frm.setLayout(new GridBagLayout()); frm.add(panel); panel.setSize(new Dimension(220, 45)); panel.setLayout(new GridBagLayout ()); panel.add(StartB); StartB.addMouseListener(this); StartB.setPreferredSize(new Dimension(220, 45)); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(1200, 420); frm.setVisible(true); frm.setResizable(false); frm.setLocationRelativeTo(null); } public static void main(String[] args) { new Frame(); } public void mouseClicked(MouseEvent e) { StartB.setContentAreaFilled(false); panel.remove(StartB); frm.remove(panel); frm.remove(TitleL); //frm.setLayout(null); frm.add(new Board()); //Add Game "Tiles" Or Content. x = 1200 frm.validate(); System.out.println("Hit!"); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }

    Read the article

  • Java swing hold buttons

    - by Simon Charette
    Hi, I'm trying to create a subclass of JButton or AbstractButton that would call specified .actionPerformed as long as the mouse is held down on the button. So far I was thinking of extending JButton, adding a mouse listener on creation (inside constructor) and calling actionPerformed while the mouse is down. So far i came up with that but I was wondwering if I was on the right track and if so, how to correctly implement the "held down" logic. package components; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; public class HoldButton extends JButton { private class HeldDownMouseListener implements MouseListener { private boolean mouseIsHeldDown; private HoldButton button; private long millis; public HeldDownMouseListener(HoldButton button, long millis) { this.button = button; this.millis = millis; } @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { mouseIsHeldDown = true; // This should be run in a sub thread? // while (mouseIsHeldDown) { // button.fireActionPerformed(new ActionEvent(button, ActionEvent.ACTION_PERFORMED, "heldDown")); // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // e.printStackTrace(); // continue; // } // } } @Override public void mouseReleased(MouseEvent arg0) { mouseIsHeldDown = false; } } public HoldButton() { addHeldDownMouseListener(); } public HoldButton(Icon icon) { super(icon); addHeldDownMouseListener(); } public HoldButton(String text) { super(text); addHeldDownMouseListener(); } public HoldButton(Action a) { super(a); addHeldDownMouseListener(); } private void addHeldDownMouseListener() { addMouseListener(new HeldDownMouseListener(this, 300)); } } Thanks a lot for your time.

    Read the article

  • Trying to get focus onto JTextPane after doubleclicking on JList element (Java)

    - by Alex Cheng
    Hi all. Problem: I have the following JList which I add to the textPane, and show it upon the caret moving. However, after double clicking on the Jlist element, the text gets inserted, but the caret is not appearing on the JTextPane. This is the following code: listForSuggestion = new JList(str.toArray()); listForSuggestion.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listForSuggestion.setSelectedIndex(0); listForSuggestion.setVisibleRowCount(visibleRowCount); listScrollPane = new JScrollPane(listForSuggestion); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { JList theList = (JList) mouseEvent.getSource(); if (mouseEvent.getClickCount() == 2) { int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { Object o = theList.getModel().getElementAt(index); //System.out.println("Double-clicked on: " + o.toString()); //Set the double clicked text to appear on textPane String completion = o.toString(); int num= textPane.getCaretPosition(); textPane.select(num, num); textPane.replaceSelection(completion); textPane.setCaretPosition(num + completion.length()); int pos = textPane.getSelectionEnd(); textPane.select(pos, pos); textPane.replaceSelection(""); textPane.setCaretPosition(pos); textPane.moveCaretPosition(pos); } } theList.clearSelection(); Any idea on how to "de-focus" the selection on the Jlist, or make the caret appear on the JTextPane after the text insertion? I'll elaborate more if this is not clear enough. Please help, thanks!

    Read the article

  • TextField breaking MOUSE_OVER in as3: only after moving it!

    - by Franz
    I'm having a really weird problem with the MOUSE_OVER event. I'm building dynamic tabs representing mp3 songs containing textfields with info and a dynamic image for the cover art. I am trying to get a simple MOUSE_OVER working over the whole tab, such that you can select the next song to play. I am using a Sprite with alpha 0 that overlays my whole tab (incl. the textFields) as a Listener for MOUSE_OVER and _OUT... I've checked by setting the alpha to something visible and it indeed covers my tab and follows it around as I move it (just making sure I'm not moving the tab without moving the hotspot). Also, I only create it once my cover art is loaded, ensuring that it will cover that too. Now, when the tab is in the top position, everything is dandy. As soon as I move the tab to make space for the next tab, the textFields break my roll behaviour... just like that noob mistake of overlaying a sprite over the one that you're listening for MouseEvents on. But... the roll area is still on top of the field, I've set selectable and mouseEnabled to false on the textFields... nothing. It is as if the mere fact of moving the whole tab now puts the textField on top of everything in my tab (whereas visually, it's still in its expected layer). I'm using pixel fonts but tried it with system fonts, same thing... at my wits end here. public function Tab(tune:Tune) { _tune = tune; mainSprite = new Sprite(); addChild(mainSprite); drawBorder(); createFormat(); placeArtist(); placeTitle(); placeAlbum(); coverArt(); } private function placeButton():void { _button = new Sprite(); _button.graphics.beginFill(0xFF000,0); _button.graphics.drawRect(0,0,229,40); _button.graphics.endFill(); _button.addEventListener(MouseEvent.MOUSE_OVER, mouseListener); _button.addEventListener(MouseEvent.MOUSE_OUT, mouseListener); _button.buttonMode = true; mainSprite.addChild(_button); } private function mouseListener(event:MouseEvent):void { switch(event.type){ case MouseEvent.MOUSE_OVER : hilite(true); break; case MouseEvent.MOUSE_OUT : hilite(false); break; } } private function createFormat():void { _format = new TextFormat(); _format.font = "FFF Neostandard"; _format.size = 8; _format.color = 0xFFFFFF; } private function placeArtist():void { var artist : TextField = new TextField(); artist.selectable = false; artist.defaultTextFormat = _format; artist.x = 41; artist.y = 3; artist.width = 135; artist.text = _tune.artist; artist.mouseEnabled = false; mainSprite.addChild(artist); } private function placeTitle():void { var title : TextField = new TextField(); title.selectable = false; title.defaultTextFormat = _format; title.x = 41; title.y = 14; title.width = 135; title.text = _tune.title; title.mouseEnabled = false; mainSprite.addChild(title); } private function placeAlbum():void { var album : TextField = new TextField(); album.selectable = false; album.defaultTextFormat = _format; album.x = 41; album.y = 25; album.width = 135; album.text = _tune.album; album.mouseEnabled = false; mainSprite.addChild(album); } private function drawBorder():void { _border = new Sprite(); _border.graphics.lineStyle(1, 0x545454); _border.graphics.drawRect (0,0,229,40); mainSprite.addChild(_border); } private function coverArt():void { _image = new Sprite(); var imageLoader : Loader = new Loader(); _loaderInfo = imageLoader.contentLoaderInfo; _loaderInfo.addEventListener(Event.COMPLETE, coverLoaded) var image:URLRequest = new URLRequest(_tune.coverArt); imageLoader.load(image); _image.x = 1.5; _image.y = 2; _image.addChild(imageLoader); } private function coverLoaded(event:Event):void { _loaderInfo.removeEventListener(Event.COMPLETE, coverLoaded); var scaling : Number = IMAGE_SIZE / _image.width; _image.scaleX = scaling; _image.scaleY = scaling; mainSprite.addChild (_image); placeButton(); } public function hilite(state:Boolean):void{ var col : ColorTransform = new ColorTransform(); if(state){ col.color = 0xFFFFFF; } else { col.color = 0x545454; } _border.transform.colorTransform = col; }

    Read the article

  • Structure of a correctly implemented JTable with TableModel and Listeners?

    - by bamboocha
    I am pretty new to Java and its JTables and this is where I am struggling at the moment. I need to create a GUI which shows me results of a sql query like SELECT * FROM tblPeople WHERE name='Doe'. My idea was to create a a JFrame which displays a JTable with all found records. Besides this, I need to also implement some code to handle when a user is double clicking a record or selecting it by using his arrow keys (additional feature: pressing 12(e.g.) should select the 12th record). What is the best way to structure my program (what classes do I need and especially where do I store my logic)? I came up with structuring it the following way: Main.java ("view") SQLConnection.java PeopleTableModel.java (only stores and returns data given by the passed ResultSet, "model" inherits from DefaultTableModel) PeopleTable.java (stores basically all my logic including KeyListener and MouseListener, "controller", inherits from JTable) Are there better ways to achieve my goals? If so, what are they?

    Read the article

  • Custom JComponent not displaying in Custom JPanel

    - by Trizicus
    I've tried the add() method but nothing is displayed when I try to add Test to GraphicsTest. How should I be adding it? Can someone show me? I've included the code I'm using. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; public class Test extends JComponent { Test() { setOpaque(false); setBackground(Color.white); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("Hello", 50, 50); g2d.dispose(); } } import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; public class GraphicsTest extends JPanel implements MouseListener { private Graphics2D g2d; private String state; private int x, y; GraphicsTest() { add(new Test()); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g; g2d.setColor(Color.BLACK); g2d.drawString("STATE: " + state, 5, 15); g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30); g2d.setColor(Color.red); Rectangle2D r2d = new Rectangle2D.Double(x, y, 10, 10); g2d.draw(r2d); g2d.dispose(); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setX(int x) { this.x = x; repaint(); } public void setY(int y) { this.y = y; repaint(); } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }

    Read the article

  • Please Critique Code (Java, Java2D, javax.swing.Timer)

    - by Trizicus
    Learn by practice right? Please critique and suggest anything! Thanks :) import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } JFrame frame; GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gp.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); gp.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} }); frame.add(gp); } }); } } GraphicsPanel: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { Test t; Timer test; GraphicsPanel() { t = new Test(); setLayout(new BorderLayout()); add(t, BorderLayout.CENTER); test = new Timer(17, new Gameloop(this)); test.start(); } class Gameloop implements ActionListener { GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { t.incX(); gp.repaint(); } catch (Exception ez) { } } } } Test: import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; public class Test extends JComponent { Toolkit tk; Image img; int x, y; Test() { tk = Toolkit.getDefaultToolkit(); img = tk.getImage(getClass().getResource("images.jpg")); this.setPreferredSize(new Dimension(15, 15)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("x: " + x, 350, 50); g2d.drawImage(img, x, 80, null); g2d.dispose(); } public void incX() { x++; } }

    Read the article

  • mouse listener event

    - by user161004
    I have got a program having an array of buttons, each of these button has their mouselistener event. Now, how can i find which of the buton is clicked through the mouse listener.

    Read the article

  • Placing component on Glass Pane

    - by Chris Lieb
    I have a subclass of JLabel that forms a component of my GUI. I have implemented the ability to drag and drop the component from one container to another, but without any visual effects. I want to have this JLabel follow the cursor during the drag of the item from one container to another. I figured that I could just create a glass pane and draw it on there. However, even after I add the component to the glass pane, set the component visible, and set the glass pane visible, and set the glass pane as opaque, I still so not see the component. I know the component works because I can add it to the content pane and have it show up. How do I add a component to the glass pane? package wpics509s10t7.view; import javax.swing.*; import wpics509s10t7.model.Tile; import java.awt.*; import java.awt.dnd.DragSource; import java.awt.event.AWTEventListener; import java.awt.event.MouseEvent; /** * GlassPane tutorial * "A well-behaved GlassPane" * http://weblogs.java.net/blog/alexfromsun/ * <p/> * This is the final version of the GlassPane * it is transparent for MouseEvents, * and respects underneath component's cursors by default, * it is also friedly for other users, * if someone adds a mouseListener to this GlassPane * or set a new cursor it will respect them * * @author Alexander Potochkin */ public class GlassPane extends JPanel implements AWTEventListener { private static final long serialVersionUID = 1L; private final JFrame frame; private TileView tv; // subclass of JLabel private Point point; private WordStealApp wsa; public GlassPane(JFrame frame, WordStealApp wsa) { super(null); this.wsa = wsa; this.frame = frame; setOpaque(true); setLayout(null); setVisible(true); composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); } public void beginDrag(Tile t, Point p) { this.tv = new TileView(t, null, this.wsa, true); this.add(this.tv); System.out.println("Starting point: x=" + p.getX() + ",y=" + p.getY()); this.tv.setLocation((int)p.getX(), (int)p.getY()); this.tv.setVisible(true); } public void endDrag(Point p) { System.out.println("Ending point: x=" + p.getX() + ",y=" + p.getY()); this.remove(this.tv); this.tv.setVisible(false); this.tv = null; } public void eventDispatched(AWTEvent event) { if (event instanceof MouseEvent) { MouseEvent me = (MouseEvent) event; if (!SwingUtilities.isDescendingFrom(me.getComponent(), frame)) { return; } if (me.getID() == MouseEvent.MOUSE_EXITED && me.getComponent() == frame) { if (tv != null) { tv.setVisible(false); } point = null; } else { MouseEvent converted = SwingUtilities.convertMouseEvent(me.getComponent(), me, frame.getGlassPane()); point = converted.getPoint(); } repaint(); } } /** * If someone adds a mouseListener to the GlassPane or set a new cursor * we expect that he knows what he is doing * and return the super.contains(x, y) * otherwise we return false to respect the cursors * for the underneath components */ @Override public boolean contains(int x, int y) { if (getMouseListeners().length == 0 && getMouseMotionListeners().length == 0 && getMouseWheelListeners().length == 0 && getCursor() == Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)) { return false; } return super.contains(x, y); } }

    Read the article

  • ActionScript 3 Cant see Movieclip

    - by user3697993
    When I play my game it does not show my _Player Movieclip, but it does collide with the ground which is very confusing. So I believe the movieclip is there but not showing the texture/Sprite. I think the problem is in "function Spawn" (First Function). public class PewdyBird extends MovieClip { //Player variables public var Up_Speed:int = 25; public var speed:Number = 0; public var _grav:Number = 0.5; public var isJump:Boolean = false; public var Score:int = 0; public var Player_Live:Boolean = true; public var _Player:Player = new Player(); //Other variables //Environment variables var Floor:int = 480; var Clock:Number = 0; var Clock_restart:Number = 0; var Clock_ON:Boolean = false; var Clock_max:int = 15; var Player_Stage:Boolean = true; private var _X:int; private var _Y:int; private var hit_ground:Boolean = false; private var width_BG:int = 479; //SPAWN function Spawn(e:Event){ _Player.x = 200; _Player.y = 200; stage.addChild(_Player); } //Keyboard Input private function KeyboardListener(e:KeyboardEvent){ if(e.keyCode == Keyboard.SPACE){ Clock = Clock_restart; Clock_ON = true; isJump = true; if(isJump){ _Player.gotoAndPlay("Fly"); speed = -Up_Speed; isJump = false; } } } //Mouse Input & Spawn Listener private function MouseListener(m:MouseEvent){ if(MouseEvent.CLICK){ Clock = Clock_restart; Clock_ON = true; isJump = true; if(isJump){ _Player.gotoAndPlay("Fly"); speed = -Up_Speed; isJump = false; } } } //Rotation Fly function Rot_Fly(){ if(Clock < Clock_max){ _Player.rotation = -15; }else if(Clock >= Clock_max){ if(_Player.rotation < 90){ _Player.rotation += 10; }else if(_Player.rotation >= 90){ _Player.rotation = 90; } } } //END //Update Function function enter_frame(e:Event):void{ Rot_Fly(); //Clock if(Clock_ON){ Clock++; }else if(Clock > Clock_max){ Clock = Clock_max; } //Fall Limits if(speed >= 20){ _Player.y += 20; return; _Player.gotoAndPlay("Fall"); } //Physics speed += _grav*3; _Player.y += speed; } //Hit Ground function Hit_Ground(e:Event){ if(_Player.hitTestObject(Ground1)){ _grav = 0; speed = 0; trace("HIT GROUND"); }else if(_Player.hitTestObject(Ground2)){ _grav = 0; speed = 0; trace("HIT GROUND"); }else if(_Player.hitTestObject(Ground1) == false){ _grav = 1; }else if(_Player.hitTestObject(Ground2) == false){ _grav = 1; } } //Background Slide (Left) private function Background_Move(e:Event):void{ Background1.x -= 1.5; Background2.x -= 1.5; Ground1.x -= 4; Ground2.x -= 4; if(Background1.x < -width_BG){ Background1.x = width_BG; } else if(Background2.x < -width_BG){ Background2.x = width_BG; } else if(Ground1.x < -width_BG){ Ground1.x = width_BG; } else if(Ground2.x < -width_BG){ Ground2.x = width_BG; } } } The eventListeners are in flash it self stage.addEventListener(Event.ENTER_FRAME, enter_frame); stage.addEventListener(Event.ENTER_FRAME, Hit_Ground); stage.addEventListener(KeyboardEvent.KEY_UP, KeyboardListener); stage.addEventListener(MouseEvent.CLICK, MouseListener); stage.addEventListener(Event.ENTER_FRAME, Background_Move); stage.addEventListener(Event.ADDED_TO_STAGE, Spawn);

    Read the article

1 2 3  | Next Page >