Search Results

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

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

  • Proper method to update and draw from game loop?

    - by Lost_Soul
    Recently I've took up the challenge for myself to create a basic 2d side scrolling monster truck game for my little brother. Which seems easy enough in theory. After working with XNA it seems strange jumping into Java (which is what I plan to program it in). Inside my game class I created a private class called GameLoop that extends from Runnable, then in the overridden run() method I made a while loop that handles time and such and I implemented a targetFPS for drawing as well. The loop looks like this: @Override public void run() { long fpsTime = 0; gameStart = System.currentTimeMillis(); lastTime = System.currentTimeMillis(); while(game.isGameRunning()) { currentTime = System.currentTimeMillis(); long ellapsedTime = currentTime - lastTime; if(mouseState.leftIsDown) { que.add(new Dot(mouseState.getPosition())); } entities.addAll(que); game.updateGame(ellapsedTime); fpsTime += ellapsedTime; if(fpsTime >= (1000 / targetedFPS)) { game.drawGame(ellapsedTime); } lastTime = currentTime; } The problem I've ran into is adding of entities after a click. I made a class that has another private class that extends MouseListener and MouseMotionListener then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great but when I add the entity it throws a CME (Concurrent Modification Exception) sometimes. I have all the entities stored in a LinkedList so later I tried adding a que linkedlist where I later add the que to the normal list in the update loop. I think this would work fine if it was just the update method in the gameloop but with the repaint() method (called inside game.drawGame() method) it throws the CME. The only other thing is that I'm currently drawing directly from the overridden paintComponent() method in a custom class that extends JPanel. Maybe there is a better way to go about this? As well as fix my CME? Thanks in advance!!!

    Read the article

  • Context Sensitive JTable (Part 2)

    - by Geertjan
    Now, having completed part 1, let's add a popup menu to the JTable. However, the menu item in the popup menu should invoke the same Action as invoked from the toolbar button created yesterday. Add this to the constructor created yesterday: Collection<? extends Action> stockActions =         Lookups.forPath("Actions/Stock").lookupAll(Action.class); for (Action action : stockActions) {     popupMenu.add(new JMenuItem(action)); } MouseListener popupListener = new PopupListener(); // Add the listener to the JTable: table.addMouseListener(popupListener); // Add the listener specifically to the header: table.getTableHeader().addMouseListener(popupListener); And here's the standard popup enablement code: private JPopupMenu popupMenu = new JPopupMenu(); class PopupListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { showPopup(e); } @Override public void mouseReleased(MouseEvent e) { showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }

    Read the article

  • Java MVC - How to divide a done text game into MVC?

    - by Zopyrus
    Been sitting here for hours now trying to figure this out, so a bit sympathy for this large question. :) The Goal: I simply want to divide my done code into MVC (Model View Controller) parts. I have the game logics done and text based - the code works fine. The Problem: Well, I want to implement this code into MVC, but where do explain for the MODEL that it should use text-based? Because the VIEW is only for the layout (graphically) correct? I am having a REALLY hard time figuring out where to begin at all. Any pointers would be so nice! Here is my game logics code: import mind.*; import javax.swing.*; import java.util.*; import java.lang.*; import java.awt.*; public class Drive { String[] mellan; boolean gameEnd, checkempty, checkempty2, enemy, enemy2; String gr,rd,tom; int digits; public Drive() { // Gamepieces in textform gr="G"; rd="R"; tom=" "; mellan = new String[7]; String[] begin = {gr,gr,gr,tom,rd,rd,rd}; String[] end = {rd,rd,rd,tom,gr,gr,gr}; //input Scanner in = new Scanner(System.in); mellan=begin; gameEnd=false; while (gameEnd == false) { for(int i=0; i<mellan.length; i++) { System.out.print(mellan[i]); } System.out.print(" Choose 0-6: "); digits = in.nextInt(); move(); checkWin(); } } void move() { //BOOLEAN for gameruls!!! checkempty = digits<6 && mellan[digits+1]==tom; checkempty2 = digits>0 && mellan[digits-1]==tom; enemy = (mellan[digits]==gr && mellan[digits+1]==rd && mellan[digits+2]==tom); enemy2 = (mellan[digits]==rd && mellan[digits-1]==gr && mellan[digits-2]==tom); if(checkempty) { mellan[digits+1]=mellan[digits]; mellan[digits]=tom; } else if (checkempty2) { mellan[digits-1]=mellan[digits]; mellan[digits]=tom; } else if (enemy) { mellan[digits+2]=mellan[digits]; mellan[digits]=tom; } else if (enemy2) { mellan[digits-2]=mellan[digits]; mellan[digits]=tom; } } void checkWin() { String[] end = {rd,rd,rd,tom,gr,gr,gr}; for (int i=0; i<mellan.length; i++){ } if (Arrays.equals(mellan,end)) { for (int j=0; j<mellan.length; j++) { System.out.print(mellan[j]); } displayWin(); } } void displayWin() { gameEnd = true; System.out.println("\nNicely Done!"); return; } // Kör Drive! public static void main(String args[]) { new Drive(); } } Here is how I defined my DriveView thus far: (just trying to make one button to work) import mind.*; import javax.swing.*; import java.util.*; import java.lang.*; import java.awt.*; import java.awt.event.*; public class DriveView extends JFrame { JButton ruta1 = new JButton("Green"); JButton ruta2 = new JButton("Green"); JButton rutatom = new JButton(""); JButton ruta6 = new JButton("Red"); private DriveModel m_model; public DriveView(DriveModel model) { m_model = model; //Layout for View JPanel myPanel = new JPanel(); myPanel.setLayout(new FlowLayout()); myPanel.add(ruta1); myPanel.add(ruta2); myPanel.add(rutatom); myPanel.add(ruta6); this.setContentPane(myPanel); this.pack(); this.setTitle("Drive"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void addMouseListener(ActionListener mol) { ruta2.addActionListener(mol); } } And DriveController which gives me error at compile import mind.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.lang.*; public class DriveController { private DriveModel m_model; private DriveView m_view; public DriveController(DriveModel model, DriveView view) { m_model = model; m_view = view; view.addMouseListener(new MouseListener()); } class MouseListener implements ActionListener { public void actionPerformed(ActionEvent e) { String mening; mening = e.getActionCommand(); if (mening.equals("Green")) { setForeground(Color.red); } } } }

    Read the article

  • JPanel Layout Image Cutoff

    - by Trizicus
    I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either. So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code. Custom JPanel: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel implements MouseListener { private Entity test; private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; GraphicsPanel() { test = new Entity("test.png"); Thread t1 = new Thread(test); t1.start(); Entity ent2 = new Entity("images.jpg"); ent2.setX(150); ent2.setY(150); Thread t2 = new Thread(ent2); t2.start(); Entity ent3 = new Entity("test.png"); ent3.setX(0); ent3.setY(150); Thread t3 = new Thread(ent3); t3.start(); //ESSENTIAL setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(test); add(ent2); add(ent3); //GAMELOOP timer = new Timer(30, new Gameloop(this)); timer.start(); addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } 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) { } class Gameloop implements ActionListener { private GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { gp.getFPS(); gp.repaint(); } catch (Exception ez) { } } } } Main class: import java.awt.EventQueue; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } private JFrame frame; private 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); frame.add(gp); } }); } } Custom JComponent import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JComponent; public class Entity extends JComponent implements Runnable { private BufferedImage bImg; private int x = 0; private int y = 0; private int entityWidth, entityHeight; private String filename; Entity(String filename) { this.filename = filename; } public void run() { bImg = loadBImage(filename); entityWidth = bImg.getWidth(); entityHeight = bImg.getHeight(); setPreferredSize(new Dimension(entityWidth, entityHeight)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(bImg, x, y, null); g2d.dispose(); } public BufferedImage loadBImage(String filename) { try { bImg = ImageIO.read(getClass().getResource(filename)); } catch (Exception e) { } return bImg; } public int getEntityWidth() { return entityWidth; } public int getEntityHeight() { return entityHeight; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }

    Read the article

  • Java MouseEvents not working

    - by billynomates
    This may be a stupid question, but I have to ask! I have the following code snippets that are supposed to run their corresponding methods when the user interacts with objects. For some reason, "foo" is never printed, but "bar" is. myJSpinner1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt() { System.out.println("foo"); //"foo" is not printed } }); myJSpinner2.addChangeListener(new java.awt.event.ChangeListener() { public void stateChanged(java.awt.event.ChangeEvent evt() { System.out.println("bar"); //"bar" is printed } }); I get no exceptions or stack trace. What am I missing in the MouseListener one? Thanks in advance.

    Read the article

  • problems with overloaded function members C++

    - by Dr Deo
    I have declared a class as class DCFrameListener : public FrameListener, public OIS::MouseListener, public OIS::KeyListener { bool keyPressed(const OIS::KeyEvent & kEvt); bool keyReleased(const OIS::KeyEvent &kEvt); //*******some code missing************************ }; But if i try defining the members like this bool DCFrameListener::keyPressed(const OIS::KeyEvent kEvt) { return true; } The compiler refuses with this error error C2511: 'bool DCFrameListener::keyPressed(const OIS::KeyEvent)' : overloaded member function not found in 'DCFrameListener' see declaration of 'DCFrameListener' Why is this happening, yet i declared the member keyPressed(const OIS::KeyEvent) in my function declaration. any help will be appreciated. Thanks

    Read the article

  • JButtons re-enable themselves after being disabled

    - by Anarchist
    I have an array of JButtons which form a keypad interface. After six numbers are entered I want to disable the keypad so that no further numbers can be entered by the user. I have written the code and the buttons do disable until the mouse hovers above any of them, then the buttons seem to re-enable themselves and run actionEvents added to them. The full code is available here. Possible things that I think are wrong. There is some sort of MouseListener which is ignoring when I set button.setEnabled(false); I haven't separated attributes from the buildGUI(); correctly, I only did this anyway so that the inner class could access them. Possibly something to do with the gridLayout as disabling the buttons seems to work for my services JPanel buttons.

    Read the article

  • How to change the jtooltip timers for 1 component.

    - by i30817
    I have a component where i want to display a custom jtooltip. That is easy, just change the getTooltip method. Similar for location and text. However i also want to change the timers. The tooltip should always be displayed if the mouse is over a cellrenderer of the component. If it leaves all of those it should be turned invisible. I know that i can use TooltipManager to control the times globally. But the best solution is probably to just shortcircut that and display the tooltip myself with a mouselistener. However when i tried to do that (unregister the component in TooltipManager and setting the tooltip visible, with text and in the correct position, in a mouse listener) the tooltip never showed at all. What am i doing wrong?

    Read the article

  • Is it Possible to show a previously hidden JFrame using a keylistener

    - by JIM
    here is my code, i basically just did a tester for the most common listeners, which i might later use in future projects, the main problem is in the keylistener at the bottom, i am trying to re-show the frame but i think it just cant be done that way, please help ps: no idea why the imports dont show up right. package newpackage; import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JSeparator; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class NewClass1 extends JFrame { private JLabel item1,infomouse,infoclicks,infoKeys,writehere; private JButton button1,button2,button3; private JTextArea text1,status,KeyStatus; private JTextField text2,text3,mouse,clicks,test; private JSeparator sep1; private int clicknumber; public NewClass1() { super("Listener Tests"); setLayout(null); sep1 = new JSeparator(); button1 = new JButton("Button1"); button2 = new JButton("Button2"); button3 = new JButton("Button3"); item1 = new JLabel("Button Status :"); infomouse = new JLabel("Mouse Status :"); infoclicks = new JLabel("Nº of clicks :"); infoKeys = new JLabel("Keyboard status:"); writehere = new JLabel("Write here: "); text1 = new JTextArea(); text2 = new JTextField(20); text3 = new JTextField(20); status = new JTextArea(); mouse = new JTextField(20); clicks = new JTextField(4); KeyStatus = new JTextArea(); test = new JTextField(3); clicks.setText(String.valueOf(clicknumber)); text1.setEditable(true); text2.setEditable(false); text3.setEditable(false); status.setEditable(false); mouse.setEditable(false); clicks.setEditable(false); KeyStatus.setEditable(false); text1.setBounds(135, 310, 150, 20); text2.setBounds(135, 330, 150, 20); text3.setBounds(135, 350, 150, 20); status.setBounds(15, 20, 240, 20); infomouse.setBounds(5,45,120,20); infoKeys.setBounds(5,90,120,20); KeyStatus.setBounds(15,115,240,85); test.setBounds(15,225,240,20); mouse.setBounds(15,70,100,20); infoclicks.setBounds(195, 45, 140, 20); clicks.setBounds(195, 70, 60, 20); item1.setBounds(5, 0, 120, 20); button1.setBounds(10, 310, 115, 20); button2.setBounds(10, 330, 115, 20); button3.setBounds(10, 350, 115, 20); sep1.setBounds(5, 305, 285, 10); sep1.setBackground(Color.BLACK); status.setBackground(Color.LIGHT_GRAY); button1.addActionListener(new button1list()); button2.addActionListener(new button1list()); button3.addActionListener(new button1list()); button1.addMouseListener(new MouseList()); button2.addMouseListener(new MouseList()); button3.addMouseListener(new MouseList()); getContentPane().addMouseListener(new MouseList()); test.addKeyListener(new KeyList()); this.addKeyListener(new KeyList()); test.requestFocus(); add(item1); add(button1); add(button2); add(button3); add(text1); add(text2); add(text3); add(status); add(infomouse); add(mouse); add(infoclicks); add(clicks); add(infoKeys); add(KeyStatus); add(test); add(sep1); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (Exception e){System.out.println("Error");} SwingUtilities.updateComponentTreeUI(this); setSize(300, 400); setResizable(false); setVisible(true); test.setFocusable(true); test.setFocusTraversalKeysEnabled(false); setLocationRelativeTo(null); } public class button1list implements ActionListener { public void actionPerformed(ActionEvent e) { String buttonpressed = e.getActionCommand(); if (buttonpressed.equals("Button1")) { text1.setText("just"); } else if (buttonpressed.equals("Button2")) { text2.setText(text2.getText()+"testing "); } else if (buttonpressed.equals("Button3")) { text3.setText("this"); } } } public class MouseList implements MouseListener{ public void mouseEntered(MouseEvent e){ if(e.getSource()==button1){ status.setText("button 1 hovered"); } else if(e.getSource()==button2){ status.setText("button 2 hovered"); } else if(e.getSource()==button3){ status.setText("button 3 hovered"); } } public void mouseExited(MouseEvent e){ status.setText(""); } public void mouseReleased(MouseEvent e){ if(!status.getText().equals("")){ status.replaceRange("", 0, 22); } } public void mousePressed(MouseEvent e){ if(e.getSource()==button1){ status.setText("button 1 being pressed"); } else if(e.getSource()==button2){ status.setText("button 2 being pressed"); } else if(e.getSource()==button3){ status.setText("button 3 being pressed"); } } public void mouseClicked(MouseEvent e){ clicknumber++; mouse.setText("mouse working"); clicks.setText(String.valueOf(clicknumber)); } } public class KeyList implements KeyListener{ public void keyReleased(KeyEvent e){} public void keyPressed(KeyEvent e){ KeyStatus.setText(""); test.setText(""); String full = e.paramString(); String [] temp = null; temp = full.split(","); for(int i=0; i<7 ;i++){ KeyStatus.append(temp[i] + "\n"); } if(e.getKeyChar()=='h'){setVisible(false); test.requestFocus(); } if(e.getKeyChar()=='s'){setVisible(true);} } public void keyTyped(KeyEvent e){} } }

    Read the article

  • Compiling a DLL which includes Ogre3D gives an assertion error when used

    - by samaursa
    Hi, I have a framework that I am building and is being compiled into a static library to be used by other projects. The library works perfectly without issues. The problem is that the link time is very long for the projects that use the library so I thought I will make a DLL project of the same framework. I started with baby steps and created an MFC DLL project through visual studio. The project has the following header: /// -------------------------------------------- #ifndef OGRECORE_H #define OGRECORE_H #ifdef OGREFW_EXPORT #define OGREFW_DLL __declspec(dllexport) #else #define OGREFW_DLL __declspec(dllimport) #endif class OgreRoot; namespace OgreFW { class OGREFW_DLL OgreCore// : public OIS::KeyListener, public OIS::MouseListener { public: OgreCore(); ~OgreCore(); }; }; #endif // OGRECORE_H and this is the source #include "stdafx.h" #include "OgreCore.h" //#include "Ogre.h" //#include "OgreRoot.h" //#include "OgreRenderWindow.h" //#include "OgreLog.h" //#include "OgreLogManager.h" //#include "OgreOverlay.h" //#include "OgreViewport.h" //#include "OgreRenderWindow.h" //#include "OgreFrameListener.h" //#include "OgreWindowEventUtilities.h" //#include "OgreSceneNode.h" //#include "OgreEntity.h" //#include "OgreManualObject.h" //#include "OgreMeshManager.h" //#include "OgreConfigFile.h" //#include "OgreOverlayContainer.h" //#include "OgreOverlayManager.h" namespace OgreFW { OGREFW_DLL OgreCore::OgreCore() { } // ------------------------ OGREFW_DLL OgreCore::~OgreCore() { } } As you can see I have commented out Ogre includes. When a project uses the compiled DLL and constructs this (OgreCore) class, it works perfectly fine. As soon as uncomment one of the Ogre includes and compile the DLL again, the project that uses the DLL now gives an assertion error. The full details can be found here in the Ogre forum post. I posted the question there first but since its not really an Ogre specific question I thought I will try here as well. The link to the Ogre post is: http://www.ogre3d.org/forums/viewtopic.php?f=2&t=58403 Thank you in advance

    Read the article

  • vlcj not displaying the video

    - by Cássio Eudardo
    I'm using vlcj to play video, but the video doesn't display on some computers(i tested in 4 and worked on 2, all windows), on 1 it displays the button but not the video and on the other it just display a gray background without the button. I tested .wmv and .avi files. I'm using the following code: public class Video extends JFrame implements WindowListener{ private JPanel contentPane; private JButton btnClose; private Dimension size; private float aspectRatio; private EmbeddedMediaPlayer mediaPlayer; public Video() { try { size = Toolkit.getDefaultToolkit().getScreenSize(); aspectRatio = (float)size.width/size.height; String file = "..."; btnClose = new JButton("X"); btnClose.addActionListener(new ActionListener() {...}); btnClose.setBounds(640 - 50, 10, 40, 40); setBounds(size.width/2 - 320, (int)(size.height - 40*aspectRatio) - 250, 640, 200); contentPane = new JPanel(); contentPane.setLayout(null); setContentPane(contentPane); WindowsCanvas surface = new WindowsCanvas(); contentPane.setBounds(0, 0, 640, 200); surface.setBounds(0, 0, 640, 200); MediaPlayerFactory factory = new MediaPlayerFactory(new String("--no-video-title-show")); mediaPlayer = factory.newEmbeddedMediaPlayer(); surface.addMouseListener(new MouseListener() {...}); contentPane.add(btnClose); contentPane.add(surface); setVisible(true); mediaPlayer.setVideoSurface(factory.newVideoSurface(surface)); mediaPlayer.setRepeat(true); mediaPlayer.playMedia(file); } catch(Exception e) { } }}

    Read the article

  • JPanel not listening to key event when there is a child component with JButton on it

    - by Yifu
    I'm working on a map editor for my college project. And I had a problem that the map panel is not listening key event while it should. This happens when I add a ToolBarPane (which extends JPanel) with JComponent such as JButton, JComboBox that implements ActionListener on it AND the map panel (which extends the JPanel) together on to the Frame (I used BorderLayout). I have System.out.println statement to test if the key press is received, and it's not printing, if I remove the ToolBar, the key listener works again, so is the mouseListenner is disabled just like the keyListener, which means I can't handle press events etc, but the mouseListener works fine and I can still handle mouse move event. Here is a screen shot how it works without the ToolBarPane http://img684.imageshack.us/img684/3232/sampleku.png note that you can use the mouse to put images on the map, you can also select images using the mouse just like a laser tool, and by pressing number key you can switch between different images, this works fine until I add the ToolBarPane which shows like this: img291.imageshack.us/img291/8020/failve.png (please add http before that, i can only post one hyperlink) (I can't post images here cuz im a new user) With the ToolBarPane on I was no longer able to handle the key event. I guess it might by that the focus as been transfered to that panel somehow, but not sure at all. Does and body know this and can help me out? Thanks very much

    Read the article

  • Multiple Exception Handling in one if statement [closed]

    - by JA3N
    I am having trouble with throwing and catching exceptions. Here is the code for assignSeat(), assignSeat is called in a try block in another class. void assignSeat(String passengerName, int x, int y) throws SeatOccupiedException, InvalidPassengerNameException { Seat tSeat = airplane.getSeat(x,y); if (tSeat!=null) { if (passengerName.isEmpty() || !passengerName.matches("[a-zA-Z]+")) { throw new InvalidPassengerNameException(); } //excluded else if else if (foundPassenger(passengerName)) { airplane.seatList.get(airplane.seatNumber(passengerName)).unOccupy(); tSeat.occupy(); for (int i = 0; i<passengers.size();i++) if (passengers.get(i).getName().equals(passengerName)) passengers.get(i).changeSeat(tSeat.getSeatName()); } else if (!tSeat.occupied) { tSeat.occupy(); addPassenger(passengerName, tSeat.getSeatName()); } else if (tSeat.occupied) { throw new SeatOccupiedException(); } } and here is the code that calls assignSeat() and is in another class (I won't copy the whole class to make it look clearer) if (afComp.currentAF != null) { try { afComp.currentAF.assignSeat(nameField.getText(), x, y); //<-Problem here, "Unhandled exception type SeatOccupiedException" } catch (SeatOccupiedException exception) //<-Problem here, "Unreachable catch block, This exception is never thrown from the try statement body" { } catch(InvalidPassengerNameException exception) //<-No problems. { } } Whats wrong with the try block? why won't it throw the SeatOccupiedException? Exception classes: SeatOccupied: package a2; public class SeatOccupiedException extends Exception { public SeatOccupiedException(){} } InvalidPassengerName: package a2; public class InvalidPassengerNameException extends Exception { public InvalidPassengerNameException() {} } Every class I have is in package a2 imports for class that calls assignSeat package a2; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.event.*; imports for class that has assignSeat package a2; import java.util.ArrayList;

    Read the article

  • Circle to move when mouse clicked Java

    - by Myt
    So I am really new to Java and I need a circle to move around JFrame when it's clicked, but the circle has to get random cordinates. So far this code generates a new circle every time it's clicked, but all the other circles stay there aswell, but I only need one circle to move around the frame. So maybe someone can help me a little :) public class test2 extends JFrame implements MouseListener { int height, width; public test2() { this.setTitle("Click"); this.setSize(400,400); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); addMouseListener(this); width = getSize().width; height = getSize().height; } public void paint (Graphics g) { setBackground (Color.red); g.setColor(Color.yellow); int a, b; a = -50 + (int)(Math.random()*(width+40)); b = (int)(Math.random()*(height+20)); g.fillOval(a, b, 130, 110); } public void mouseClicked(MouseEvent e) { int a, b; a = -50 + (int)(Math.random()*(width+40)); b = (int)(Math.random()*(height+20)); repaint(); } public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mousePressed(MouseEvent e){} public static void main(String arg[]){ new test2(); } }

    Read the article

  • creating a pre-menu level select screen

    - by Ephiras
    Hi I am working on creating a tower Defence java applet game and have come to a road block about implementing a title screen that i can select the level and difficulty of the rest of the game. my title screen class is called Menu. from this menu class i need to pass in many different variables into my Main class. i have used different classes before and know how to run them and such. but if both classes extend applet and each has its individual graphics method how can i run things from Main even though it was created in Menu. what i essentially want to do is run the Menu class withits action listeners and graphics until a Difficulty button has been selected, run the main class (which 100% works without having to have the Menu class) and pretty much terminate Menu so that i cannot go back to it, do not see its buttons or graphics menus. can i run one applet annd when i choose a button close that one and launch the other one? IF you would like to download the full project you can find it here, i had to comment out all the code that wasn't working my Menu class import java.awt.*; import java.awt.event.*; import java.applet.*; public class Menu extends Applet implements ActionListener{ Button bEasy,bMed,bHard; Main m; public void init(){ bEasy= new Button("Easy"); bEasy.setBounds(140,200,100,50); add(bEasy); bMed = new Button("Medium");bMed.setBounds(280,200,100,50); add(bMed); bHard= new Button("Hard");bHard.setBounds(420,200,100,50); add(bHard); setLayout(null); } public void actionPerformed(ActionEvent e){ Main m = new Main(20,10,3000,mapMed);//break; switch (e.getSource()){ case bEasy: Main m = new Main(6000,20,"levels/levelEasy.png");break;//enimies tower money world case bMed: Main m = new Main(4000,15,"levels/levelMed.png");break; case bHard: Main m = new Main(2000,10,"levels/levelEasy.png");break; default: break; } } public void paint(){ //m.draw(g) } } and here is my main class initialising code. import java.awt.*; import java.awt.event.*; import java.applet.*; import java.io.IOException; public class Main extends Applet implements Runnable, MouseListener, MouseMotionListener, ActionListener{ Button startButton, UpgRange, UpgDamage; //set up the buttons Color roadCol,startCol,finCol,selGrass,selRoad; //set up the colors Enemy e[][]; Tower t[]; Image towerpic,backpic,roadpic,levelPic; private Image i; private Graphics doubleG; //here is the world 0=grass 1=road 2=start 3=end int world[][],eStartX,eStartY; boolean drawMouse,gameEnd; static boolean start=false; static int gridLength=15; static int round=0; int Mx,My,timer=1500; static int sqrSize=31; int towers=0,towerSelected=-10; static int castleHealth=2000; String levelPath; //choose the level Easy Med or Hard int maxEnemy[] = {5,7,12,20,30,15,50,30,40,60};//number of enimies per round int maxTowers=15;//maximum number of towers allowed static int money =2000,damPrice=600,ranPrice=350,towerPrice=700; //money = the intial ammount of money you start of with //damPrice is the price to increase the damage of a tower //ranPrice is the price to increase the range of a tower public void main(int cH,int mT,int mo,int dP,int rP,int tP,String path,int[] mE)//constructor 1 castleHealth=cH; maxTowers=mT; money=mo; damPrice=dP; ranPrice=rP; towerPrice=tP; String levelPath=path; maxEnemy = mE; buildLevel(); } public void main(int cH,int mT,String path)//basic constructor castleHealth=cH; maxTowers=mT; String levelPath=path; maxEnemy = mE; buildLevel(); } public void init(){ setSize(sqrSize*15+200,sqrSize*15);//set the size of the screen roadCol = new Color(255,216,0);//set the colors for the different objects startCol = new Color(0,38,255); finCol = new Color(255,0,0); selRoad = new Color(242,204,155);//selColor is the color of something when your mouse hovers over it selGrass = new Color(0,190,0); roadpic = getImage(getDocumentBase(),"images/road.jpg"); towerpic = getImage(getDocumentBase(),"images/tower.png"); backpic = getImage(getDocumentBase(),"images/grass.jpg"); levelPic = getImage(getDocumentBase(),"images/level.jpg"); e= new Enemy[maxEnemy.length][];//activates all of the enimies for (int r=0;r<e.length;r++) e[r] = new Enemy[maxEnemy[r]]; t= new Tower[maxTowers]; for (int i=0;i<t.length;i++) t[i]= new Tower();//activates all the towers for (int i=0;i<e.length; i++)//sets all of the enimies starting co ordinates for (int j=0;j<e[i].length;j++) e[i][j] = new Enemy(eStartX,eStartY,world); initButtons();//initialise all the buttons addMouseMotionListener(this); addMouseListener(this); }

    Read the article

  • Why keylistener is not working here?

    - by swift
    i have implemented keylistener interface and implemented all the needed methods but when i press the key nothing happens here, why? package swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JTextArea; class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { static BufferedImage image; String shape; Color color=Color.black; Point start; Point end; Point mp; Button elipse=new Button("elipse"); int x[]=new int[50]; int y[]=new int[50]; Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[9]; String selected; Point label; String key; int ex,ey;//eraser //DatagramSocket dataSocket; JButton button = new JButton("test"); JLayeredPane layerpane; Point p=new Point(); int w,h; public Paper() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(640, 480); frame.setBackground(Color.black); layerpane=frame.getLayeredPane(); setWidth(539,444); setBounds(69,0,555,444); layerpane.add(this,new Integer(2)); layerpane.add(this.addButtons(),new Integer(0)); setLayout(null); setOpaque(false); addMouseListener(this); addMouseMotionListener(this); setFocusable(true); addKeyListener(this); System.out.println(isFocusable()); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) g2.drawPolygon(x,y,2); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) g2.drawPolygon(x,y,2); } if(label!=null) { JTextArea textarea=new JTextArea(); if(selected==("text")) { textarea.setBounds(label.x, label.y, 50, 50); textarea.setMaximumSize(new Dimension(100,100)); textarea.setBackground(new Color(237,237,237)); add(textarea); g2.drawString("key",label.x,label.y); } } start=null; repaint(); g2.dispose(); } public void text() { System.out.println(label); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x, start.y, 10, 10); } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setMaximumSize(new Dimension(70,70)); JPanel shape=new JPanel(); JPanel colourbox=new JPanel(); shape.setLayout(new GridLayout(4,2)); shape.setMaximumSize(new Dimension(70,140)); colourbox.setLayout(new GridLayout(3,3)); colourbox.setMaximumSize(new Dimension(70,70)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round rect"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); shape.add(elipse); shape.add(rectangle); shape.add(line); shape.add(erase); shape.add(roundrect); shape.add(polygon); shape.add(text); buttonpanel.add(shape); for(int i=0;i<9;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); colourbutton[i].addActionListener(this); } buttonpanel.add(colourbox); buttonpanel.setBounds(0, 0, 70, 210); return buttonpanel; } public void mouseClicked(MouseEvent e) { if(selected=="text") { label=new Point(); label=e.getPoint(); draw(); } } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase"||selected=="text") { start=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { mp = e.getPoint(); } else if(selected=="poly") { x[0]=e.getX(); y[0]=e.getY(); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } draw(); } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); } else if(selected=="erase") { start=e.getPoint(); erase(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } repaint(); } public void mouseMoved(MouseEvent arg0) {} public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) selected="poly"; else if(e.getSource()==text) selected="text"; if(e.getSource()==colourbutton[0]) color=Color.black; else if(e.getSource()==colourbutton[1]) color=Color.white; else if(e.getSource()==colourbutton[2]) color=Color.red; else if(e.getSource()==colourbutton[3]) color=Color.orange; else if(e.getSource()==colourbutton[4]) color=Color.blue; else if(e.getSource()==colourbutton[5]) color=Color.green; else if(e.getSource()==colourbutton[6]) color=Color.pink; else if(e.getSource()==colourbutton[7]) color=Color.magenta; else if(e.getSource()==colourbutton[8]) color=Color.cyan; } @Override public void keyPressed(KeyEvent e) { System.out.println("pressed"); } @Override public void keyReleased(KeyEvent e) { System.out.println("key released"); } @Override public void keyTyped(KeyEvent e) { System.out.println("Typed"); } public static void main(String[] a) { new Paper(); } } class Button extends JButton { String name; public Button(String name) { this.name=name; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",5, 22); } }

    Read the article

  • Right-click context menu for Java JTree?

    - by arcanex
    I'm trying to implement pop-up menus in Java JTree. I've sub-classed DefaultTreeCellRenderer (to change node appearance) and DefaultTreeCellEditor (to create Components to attach event listeners to, since apparently the Components that DefaultTreeCellRenderer.getTreeCellRendererComponent() returns can't do it?). I don't really want to "edit" the nodes, just be able to pop-up a menu when a node gets right-clicked, but this is the only way I can think of doing it right now... Below is the code that I have so far-- I'm just trying to figure out how to capture MouseEvents. It sort of works, but badly. What's a better way to accomplish what I'm trying to do here? private class My_TreeCellRenderer extends DefaultTreeCellRenderer { My_TreeCellRenderer() { super (); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // set label text and tool tips setText(((My_Object)value).getTreeLabel()); setToolTipText(((My_Object)value).getTreeToolTip()); return this; } } private class My_TreeCellEditor extends DefaultTreeCellEditor { private MouseAdapter ma; My_TreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { super (tree, renderer); ma = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { System.out.println("My Popup"); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { System.out.println("My Popup"); } } }; } public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { String src_filename = null; // return non-editing component Component c = renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, true); // add mouse listener if it's not listening already MouseListener mouseListeners[] = c.getMouseListeners(); int i; for (i=0; i < mouseListeners.length && mouseListeners[i] != ma; i++); if (i >= mouseListeners.length) c.addMouseListener(ma); return c; } protected boolean canEditImmediately(EventObject event) { if (event instanceof MouseEvent && ((MouseEvent)event).getClickCount() == 1) return true; else return false; } }

    Read the article

  • 2d java Graphics

    - by LukeG
    I am new to java 2d graphics and I have problem handling mouseclick event. Is it possible for you to tell me why there is nothing going on after updating mouse status to clicked ? What I want to do is to change the image in array at 0 2 to another image. Nothing happens tho. Thanks for your help in advance. import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.*; import java.awt.*; import javax.swing.ImageIcon; import javax.swing.*; public class Board extends JPanel implements MouseListener { private static boolean[] keyboardState = new boolean[525]; private static boolean[] mouseState = new boolean[3]; private static Image[][] images; Image house; int w = 0; int h = 0; int xPos; int yPos; ImageIcon ii = new ImageIcon(this.getClass().getResource("house.gif")); ImageIcon iii = new ImageIcon(this.getClass().getResource("house1.gif")); public Board() { house = ii.getImage(); h = house.getHeight(null); w = house.getWidth(null); images = new Image[10][10]; for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { images[i][j] = house; } } } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { g2d.drawImage(images[i][j],w*i,h*j,null); } } //g2d.drawImage(house,15,15,null); } public void checkMouse() { if(mouseState[0]) { images[0][2] = iii.getImage(); repaint(); super.repaint(); } } @Override public void mousePressed(MouseEvent e) { mouseKeyStatus(e, true); checkMouse(); } @Override public void mouseReleased(MouseEvent e) { mouseKeyStatus(e, false); repaint(); } public static boolean mouseButtonState(int button) { return mouseState[button - 1]; } private void mouseKeyStatus(MouseEvent e, boolean status) { if(e.getButton() == MouseEvent.BUTTON1) mouseState[0] = status; else if(e.getButton() == MouseEvent.BUTTON2) mouseState[1] = status; else if(e.getButton() == MouseEvent.BUTTON3) mouseState[2] = status; }

    Read the article

  • Why cant i draw an elipse in with code?

    - by bvivek88
    package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import javax.swing.*; public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; Color color; Point start=new Point(); Point end =new Point(); JButton elipse=new JButton("Elipse"); JButton rectangle=new JButton("Rectangle"); JButton line=new JButton("Line"); String selected; public test_bmp() { color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { //super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } if(selected=="line") g2.drawLine(start.x,start.y,end.x,end.y); } //Draw on Buffered image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); System.out.println("draw"); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } repaint(); g2.dispose(); } public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setBackground(color.lightGray); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener(this); buttonpanel.add(elipse); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(rectangle); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(line); return buttonpanel; } public static void main(String args[]) { test_bmp application=new test_bmp(); //Main window JFrame frame=new JFrame("Whiteboard"); frame.setLayout(new BorderLayout()); frame.add(application.addButtons(),BorderLayout.WEST); frame.add(application); //size of the window frame.setSize(600,400); frame.setLocation(0,0); frame.setVisible(true); int w = frame.getWidth(); int h = frame.getHeight(); image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @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 event) { start = event.getPoint(); } @Override public void mouseReleased(MouseEvent event) { end = event.getPoint(); draw(); } @Override public void mouseDragged(MouseEvent e) { end=e.getPoint(); repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; draw(); } } I need to create a paint application, when i draw elipse by dragging mouse from left to right it displays nothing, why?? should i use any other function here?

    Read the article

  • JTabbedPane: only first tab is drawn, the second is always empty (newbie Q)

    - by paul
    I created a very simple JTabbedPane by first creating an empty JTabbedPane object, then 2 JPanels that I later add. Each JPanel is holding a object that extends JButton and implements MouseListener. Each of these holds a different image loaded from a file; the image is held locally as a buffered image and as an image icon, etc., all of which works great. The point of all that is to allow resizing of the image when the button is resized (using getscaledinstance()), because the panel is resized, because the JTabbedPane is resized, etc., within the JFrame that holds everything. I override paintComponent() to accomplish this in the class that extends JButton. I am using MigLayout Manager, and all is well on that front controlling layout constraints, growing, filling, initial sizes, preferred sizes, etc. The images the buttons hold are of different sizes and proportions, but this caused no trouble before. Up until 2 days ago everything worked fairly well. I made some changes trying to tweak some resizing issues as I was picking up MigLayout manager. At the time I was playing around with setting various min, max, and preferred sizes using the methods provided for by the components, not the layout manager. I also fooled a bit with pack(), validate(), visible(), opaque() etc., and yes I read the article about Swing and AWT painting here: http://java.sun.com/products/jfc/tsc/articles/painting/ , and I switched to relying more and more on MigLayout. On an unrelated note, it appears JFrame's do not honor maxsize? Somehow, today, with and without using any of these methods provided by swing, with or without using MigLayout manager to handle some of these matters instead, I now have a JTabbedPane that correctly displays the FIRST JPanel I add, but NOT THE SECOND JPanel--which, while present as a tab--does not show when selected. I have switched the order of which panel is added first, and this still holds true regardless of which JPanel I add first, telling me the JPanels are ok, and the problem is most likely in the JTabbedPane. I click on the second tab, the JTabbedPane switches, but I have what appears to be a blank button in the JPanel. A few console system-out statements reveal the following: a) that the second panel and its button are constructed b) no mouse events are being captured when I click on where the second panel and button should reside, as if it didn't exist at that point; c) when I switch to the second tab, the overrided paintComponent() method of the button within that second JPanel is never called, so it is in fact never being painted despite the tab in which it resides becoming visible; d) the JTabbpedPane getComponentCount() returns a correct value of 2 after adding the 2nd panel; e) MigLayout manager actually rocks, but I digress... I cannot now revert to my older code, and despite my best efforts to undo whatever changes caused this, I cannot fix my new problem. I've commented out everything but the most essential calls: constructors for each object--with MigLayout; add() for placing the buttons on the panels using string-arguments appropriate for MigLayout; add() for placing the panels on the JTabbedPane, also with MigLayout string arguments; setting the default op on close for the JFrame; and setting the JFrame visible. This means I do not fiddle with optimization settings, double buffering settings, opaque settings, but leave them as default, and still, no fix; the second panel will not show itself. Each panel, I should add, when it is the first to be loaded, works fine, again re-affirming that the panels and buttons are themselves ok. Here is part of what I am doing: //Note: BuildaButton is a class that merely constructs my instances File f = new File("/foo.jpg"); button1 = new BuildaButton().BuildaButton(f).buildfoo1Button(); f = new File("/foo2.jpg"); button2 = new BuildaButton().BuildaButton(f).buildfoo2Button(); MigLayout ml = new MigLayout("wrap 1", "[fill, grow]0[fill, grow]", "[fill, grow]0[fill, grow]"); MigLayout ml2 = new MigLayout("wrap 2", "[fill, grow]5[fill, grow]", "[fill, grow]0[fill, grow]"); foo1panel = new JPanel(ml); foo1panel.add(button1, "w 234:945:, h 200:807:"); foo2panel = new JPanel(ml); foo2panel.add(button2, "w 186:752:, h 200:807:"); tabs.add("foo1", foo1panel); tabs.add("foo2", foo2panel); System.out.println("contents of tabs: " + tabs.getComponentCount() + " elements"); mainframe.setLayout(ml2); mainframe.setMinimumSize(new Dimension(850,800)); mainframe.add(tabs, "w 600:800:, h 780:780:"); //controlpanel is a still blank jpanel that holds nothing--it is a space holder for now & will be utilized mainframe.add(controlpanel, "w 200:200:200, h 780:780:"); mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainframe.setVisible(true); Thank you in advance for any help you can give.

    Read the article

  • Creating ActionEvent object for CustomButton in Java

    - by Crystal
    For a hw assignment, we were supposed to create a custom button to get familiar with swing and responding to events. We were also to make this button an event source which confuses me. I have an ArrayList to keep track of listeners that would register to listen to my CustomButton. What I am getting confused on is how to notify the listeners. My teacher hinted at having a notify and overriding actionPerformed which I tried doing, but then I wasn't sure how to create an ActionEvent object looking at the constructor documentation. The source, id, string all confuses me. Any help would be appreciated. Thanks! code: import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class CustomButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CustomButtonFrame frame = new CustomButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } public void addActionListener(ActionListener al) { listenerList.add(al); } public void removeActionListener(ActionListener al) { listenerList.remove(al); } public void actionPerformed(ActionEvent e) { System.out.println("Button Clicked!"); } private void notifyListeners() { ActionEvent event = new ActionEvent(CONFUSED HERE!!!!; for (ActionListener action : listenerList) { action.actionPerfomed(event); } } List<ActionListener> listenerList = new ArrayList<ActionListener>(); } class CustomButtonFrame extends JFrame { // constructor for CustomButtonFrame public CustomButtonFrame() { setTitle("Custom Button"); CustomButtonSetup buttonSetup = new CustomButtonSetup(); this.add(buttonSetup); this.pack(); } } class CustomButtonSetup extends JComponent { public CustomButtonSetup() { ButtonAction buttonClicked = new ButtonAction(); this.addMouseListener(buttonClicked); } // because frame includes borders and insets, use this method public Dimension getPreferredSize() { return new Dimension(200, 200); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // first triangle coords int x[] = new int[TRIANGLE_SIDES]; int y[] = new int[TRIANGLE_SIDES]; x[0] = 0; y[0] = 0; x[1] = 200; y[1] = 0; x[2] = 0; y[2] = 200; Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); // second triangle coords x[0] = 0; y[0] = 200; x[1] = 200; y[1] = 200; x[2] = 200; y[2] = 0; Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); g2.drawPolygon(firstTriangle); g2.setColor(firstColor); g2.fillPolygon(firstTriangle); g2.drawPolygon(secondTriangle); g2.setColor(secondColor); g2.fillPolygon(secondTriangle); // draw rectangle 10 pixels off border int s1[] = new int[RECT_SIDES]; int s2[] = new int[RECT_SIDES]; s1[0] = 5; s2[0] = 5; s1[1] = 195; s2[1] = 5; s1[2] = 195; s2[2] = 195; s1[3] = 5; s2[3] = 195; Polygon rectangle = new Polygon(s1, s2, RECT_SIDES); g2.drawPolygon(rectangle); g2.setColor(thirdColor); g2.fillPolygon(rectangle); } private class ButtonAction implements MouseListener { public void mousePressed(MouseEvent e) { System.out.println("Click!"); firstColor = Color.GRAY; secondColor = Color.WHITE; repaint(); } public void mouseReleased(MouseEvent e) { System.out.println("Released!"); firstColor = Color.WHITE; secondColor = Color.GRAY; repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} } public static final int TRIANGLE_SIDES = 3; public static final int RECT_SIDES = 4; private Color firstColor = Color.WHITE; private Color secondColor = Color.DARK_GRAY; private Color thirdColor = Color.LIGHT_GRAY; }

    Read the article

  • Java Animation Memory Overload [on hold]

    - by user2425429
    I need a way to reduce the memory usage of these programs while keeping the functionality. Every time I add 50 milliseconds or so to the set&display loop in AnimationTest1, it throws an out of memory error. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; //set&display loop while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Animation Color [on hold]

    - by user2425429
    I'm having problems in my java program for animation. I'm trying to draw a hexagon with a shape similar to that of a trapezoid. Then, I'm making it move to the right for a certain amount of time (DEMO_TIME). Animation and ScreenManager are "API" classes, and AnimationTest1 is a demo. In my test program, it runs with a black screen and white stroke color. I'd like to know why this happened and how to fix it. I'm a beginner, so I apologize for this question being stupid to all you game programmers. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Problem with JOGL and Framebuffer Render-to-texture: Invalid Framebuffer Operation Error

    - by quadelirus
    Okay, so I am trying to render a scene to a small 32x32 texture and ran into problems. I get an "invalid framebuffer operation" error when I try to actually draw anything to the texture. I have simplified the code below so that it simply tries to render a quad to a texture and then bind that quad as a texture for another quad that is rendered to the screen. So my question is this... where is the error? This is using JOGL 1.1.1. The error occurs at Checkpoint2 in the code. import java.awt.event.*; import javax.media.opengl.*; import javax.media.opengl.glu.*; import javax.swing.JFrame; import java.nio.*; public class Main extends JFrame implements GLEventListener, KeyListener, MouseListener, MouseMotionListener, ActionListener{ /* GL related variables */ private final GLCanvas canvas; private GL gl; private GLU glu; private int winW = 600, winH = 600; private int texRender_FBO; private int texRender_RB; private int texRender_32x32; public static void main(String args[]) { new Main(); } /* creates OpenGL window */ public Main() { super("Problem Child"); canvas = new GLCanvas(); canvas.addGLEventListener(this); canvas.addKeyListener(this); canvas.addMouseListener(this); canvas.addMouseMotionListener(this); getContentPane().add(canvas); setSize(winW, winH); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); canvas.requestFocus(); } /* gl display function */ public void display(GLAutoDrawable drawable) { gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, this.texRender_FBO); gl.glPushAttrib(GL.GL_VIEWPORT_BIT); gl.glViewport(0, 0, 32, 32); gl.glClearColor(1.f, 0.f, 0.f, 1.f); System.out.print("Checkpoint1: "); outputError(); gl.glBegin(GL.GL_QUADS); { //gl.glTexCoord2f(0.0f, 0.0f); gl.glColor3f(1.f, 0.f, 0.f); gl.glVertex3f(0.0f, 1.0f, 1.0f); //gl.glTexCoord2f(1.0f, 0.0f); gl.glColor3f(1.f, 1.f, 0.f); gl.glVertex3f(1.0f, 1.0f, 1.0f); //gl.glTexCoord2f(1.0f, 1.0f); gl.glColor3f(1.f, 1.f, 1.f); gl.glVertex3f(1.0f, 0.0f, 1.0f); //gl.glTexCoord2f(0.0f, 1.0f); gl.glColor3f(1.f, 0.f, 1.f); gl.glVertex3f(0.0f, 0.0f, 1.0f); } gl.glEnd(); System.out.print("Checkpoint2: "); outputError(); //Here I get an invalid framebuffer operation gl.glPopAttrib(); gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0); gl.glClearColor(0.f, 0.f, 0.f, 1.f); gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glColor3f(1.f, 1.f, 1.f); gl.glBindTexture(GL.GL_TEXTURE_1D, this.texRender_32x32); gl.glBegin(GL.GL_QUADS); { gl.glTexCoord2f(0.0f, 0.0f); //gl.glColor3f(1.f, 0.f, 0.f); gl.glVertex3f(0.0f, 1.0f, 1.0f); gl.glTexCoord2f(1.0f, 0.0f); //gl.glColor3f(1.f, 1.f, 0.f); gl.glVertex3f(1.0f, 1.0f, 1.0f); gl.glTexCoord2f(1.0f, 1.0f); //gl.glColor3f(1.f, 1.f, 1.f); gl.glVertex3f(1.0f, 0.0f, 1.0f); gl.glTexCoord2f(0.0f, 1.0f); //gl.glColor3f(1.f, 0.f, 1.f); gl.glVertex3f(0.0f, 0.0f, 1.0f); } gl.glEnd(); } /* initialize GL */ public void init(GLAutoDrawable drawable) { gl = drawable.getGL(); glu = new GLU(); gl.glClearColor(.3f, .3f, .3f, 1f); gl.glClearDepth(1.0f); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(0, 1, 0, 1, -10, 10); gl.glMatrixMode(GL.GL_MODELVIEW); //Set up the 32x32 texture this.texRender_FBO = genFBO(gl); gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, this.texRender_FBO); this.texRender_32x32 = genTexture(gl); gl.glBindTexture(GL.GL_TEXTURE_2D, this.texRender_32x32); gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB_FLOAT32_ATI, 32, 32, 0, GL.GL_RGB, GL.GL_FLOAT, null); gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT, GL.GL_TEXTURE_2D, this.texRender_32x32, 0); //gl.glDrawBuffer(GL.GL_COLOR_ATTACHMENT0_EXT); this.texRender_RB = genRB(gl); gl.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, this.texRender_RB); gl.glRenderbufferStorageEXT(GL.GL_RENDERBUFFER_EXT, GL.GL_DEPTH_COMPONENT24, 32, 32); gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, this.texRender_RB); gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0); gl.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, 0); outputError(); } private void outputError() { int c; if ((c = gl.glGetError()) != GL.GL_NO_ERROR) System.out.println(glu.gluErrorString(c)); } private int genRB(GL gl) { int[] array = new int[1]; IntBuffer ib = IntBuffer.wrap(array); gl.glGenRenderbuffersEXT(1, ib); return ib.get(0); } private int genFBO(GL gl) { int[] array = new int[1]; IntBuffer ib = IntBuffer.wrap(array); gl.glGenFramebuffersEXT(1, ib); return ib.get(0); } private int genTexture(GL gl) { final int[] tmp = new int[1]; gl.glGenTextures(1, tmp, 0); return tmp[0]; } /* mouse and keyboard callback functions */ public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { winW = width; winH = height; gl.glViewport(0, 0, width, height); } //Sorry about these, I just had to delete massive amounts of code to boil this thing down and these are hangers-on public void mousePressed(MouseEvent e) {} public void mouseDragged(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void keyPressed(KeyEvent e) {} public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void mouseMoved(MouseEvent e) { } public void actionPerformed(ActionEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }

    Read the article

  • Problem with my whiteboard application

    - by swift
    I have to develop a whiteboard application in which both the local user and the remote user should be able to draw simultaneously, is this possible? If possible then any logic? I have already developed a code but in which i am not able to do this, when the remote user starts drawing the shape which i am drawing is being replaced by his shape and co-ordinates. This problem is only when both draw simultaneously. any idea guys? Here is my code class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; int bpressed; Color color; Point start; Point end; Point mp; Button elipse=new Button("elipse"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button empty=new Button(""); JButton save=new JButton("Save"); JButton erase=new JButton("Erase"); String selected; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Point p=new Point(); int w,h; public Paper(DatagramSocket dataSocket) { this.dataSocket=dataSocket; client=new Client(dataSocket); System.out.println("paper"); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); //save.setPreferredSize(new Dimension(100,20)); save.setMaximumSize(new Dimension(75,27)); erase.setMaximumSize(new Dimension(75,27)); } public void paintComponent(Graphics g) { try { g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); repaint(); g2.dispose(); start=null; } //To add the point to the board which is broadcasted by the server public synchronized void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) selected="elipse"; else if(shape.equals("line")) selected="line"; else if(shape.equals("rect")) selected="rect"; else if(shape.equals("erase")) { selected="erase"; erase(); } if(end!=null && start!=null) { if(varname.equals("end")) end=ps; if(varname.equals("mp")) mp=ps; if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } } catch(Exception e) { e.printStackTrace(); } } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); pic.fillRect(start.x, start.y, 10, 10); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); JPanel row1=new JPanel(); JPanel row2=new JPanel(); JPanel row3=new JPanel(); JPanel row4=new JPanel(); buttonpanel.setPreferredSize(new Dimension(80,80)); //buttonpanel.setMinimumSize(new Dimension(150,150)); row1.setLayout(new BoxLayout(row1,BoxLayout.X_AXIS)); row1.setPreferredSize(new Dimension(150,150)); row2.setLayout(new BoxLayout(row2,BoxLayout.X_AXIS)); row3.setLayout(new BoxLayout(row3,BoxLayout.X_AXIS)); row4.setLayout(new BoxLayout(row4,BoxLayout.X_AXIS)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener( this); save.addActionListener( this); erase.addActionListener( this); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row1.add(elipse); row1.add(Box.createRigidArea(new Dimension(5,0))); row1.add(rectangle); buttonpanel.add(row1); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row2.add(line); row2.add(Box.createRigidArea(new Dimension(5,0))); row2.add(empty); buttonpanel.add(row2); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row3.add(save); buttonpanel.add(row3); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row4.add(erase); buttonpanel.add(row4); return buttonpanel; } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase") { start=e.getPoint(); client.broadcast(start,"start", selected,"press"); } else if(selected=="elipse"||selected=="rect") { mp = e.getPoint(); client.broadcast(mp,"mp", selected,"press"); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release"); } else if(selected=="elipse"||selected=="rect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release"); } draw(); } //start=null; } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag"); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag"); } else if(selected=="elipse"||selected=="rect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag"); client.broadcast(end,"end", selected,"drag"); } repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; if(e.getSource()==rectangle) selected="rect"; if(e.getSource()==save) save(); if(e.getSource()==erase) { selected="erase"; erase(); } } } class Button extends JButton { String name; public Button(String name) { this.name=name; Dimension buttonSize = new Dimension(35,35); setMaximumSize(buttonSize); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); } }

    Read the article

< Previous Page | 1 2 3  | Next Page >