Search Results

Search found 2668 results on 107 pages for 'implements'.

Page 10/107 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Passing Interface Class as a Parameter in Java

    - by aleclerc
    I have an interface: public interface IMech { } and a class that implements it public class Email implements IMech { } and a third class that has this method implemented: public void sendNotification( Class< IMech > mechanism ){ } now I'm trying to call that method like so foo.sendNotification(Email.class); but i keep getting an exception saying: The method sendNotification(Class<IMechanism>) in the type RemediationOperator is not applicable for the arguments (Class<EmailNotification>) Shouldn't this work if it interfaces that class?

    Read the article

  • how can I implement Comparable more than once?

    - by codeman73
    I'm upgrading some code to Java 5 and am clearly not understanding something with Generics. I have other classes which implement Comparable once, which I've been able to implement. But now I've got a class which, due to inheritance, ends up trying to implement Comparable for 2 types. Here's my situation: I've got the following classes/interfaces: interface Foo extends Comparable<Foo> interface Bar extends Comparable<Bar> abstract class BarDescription implements Bar class FooBar extends BarDescription implements Foo With this, I get the error 'interface Comparable cannot be implemented more than once with different arguments...' Why can't I have a compareTo(Foo foo) implemented in FooBar, and also a compareTo(Bar) implemented in BarDescription? Isn't this simply method overloading?

    Read the article

  • Using a Filter to serve a specific page?

    - by user246114
    Hi, I am using a class which implements Filter for my jsp stuff. It looks like this: public class MyFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.getRequestDispatcher("mypage.jsp").forward(request, response); } } So the target, "mypage.jsp", is just sitting in my top-level directory. The filter works fine if I'm entering urls like: http://www.mysite.com/foo http://www.mysite.com/boo but if I enter a trailing slash, I'll get a 404: http://www.mysite.com/foo/ http://www.mysite.com/boo/ HTTP ERROR: 404 /foo/mypage.jsp RequestURI=/foo/mypage.jsp it seems if I enter the trailing slash, then the filter thinks I want it to look for mypage.jsp in subfolder foo or boo, but I really always want it to just find it at: http://www.mysite.com/mypage.jsp how can I do that? Thank you

    Read the article

  • Persist collection of interface using Hibernate

    - by Olvagor
    I want to persist my litte zoo with Hibernate: @Entity @Table(name = "zoo") public class Zoo { @OneToMany private Set<Animal> animals = new HashSet<Animal>(); } // Just a marker interface public interface Animal { } @Entity @Table(name = "dog") public class Dog implements Animal { // ID and other properties } @Entity @Table(name = "cat") public class Cat implements Animal { // ID and other properties } When I try to persist the zoo, Hibernate complains: Use of @OneToMany or @ManyToMany targeting an unmapped class: blubb.Zoo.animals[blubb.Animal] I know about the targetEntity-property of @OneToMany but that would mean, only Dogs OR Cats can live in my zoo. Is there any way to persist a collection of an interface, which has several implementations, with Hibernate?

    Read the article

  • WCF reuse types in referenced assemblies does not reuse the ServiceContract Interface

    - by Matt
    I have three seperate projects: -MyUserControl (Needs a reference to a service implementing IMyService) -MyService (Implements IMyService) -MySharedInterfaces (IMyUserControl and IMyService) -MyWebApp The user control needs to be dynamically loaded at runtime. This implements IMyUserControl and has a property of type IMyService which will be set at runtime. The trouble is even with the option to reuse types the WebApp isn't reusing the IMyServiceType, it always generates it again from the Service Reference. This wouldn't be an issue if I could cast it to MySharedInterfaces.IMyService (which I can't understand, since it should be exactly the same). The user control is expecting something of type IMyService, is there anyway to either cast the WebServiceReference.IMyService back to MySharedInterface.IMyServiceReference or force the WebServiceReference to reuse the MySharedInterface.IMyServiceReference? Thanks

    Read the article

  • What's the standard way to organize the contents of Java packages -- specifically the location of in

    - by RenderIn
    I suppose this could go for many OO languages. I'm building my domain objects and am not sure where the best place is for the interfaces & abstract classes. If I have a pets package with various implementations of the APet abstract class: should it live side-by-side with them or in the parent package? How about interfaces? It seems like they almost have to live above the implementations in the parent package, since there could potentially be other subpackages which implement it, while there seems to be a stronger correlation between one abstract class and a subpackage. e.g. com.foo com.foo.IConsumer (interface) com.foo.APet (abstract) com.foo.pets.Dog extends APet implements IConsumer OR com.foo com.foo.IConsumer (interface) com.foo.pets.APet (abstract) com.foo.pets.Dog extends APet implements IConsumer or something else?

    Read the article

  • Casting between classes that share the same interface

    - by Chad
    I have two interfaces IHeaderRow, and IDetailRow I then have an object that implements both RawRow:IHeaderRow, IDetailRow I then need to cast it to HeaderRow which implements IHeaderRow. But when I try, it ends up being null or giving an exception. I can cast ObjectRawRow to either interface IHeaderRow, or IDetailRow var ObjectIHeaderRow = ObjectRawRow as IHeaderRow; var ObjectIDetailRow = ObjectRawRow as IDetailRow; But I can not cast ObjectRawRow to HeaderRow , or ObjectIHeaderRow to HeaderRow. It throws the error Cannot convert source type 'IA' to target type 'A' I need to cast it into the actual class HeaderRow. Thoughts?

    Read the article

  • Which machine learning library to use

    - by Space_C0wb0y
    I am looking for a library that, ideally, has the following features: implements hierarchical clustering of multidimensional data (ideally on similiarity or distance matrix) implements support vector machines is in C++ is somewhat documented (this one seems to be hardest) I would like this to be in C++, as I am most comfortable with that language, but I will also use any other language if the library is worth it. I have googled and found some, but I do not really have the time to try them all out, so I want hear what other people had for experiences. Please only answer if you have some experience with the library you recommend. P.S.: I could also use different libraries for the clustering and the SVM.

    Read the article

  • Java interface design

    - by Nayn
    Hi, I had an interface initially as below. public interface testMe { public Set<String> doSomething(); } public class A implements testMe { public Set<String> doSomething() { return // Set<String> } } I had similar classes implementing testMe. Now I have to add one more class which returns Set<Some Object> public class X implements testMe() { public Set<Some OBject> doSomething() { } } How could i add this mehtod in the interface without breaking existing classes? Thanks Nayn

    Read the article

  • VB.net: Custom ' TODO: List on an Interface

    - by Shiftbit
    How do I add my own todo and comments list to appear on Interfaces? I want it to pop up like IDisposable does: Public Class Foo : Implements IDisposable Private disposedValue As Boolean = False ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: free other state (managed objects). End If ' TODO: free your own state (unmanaged objects). ' TODO: set large fields to null. End If Me.disposedValue = True End Sub #Region " IDisposable Support " ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class Whenever I enter my own comments and todo list they are never autogenerated like IDisposable Interface does. I would like my own Interfaces to preserve the comments so that I can share my Interfaces with in source documentation.

    Read the article

  • Java FileFilter

    - by Mr CooL
    public class DocFilter extends FileFilter { public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.doc) || extension.equals(Utils.docx) ) { return true; } else { return false; } } return false; } //The description of this filter public String getDescription() { return "Just Document Files"; } } Netbeans compiler warned with the error, "No interface expected here" for above code Anyone has idea what was the problem?? I tried changing the 'extends' to 'implements', however, it didn't seem to work that way. and when I changed to implements, the following code cannot work, chooser.addChoosableFileFilter(new DocFilter()); and with this error, "method addChoosableFileFilter in class javax.swing.JFileChooser cannot be applied to given types required: javax.swing.filechooser.FileFilter" Can anyone help on this? Thanks..

    Read the article

  • Implementig Java Iterable<E> interface

    - by Metz
    Hi, i wrote this code: public class C1 implements Iterable<NC1> { private LinkedList<NC1> list; public static class NC1 { ... } ... x public Iterator<NC1> iterator() { return list.iterator(); } } but eclipse whines (at the x-ed line): - The return type is incompatible with Iterable<NC1>.iterator() - implements java.lang.Iterable<NC1>.iterator i don't understand where the mistake is. thanks in advance.

    Read the article

  • Show Alertdialog and use vibrator

    - by user1007522
    I'm having a class that implements RecognitionListener like this: public class listener implements RecognitionListener I wanted to show a alertdialog and use the vibrator but this isn't possible because I need to provide a context what I don't have. My alertdialog code was like this: new AlertDialog.Builder(this) .setTitle("dd") .setMessage("aa") .setNeutralButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .show(); But the AlertDialog.Builder(this) wants a context, the same problem with my vibrator code: v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); The getSystemService method isn't available. My code that starts the class: sr = SpeechRecognizer.createSpeechRecognizer(this); sr.setRecognitionListener(new listener()); Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test"); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5); sr.startListening(intent); Whats the best way to solve this?

    Read the article

  • @OneToOne and @JoinColumn, auto delete null entity , doable?

    - by smallufo
    I have two Entities , with the following JPA annotations : @Entity @Table(name = "Owner") public class Owner implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private long id; @OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL) @JoinColumn(name="Data_id") private Data Data; } @Entity @Table(name = "Data") public class Data implements Serializable { @Id private long id; } Owner and Data has one-to-one mapping , the owning side is Owner. The problem occurs when I execute : owner.setData(null) ; ownerDao.update(owner) ; The "Owner" table's Data_id becomes null , that's correct. But the "Data" row is not deleted automatically. I have to write another DataDao , and another service layer to wrap the two actions ( ownerDao.update(owner) ; dataDao.delete(data); ) Is it possible to make a data row automatically deleted when the owning Owner set it to null ?

    Read the article

  • repaint problem

    - by user357816
    I have a problem with my repaint in the method move. I dont know what to doo, the code is below import java.awt.*; import java.io.*; import java.text.*; import java.util.*; import javax.sound.sampled.*; import javax.swing.*; import javax.swing.Timer; import java.awt.event.*; import java.lang.*; public class bbb extends JPanel { public Stack<Integer> stacks[]; public JButton auto,jugar,nojugar; public JButton ok,ok2; public JLabel info=new JLabel("Numero de Discos: "); public JLabel instruc=new JLabel("Presiona la base de las torres para mover las fichas"); public JLabel instruc2=new JLabel("No puedes poner una pieza grande sobre una pequenia!"); public JComboBox numeros=new JComboBox(); public JComboBox velocidad=new JComboBox(); public boolean seguir=false,parar=false,primera=true; public int n1,n2,n3; public int click1=0; public int opcion=1,tiempo=50; public int op=1,continuar=0,cont=0; public int piezas=0; public int posx,posy; public int no; public bbb() throws IOException { stacks = new Stack[3]; stacks[0]=new Stack<Integer>(); stacks[1]=new Stack<Integer>(); stacks[2]=new Stack<Integer>(); setPreferredSize(new Dimension(1366,768)); ok=new JButton("OK"); ok.setBounds(new Rectangle(270,50,70,25)); ok.addActionListener(new okiz()); ok2=new JButton("OK"); ok2.setBounds(new Rectangle(270,50,70,25)); ok2.addActionListener(new vel()); add(ok2);ok2.setVisible(false); auto=new JButton("Automatico"); auto.setBounds(new Rectangle(50,80,100,25)); auto.addActionListener(new a()); jugar=new JButton("PLAY"); jugar.setBounds(new Rectangle(100,100,70,25)); jugar.addActionListener(new play()); nojugar=new JButton("PAUSE"); nojugar.setBounds(new Rectangle(100,150,70,25)); nojugar.addActionListener(new stop()); setLayout(null); info.setBounds(new Rectangle(50,50,170,25)); info.setForeground(Color.white); instruc.setBounds(new Rectangle(970,50,570,25)); instruc.setForeground(Color.white); instruc2.setBounds(new Rectangle(970,70,570,25)); instruc2.setForeground(Color.white); add(instruc);add(instruc2); add(jugar);add(nojugar);jugar.setVisible(false);nojugar.setVisible(false); add(info); info.setVisible(false); add(ok); ok.setVisible(false); add(auto); numeros.setBounds(new Rectangle(210,50,50,25)); numeros.addItem(1);numeros.addItem(2);numeros.addItem(3);numeros.addItem(4);numeros.addItem(5); numeros.addItem(6);numeros.addItem(7);numeros.addItem(8);numeros.addItem(9);numeros.addItem(10); add(numeros); numeros.setVisible(false); velocidad.setBounds(new Rectangle(150,50,100,25)); velocidad.addItem("Lenta"); velocidad.addItem("Intermedia"); velocidad.addItem("Rapida"); add(velocidad); velocidad.setVisible(false); } public void Mover(int origen, int destino) { for (int i=0;i<3;i++) { System.out.print("stack "+i+": "); for(int n : stacks[i]) System.out.print(n+";"); System.out.println(""); } System.out.println("de <"+origen+"> a <"+destino+">"); stacks[destino].push(stacks[origen].pop()); System.out.println(""); this.validate(); this.repaint( ); } public void hanoi(int origen, int destino, int cuantas) { while (parar) {} if (cuantas <= 1) Mover(origen,destino); else { hanoi(origen,3 - (origen+destino),cuantas-1); Mover(origen,destino); hanoi(3 - (origen+destino),destino,cuantas-1); } } public void paintComponent(Graphics g) { ImageIcon fondo= new ImageIcon("fondo.jpg"); g.drawImage(fondo.getImage(),0, 0,1366,768,null); g.setColor(new Color((int)(Math.random() * 254), (int)(Math.random() *255), (int)(Math.random() * 255))); g.fillRect(0,0,100,100); g.setColor(Color.white); g.fillRect(150,600,250,25); g.fillRect(550,600,250,25); g.fillRect(950,600,250,25); g.setColor(Color.red); g.fillRect(270,325,10,275); g.fillRect(270+400,325,10,275); g.fillRect(270+800,325,10,275); int x, y,top=0; g.setColor(Color.yellow); x=150;y=580; for(int ii:stacks[0]) { g.fillRect(x+((ii*125)/10),y-(((ii)*250)/10),((10-ii)*250)/10,20);} x=550;y=580; for(int ii:stacks[1]) {g.fillRect(x+((ii*125)/10),y-(((ii)*250)/10),((10-ii)*250)/10,20);} x=950;y=580; for(int ii:stacks[2]) {g.fillRect(x+((ii*125)/10),y-(((ii)*250)/10),((10-ii)*250)/10,20);} System.out.println("ENTRO"); setOpaque(false); } private class play implements ActionListener //manual { public void actionPerformed(ActionEvent algo) { parar=false; if(primera=true) { hanoi(0,2,no); primera=false; } } } private class stop implements ActionListener //manual { public void actionPerformed(ActionEvent algo) { parar=true; } } private class vel implements ActionListener //manual { public void actionPerformed(ActionEvent algo) { if (velocidad.getSelectedItem()=="Lenta") {tiempo=150;} else if (velocidad.getSelectedItem()=="Intermedia") {tiempo=75;} else tiempo=50; ok2.setVisible(false); jugar.setVisible(true); nojugar.setVisible(true); } } private class a implements ActionListener //auto { public void actionPerformed(ActionEvent algo) { auto.setVisible(false); info.setVisible(true); numeros.setVisible(true); ok.setVisible(true); op=3; } } private class okiz implements ActionListener //ok { public void actionPerformed(ActionEvent algo) { no=Integer.parseInt(numeros.getSelectedItem().toString()); piezas=no; if (no>0 && no<11) { info.setVisible(false); numeros.setVisible(false); ok.setVisible(false); for (int i=no;i>0;i--) stacks[0].push(i); opcion=2; if (op==3) { info.setText("Velocidad: ");info.setVisible(true); velocidad.setVisible(true); ok2.setVisible(true); } } else { } repaint(); } } } the code of the other class that calls the one up is below: import java.awt.*; import java.io.*; import java.net.URL; import javax.imageio.*; import javax.swing.*; import javax.swing.border.*; import java.lang.*; import java.awt.event.*; public class aaa extends JPanel { private ImageIcon Background; private JLabel fondo; public static void main(String[] args) throws IOException { JFrame.setDefaultLookAndFeelDecorated(true); final JPanel cp = new JPanel(new BorderLayout()); JFrame frame = new JFrame ("Torres de Hanoi"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.setSize(550,550); frame.setVisible(true); bbb panel = new bbb(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }

    Read the article

  • Repaint() not calling paint() in Java

    - by Joshua Auriemma
    Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now. With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program. Entire code is below: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.io.FileReader; import java.io.IOException; import java.util.Calendar; public class Reflexology1 extends JFrame{ private static final long serialVersionUID = -1295261024563143679L; private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25); private Timer moveBallTimer; int _ballXpos, _ballYpos; JButton button1, button2; JButton movingButton; JTextArea textArea1; int buttonAClicked, buttonDClicked; private long _openTime = 0; private long _closeTime = 0; JPanel thePanel = new JPanel(); JPanel thePlacebo = new JPanel(); final JFrame frame = new JFrame("Reflexology"); final JFrame frame2 = new JFrame("The Test"); JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can."); public static void main(String[] args){ new Reflexology1(); } public Reflexology1(){ frame.setSize(600, 475); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Reflexology 1.0"); frame.setResizable(false); frame2.setSize(600, 475); frame2.setLocationRelativeTo(null); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setTitle("Reflexology 1.0"); frame2.setResizable(false); button1 = new JButton("Accept"); button2 = new JButton("Decline"); //movingButton = new JButton("Click Me"); ListenForAcceptButton lForAButton = new ListenForAcceptButton(); ListenForDeclineButton lForDButton = new ListenForDeclineButton(); button1.addActionListener(lForAButton); button2.addActionListener(lForDButton); //movingButton.addActionListener(lForMButton); JTextArea textArea1 = new JTextArea(24, 50); textArea1.setText("Tracking Events\n"); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setSize(15, 50); textArea1.setEditable(false); FileReader reader = null; try { reader = new FileReader("EULA.txt"); textArea1.read(reader, "EULA.txt"); } catch (IOException exception) { System.err.println("Problem loading file"); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException exception) { System.err.println("Error closing reader"); exception.printStackTrace(); } } } JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); AdjustmentListener listener = new MyAdjustmentListener(); thePanel.add(scrollBar1); thePanel.add(button1); thePanel.add(button2); frame.add(thePanel); ListenForMouse lForMouse = new ListenForMouse(); thePlacebo.addMouseListener(lForMouse); thePlacebo.add(label1); frame2.add(thePlacebo); ListenForWindow lForWindow = new ListenForWindow(); frame.addWindowListener(lForWindow); frame2.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e){ if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();} } }); frame.setVisible(true); moveBallTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { moveBall(); System.out.println("Timer started!"); repaint(); } }); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(frame2.isVisible()){ moveBallTimer.start(); } } }); } private class ListenForAcceptButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button1){ Calendar ClCDateTime = Calendar.getInstance(); System.out.println(ClCDateTime.getTimeInMillis() - _openTime); _closeTime = ClCDateTime.getTimeInMillis() - _openTime; //frame.getContentPane().remove(thePanel); //thePlacebo.addKeyListener(lForKeys); //frame.getContentPane().add(thePlacebo); //frame.repaint(); //moveBallTimer.start(); frame.setVisible(false); frame2.setVisible(true); frame2.revalidate(); frame2.repaint(); } } } private class ListenForDeclineButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button2){ JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } private class ListenForWindow implements WindowListener{ public void windowActivated(WindowEvent e) { //textArea1.append("Window is active"); } // if this.dispose() is called, this is called: public void windowClosed(WindowEvent arg0) { } // When a window is closed from a menu, this is called: public void windowClosing(WindowEvent arg0) { } // Called when the window is no longer the active window: public void windowDeactivated(WindowEvent arg0) { //textArea1.append("Window is NOT active"); } // Window gone from minimized to normal state public void windowDeiconified(WindowEvent arg0) { //textArea1.append("Window is in normal state"); } // Window has been minimized public void windowIconified(WindowEvent arg0) { //textArea1.append("Window is minimized"); } // Called when the Window is originally created public void windowOpened(WindowEvent arg0) { //textArea1.append("Let there be Window!"); Calendar OlCDateTime = Calendar.getInstance(); _openTime = OlCDateTime.getTimeInMillis(); //System.out.println(_openTime); } } private class MyAdjustmentListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent arg0) { AdjustmentEvent scrollBar1; //System.out.println(scrollBar1.getValue())); } } public void paint(Graphics g) { //super.paint(g); frame2.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.fill(ball); System.out.println("Calling fill()"); } protected void moveBall() { //System.out.println("I'm in the moveBall() function!"); int width = getWidth(); int height = getHeight(); int min, max, randomX, randomY; min =200; max = -200; randomX = min + (int)(Math.random() * ((max - min)+1)); randomY = min + (int)(Math.random() * ((max - min)+1)); //System.out.println(randomX + ", " + randomY); Rectangle ballBounds = ball.getBounds(); //System.out.println(ballBounds.x + ", " + ballBounds.y); if (ballBounds.x + randomX < 0) { randomX = 200; } else if (ballBounds.x + ballBounds.width + randomX > width) { randomX = -200; } if (ballBounds.y + randomY < 0) { randomY = 200; } else if (ballBounds.y + ballBounds.height + randomY > height) { randomY = -200; } ballBounds.x += randomX; ballBounds.y += randomY; _ballXpos = ballBounds.x; _ballYpos = ballBounds.y; ball.setFrame(ballBounds); } public void start() { moveBallTimer.start(); } public void stop() { moveBallTimer.stop(); } private class ListenForMouse implements MouseListener{ // Called when the mouse is clicked public void mouseClicked(MouseEvent e) { //System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n"); if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) { System.out.println("TRUE"); } System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } // System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos); // Mouse over public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse left the mouseover area: public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.

    Read the article

  • Can't get jQuery AutoComplete to work with External JSON

    - by rockinthesixstring
    I'm working on an ASP.NET app where I'm in need of jQuery AutoComplete. Currently there is nothing happening when I type data into the txt63 input box (and before you flame me for using a name like txt63, I know, I know... but it's not my call :D ). Here's my javascript code <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script> <script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.1.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> var theSource = '../RegionsAutoComplete.axd?PID=<%= hidden62.value %>' $(function () { $('#<%= txt63.ClientID %>').autocomplete({ source: theSource, minLength: 2, select: function (event, ui) { $('#<%= hidden63.ClientID %>').val(ui.item.id); } }); }); and here is my HTTP Handler Namespace BT.Handlers Public Class RegionsAutoComplete : Implements IHttpHandler Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable Get Return False End Get End Property Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest 'the page contenttype is plain text context.Response.ContentType = "application/json" context.Response.ContentEncoding = Encoding.UTF8 'set page caching context.Response.Cache.SetExpires(DateTime.Now.AddHours(24)) context.Response.Cache.SetCacheability(HttpCacheability.Public) context.Response.Cache.SetSlidingExpiration(True) context.Response.Cache.VaryByParams("PID") = True Try ' use the RegionsDataContext Using RegionDC As New DAL.RegionsDataContext ' query the database based on the querysting PID Dim q = (From r In RegionDC.bt_Regions _ Where r.PID = context.Request.QueryString("PID") _ Select r.Region, r.ID) ' now we loop through the array ' and write out the ressults Dim sb As New StringBuilder sb.Append("{") For Each item In q sb.Append("""" & item.Region & """: """ & item.ID & """,") Next sb.Append("}") context.Response.Write(sb.ToString) End Using Catch ex As Exception HealthMonitor.Log(ex, False, "This error occurred while populating the autocomplete handler") End Try End Sub End Class End Namespace The rest of my ASPX page has the appropriate controls as I had this working with the old version of the jQuery library. I'm trying to get it working with the new one because I heard that the "dev" CDN was going to be obsolete. Any help or direction will be greatly appreciated.

    Read the article

  • What is this Design Pattern?

    - by Can't Tell
    I read the Wikipedia articles on FactoryMethod and AbstractFactory but the following code doesn't seem to fit anywhere. Can someone explain to me what the following pattern is or if it is an anti-pattern? interace PaymentGateway{ void makePayment(); } class PaypalPaymentGateway implements PaymentGateway { public void makePayment() { //some implementation } } class AuthorizeNetPaymentGateway implements PaymentGateway { public void makePayment() { //some implementation } } class PaymentGatewayFacotry{ PaymentGateway createPaymentGateway(int gatewayId) { if(gatewayId == 1) return PaypalPaymentGateway(); else if(gatewayId == 2) return AuthorizeNetPaymentGateway(); } } Let's say the user selects the payment method using a radio button on an html page and the gatewayId is derived from the radio button value. I have seen code like this and thought it was the AbstractFactory pattern but after reading the Wikipedia article, I'm having doubts.

    Read the article

  • Question on a tutorial

    - by hansa
    Hello, i´m trying to get following tutorial to run and understand: http://www.ibm.com/developerworks/web/library/wa-cometjava/index.html In the example code which can be downloaded at the bottom of the page is everything in one class with two inner classes. How can i make the the thread of "MessageSender" (Listing 3) visible to "The Weatherman" (Listing 4) so i can use it in the run method without using inner classes? Thank you hansa Reformulation of Question: How to make the send-method of inner class MessageSender make accessible in ClassThatDoSomething. Example-Code: public class Example extends HttpServlet implements CometProcessor { private MessageSender messageSender = null; @Override public void init() throws ServletException { // starts thread MessageSender } public event(CometEvent) { // Object of ClassThatDoSomething gets created started } private class ClassThatDoSomething { public void start() { Runnable runnable = new Runnable() { public void run(){ messageSender.send(message); } Thread thread = new Thread(runnable); thread.start(); } } private class MessageSender implements Runnable { public void send(String message) { //... } public void run() { //...} } }

    Read the article

  • EJB / JSF java.lang.ClassNotFoundException: com.ericsantanna.jobFC.dao.DAOFactoryRemote from [Module "com.sun.jsf-impl:main" from local module loader

    - by Eric Sant'Anna
    I'm in my first time using EJB and JSF, and I can't resolve this: 20:23:12,457 Grave [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8081-2) com.ericsantanna.jobFC.dao.DAOFactoryRemote from [Module "com.sun.jsf-impl:main" from local module loader @439db2b2 (roots: C:\jboss-as-7.1.1.Final\modules)]: java.lang.ClassNotFoundException: com.ericsantanna.jobFC.dao.DAOFactoryRemote from [Module "com.sun.jsf-impl:main" from local module loader @439db2b2 (roots: C:\jboss-as-7.1.1.Final\modules)] I'm getting this when I do an action like a selectOneMenu or a commandButton click. DAOFactory.class @Singleton @Remote(DAOFactoryRemote.class) public class DAOFactory implements DAOFactoryRemote { private static final long serialVersionUID = 6030538139815885895L; @PersistenceContext private EntityManager entityManager; @EJB private JobDAORemote jobDAORemote; /** * Default constructor. */ public DAOFactory() { // TODO Auto-generated constructor stub } @Override public JobDAORemote getJobDAO() { JobDAO jobDAO = (JobDAO) jobDAORemote; jobDAO.setEntityManager(entityManager); return jobDAO; } JobDAO.class @Stateless @Remote(JobDAORemote.class) public class JobDAO implements JobDAORemote { private static final long serialVersionUID = -5483992924812255349L; private EntityManager entityManager; /** * Default constructor. */ public JobDAO() { // TODO Auto-generated constructor stub } @Override public void insert(Job t) { entityManager.persist(t); } @Override public Job findById(Class<Job> classe, Long id) { return entityManager.getReference(classe, id); } @Override public Job findByName(Class<Job> clazz, String name) { return entityManager .createQuery("SELECT job FROM " + clazz.getName() + " job WHERE job.nome = :nome" , Job.class) .setParameter("name", name) .getSingleResult(); } ... TriggerFormBean.class @ManagedBean @ViewScoped @Stateless public class TriggerFormBean implements Serializable { private static final long serialVersionUID = -3293560384606586480L; @EJB private DAOFactoryRemote daoFactory; @EJB private TriggerManagerRemote triggerManagerRemote; ... triggerForm.xhtml (a portion with problem) </p:layoutUnit> <p:layoutUnit id="eastConditionPanel" position="center" size="50%"> <p:panel header="Conditions to Release" style="width:97%;height:97%;"> <h:panelGrid columns="2" cellpadding="3"> <h:outputLabel value="Condition Name:" for="conditionName" /> <p:inputText id="conditionName" value="#{triggerFormBean.newCondition.name}" /> </h:panelGrid> <p:commandButton value="Add Condition" update="conditionsToReleaseList" id="addConditionToRelease" actionListener="#{triggerFormBean.addNewCondition}" /> <p:orderList id="conditionsToReleaseList" value="#{triggerFormBean.trigger.conditionsToRelease}" var="condition" controlsLocation="none" itemLabel="#{condition.name}" itemValue="#{condition}" iconOnly="true" style="width:97%;heigth:97%;"/> </p:panel> </p:layoutUnit> In TriggerFormBean.class if comments daoFactory we get the same exception with triggerManagerRemote, both annotated with @EJB. I'm don't understand the relationship between my DAOFactory and the "Module com.sun.jsf-impl:main"... Thanks.

    Read the article

  • Getting field of type bytea in helper table when using GenerationType.IDENTITY

    - by dtrunk
    I'm creating my db scheme using Hibernate. There's a Table called "tbl_articles" and another one called "tbl_categories". To have a n-n relationship a helper table ("tbl_articles_categories") is needed. Here are all necessary Entities: @Entity @Table( name = "tbl_articles" ) public class Article implements Serializable { private static final long serialVersionUID = 1L; @Id @Column( nullable = false ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Integer id; // other fields... public Integer getId() { return id; } public void setId( Integer id ) { this.id = id; } // other fields... } @Entity @Table( name = "tbl_categories" ) public class Category implements Serializable { private static final long serialVersionUID = 1L; @Id @Column( nullable = false ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Integer id; // other fields public Integer getId() { return id; } public void setId( Integer id ) { this.id = id; } // other fields... } @Entity @Table( name = "tbl_articles_categories" ) @AssociationOverrides({ @AssociationOverride( name = "pk.article", joinColumns = @JoinColumn( name = "article_id" ) ), @AssociationOverride( name = "pk.category", joinColumns = @JoinColumn( name = "category_id" ) ) }) public class ArticleCategory { private ArticleCategoryPK pk = new ArticleCategoryPK(); public void setPk( ArticleCategoryPK pk ) { this.pk = pk; } @EmbeddedId public ArticleCategoryPK getPk() { return pk; } @Transient public Article getArticle() { return pk.getArticle(); } public void setArticle( Article article ) { pk.setArticle( article ); } @Transient public Category getCategory() { return pk.getCategory(); } public void setCategory( Category category ) { pk.setCategory( category ); } } @Embeddable public class ArticleCategoryPK implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne @ForeignKey( name = "tbl_articles_categories_fkey_article_id" ) private Article article; @ManyToOne @ForeignKey( name = "tbl_articles_categories_fkey_category_id" ) private Category category; public ArticleCategoryPK( Article article, Category category ) { setArticle( article ); setCategory( category ); } public ArticleCategoryPK() { } public Article getArticle() { return article; } public void setArticle( Article article ) { this.article = article; } public Category getCategory() { return category; } public void setCategory( Category category ) { this.category = category; } } Now, I'm getting a serial type what I wanted in my articles table as well as in my categories table. But looking into my helper table, there aren't the expected fields article_id and category_id each of type integer - instead there are article and category of type bytea. What's wrong here? EDIT: Sorry, forgot to mention that I'm using PostgreSQL.

    Read the article

  • Another Spring + Hibernate + JPA question

    - by Albinoswordfish
    I'm still struggling with changing my Spring Application to use Hibernate with JPA to do database activities. Well apparently from a previous post I need an persistence.xml file. However do I need to make changes to my current DAO class? public class JdbcProductDao extends Dao implements ProductDao { /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog(getClass()); public List<Product> getProductList() { logger.info("Getting products!"); List<Product> products = getSimpleJdbcTemplate().query( "select id, description, price from products", new ProductMapper()); return products; } public void saveProduct(Product prod) { logger.info("Saving product: " + prod.getDescription()); int count = getSimpleJdbcTemplate().update( "update products set description = :description, price = :price where id = :id", new MapSqlParameterSource().addValue("description", prod.getDescription()) .addValue("price", prod.getPrice()) .addValue("id", prod.getId())); logger.info("Rows affected: " + count); } private static class ProductMapper implements ParameterizedRowMapper<Product> { public Product mapRow(ResultSet rs, int rowNum) throws SQLException { Product prod = new Product(); prod.setId(rs.getInt("id")); prod.setDescription(rs.getString("description")); prod.setPrice(new Double(rs.getDouble("price"))); return prod; } } } Also my Product.Java is below public class Product implements Serializable { private int id; private String description; private Double price; public void setId(int i) { id = i; } public int getId() { return id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Description: " + description + ";"); buffer.append("Price: " + price); return buffer.toString(); } } I guess my question would be, How would my current classes change after using Hibernate + JPA with an Entity Manager

    Read the article

  • [app-engine-java-groovy] One-to-Many relationship. Select objects from datastore.

    - by Olexandr
    Hi. I've omitted some code(package declarations, imports, other fields) for shortness. I have here simple One-to-Many relation. It worked fine till this moment. @PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true") class Restaurant implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) Key id @Persistent(mappedBy = "restaurant") List<RestaurantAddress> addresses = new ArrayList<RestaurantAddress>() } //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= @PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true") class RestaurantAddress implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) Key id @Persistent Restaurant restaurant } Now i need to get(select) all the Restaurants from DB: def getRestaurantsToExport(final String dst, final int count) { String field = restaurantExportFields[dst] return transactionExecute() { PersistenceManager pm -> Query q = pm.newQuery(Restaurant.class) q.filter = "$field == null" q.setRange(0, count) return q.execute() } } But there are on problem - query gives me 12 restaurants(as in DB) but every Restaurant has 0 Address but in Datastore every Restaurant has minimum 2 addresses. Have anyone the same problem or knows the solution ?

    Read the article

  • Annotations: methods vs variables

    - by Zenzen
    I was always sure (don't know why) that it's better to add annotations to variables, but while browsing the Hibernate doc http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection I noticed they tend to annotate the methods. So should I put my annotations before methods, like this: @Entity public class Flight implements Serializable { private long id; @Id @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } } Or is it better to do it like this: @Entity public class Flight implements Serializable { @Id @GeneratedValue private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } } Or maybe there's no difference?

    Read the article

  • Convert an interface's event from VB.Net to C#

    - by Jules
    Hi, I'm struggling to convert the below code to C#. Class Class1 Implements IMyInterface Public Event MyEvent(ByVal sender As Object, ByVal e As MyEventArgs) Implements IMyInterface.MyEvent Public Sub New() AddHandler Me.Slider.ValueChanged, AddressOf OnSliderValueChanged End Sub Private Sub OnSliderValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) RaiseEvent MyEvent(Me, New MyEventArgs()) End Sub End Class Here's what visual studio inserts when I ask it to implement for me: event EventHandler<MyEventArgs> IMyInterface.MyEvent { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } With a bit of googling I'm sure I can find out what to replace the NotImplementedException parts with but VS is still telling me that the definition is not implemented anyway.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >