w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Distributing a java plugin's functionality elegantly - general Java / OOP noob issue
If I understood you right you want a Bukkit Plugin to change Weather, Time, list online players and so on. But you shouldn't spilt that all up. It is easier for you if you do that in one Project. If you want a organised plugin you only should use packages and classes. The bukkit wiki shows you how to do it. Bukkit Plugin Tutorial I use it myself for my plugins.

Categories : Java

Java performance testing changes when executing code from callback class. Java stack frame issue?
These results aren't really "dramatic." The averages for the 1000000 runs are: staticMethod1 explicit: 14541456.7 (14.5 ns per iteration) callback: 15272563.3 (15.2 ns per iteration) slowdown: 0.7 ns per iteration staticMethod2 explicit: 2167413.1 (2.2 ns per iteration) callback: 9494495.2 (9.5 ns per iteration) slowdown: (7 ns per iteration) The fact that the slowdown between these is off by (almost exactly) an order of magnitude is weird, but the big thing is that the callback approach slowed down by at most about 7 ns. That's not a whole lot. UPDATE More results you have posted, with the order of testing method2 then method1, are consistent with the following: the JVM initially runs your code in interpreted mode, profiling it; it sees that you always call the same implmenta

Categories : Java

Performance issue in using two java class in single java file
Don't worry about performance until somebody notices a real problem in a production environment. Anything else is premature optimization. That being said, don't use two top-level classes in a single java file. It's a bad code smell.

Categories : Java

Java issue, java.io.FileNotFoundException:
I guess you are behind a proxy that is why you are getting issue with url.openStream(). Try to set the proxy configuration, hope it works. String proxyUser = ""; String proxyPassword = ""; String proxyAddress = ""; int proxyPort = 8080; InetSocketAddress sa = new InetSocketAddress(proxyAddress, proxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, sa); URLConnection conn = url.openConnection(proxy);

Categories : Java

Issue with java.nio in Android 3+
Alright, so here was the problem: In the array the phone was getting, both messages were coming in at once (look at question to see what I mean). It was only reading all of it (due to InputStream.read() returning the length of the entire buffer) but accepting some of it (due to the length header). After it read the 16 byte message at the beginning and cleared it from the buffer, it read the zeros in it's space again. The Solution? Make the server take a breath between the cipher share and the connected message. It turns out it was a "good" problem - my phone is too fast. That's why it worked in an emulator with old software. (Plus I have a lightning fast Nexus 4, so that may have contributed.)

Categories : Java

Java repaint issue
Introduce a boolean to keep track of whether this component has drawn rectangles before or not private boolean hasBeenPainted; Then in your paintcomponent: public void paintComponent(Graphics g){ super.paintComponent(g); if(hasBeenPainted){return;} random=new Random(); for(int i=0;i<=1000;i++){ rX=random.nextInt(400); rY=random.nextInt(400); g.drawRect(rX,rY,20,20); } g.setColor(Color.red); g.fillRect(x,y,20,20); hasBeenPainted = true; }

Categories : Java

java run out of memory issue
Heap is only part of the equation. Have a look at total resident memory - it includes heap and off heap contributions. Off heap includes mapped JARs, thread stacks (~1MB per thread), perm gen, etc. SO has a number of questions on how to do it on Linux.

Categories : Java

Java Rectangle Issue
The fillRect and drawRect methods take int arguments, not double. You have two options: If you're using Graphics2D, use g.fill(rectangle) instead of fillRect. Cast the arguments to int g.fillRect((int) rectangle.getX(),(int) rectangle.getY(), (int) rectangle.getWidth(),(int) rectangle.getHeight());

Categories : Java

Java Split issue
The split method by default discards trailing empty strings when splitting the text. If you really want the trailing empty strings, then use the overloaded version of split that takes two arguments -- the second argument limit can be negative, and it tells split not to discard trailing empty strings. But I don't see why you would want the trailing empty strings. The split method normally discards them for you.

Categories : Java

Java Comm API Issue
In your code you have (exception handling removed for purpose of example): byte[] readBuffer = new byte[20]; while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.print(new String(readBuffer)); You have a 20-byte buffer and you are constructing a String from all 20 bytes no matter how much data you read. In Java, a String can contain nulls, and so your string ends up being a character followed by 19 nulls. Then when you print it your particular console displays spaces instead of nulls. Couple of things to note. First, it's not really clear what you are trying to do with this loop. You repeatedly read into the same 20 byte buffer no matter how many bytes are left on the stream (e.g. if there are 400 bytes to read, at most readBuffer end

Categories : Java

Visibility issue in Java
if you want variables to be accessible through subclass, you need to make them protected. but still those will be accessible from other classes but in same package. however those will be protected from classes outside of the package, except those who inherit your class where the variables are defined. And yes, instead of making variables themselves as private, you should define setters to access them. It is not at all bad practice, in fact its best practice in all object oriented programming.

Categories : Java

Issue getting program to run JAVA
Looks like you are trying to add buttons which are not initialized add(okButton); add(cancelButton); You should initialize both of them before adding them Button okButton = new Button(..); Button cancelButton = new Button(..);

Categories : Java

Generics issue with Java
Specify the generics type as Map<String, Object> data = this.aub.getData(); data.put("ip_macs", new LinkedList<Object>()); // Compiles When you say Map<String, ? extends Object> it means a Map whose key is of type String and the value extends Object but its type is unknown ?. Since, the type is not known it's unsafe to insert a LinkedList object there. Basically, the compiler is trying to prevent this: Map<String, String> mapOfStrings = new HashMap<String, String>(); mapOfStrings.add("string", "value"); Map<String, ? extends Object> map = mapOfStrings; // Compiles map.add("string", 1); // ERROR! If this was allowed, you just circumvented the type safety offered by generics.

Categories : Java

Java For Loop Issue
The input.nextInt() call reads the integer but leaves the new line character unread in the input stream, so the input.nextLine() call in the loop just reads that character in the first iteration. So, you need the following - int playernum = input.nextInt(); input.nextLine(); //read the unread new line character from the input stream

Categories : Java

Java image display issue
Well, i'd say to try using Graphics, meaning you need to override the paint method; i'd recommend that you put the mouseX and mouseY as global variables though… // creating global image variable for use later Image imageVariable = new ImageIcon("image path").getImage(); public void paintComponent(Graphics g) { // here you could either create a Graphics2D object // Graphics2D g2 = (Graphics2D)g; // or you could use the g parameter as it is, doesn't matter. // use the global variable for the image to be drawn onto the screen // use the global value of the mouseX and mouseY for where you click the mouse // to place the image, and this should be it g.drawImage(imageVariable, mouseX, mouseY, null); } Hope this helps!

Categories : Java

Java 7 SimpleDateformat misuse or issue?
Explanation is here DateFormatSymbols dfs = new DateFormatSymbols(Locale.FRENCH); for (String s : dfs.getShortMonths()) { System.out.print(s + " "); } output janv. f?vr. mars avr. mai juin juil. ao?t sept. oct. nov. d?c. as you can see shortened form for mars = mars.

Categories : Java

Java Date Math Issue
What is the meaning of the Date fields in your job object? I get the feeling you're trying to represent a "time of day" with a date object. This is probably not a good idea. If you want a job to run 6 hours into the day, I would store a long that represents 6 hours in millis: static final long ONE_HOUR = 1000L * 60L * 60L; Date today = DateUtil.getToday(); Date todayExecTime = new Date(today.getTime() + 6 * ONE_HOUR); Of course, if your locale uses daylight saving time, this method could be off by an hour twice per year (if your exec time is after the change in time, which is usually early in the morning). If you just want JobA to run 6 hours into the day (rather than running at 6:00AM) it won't matter. If this is a small piece of a more complicated scheduling system, you mig

Categories : Java

buffering issue with java communicating vlc
I looks like I always find the answer to my questions after I publish them to stackoverflow... DOUBLE CRLF should stand after the last header for the usual RTSP protocol 9not the customized one used in the example).

Categories : Java

simpleXML deserialization issue in java
I believe you need to add another field and annotate with @Text, like this example

Categories : Java

Java & MySQL timzone issue
Right, if you can fix the string to not include the time zone, it's simpler. Firstly, you need to understand that a Date object doesn't contain a time zone at all - it's just a point in time. Next, as we're trying to parse a date/time specified in UTC, you should set that in the SimpleDateFormat: DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); dfm.setTimeZone(TimeZone.getTimeZone("UTC")); Now at that point I'd hope that JPA would do the right thing. You'd at least be passing the right value to the Timestamp constructor. However, this part of the MySQL documentation makes me nervous: MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATET

Categories : Java

Encoding issue with System.out in Java
Your implementation of OutputStream is wrong: you pretend that write(int) receives characters, but in fact it receives raw bytes. If you check out PrintStream, you'll see that its print and append methods first apply encoding and then eventually call write(int) for each encoded byte. You shoud not attempt to transfer raw bytes back to the string in your TextArea. Instead implement PrintStream and its character-based methods and shove those strings/char arrays directly into the UI component.

Categories : Java

Java - Hibernate - mappedBy issue
I think you might want to map like this: public class TransactionNoteDW extends DateAuditableBean { //.... @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "patient_id") private PatientVisitTransaction patient; } public class PatientVisitTransaction extends Bean { //.... @OneToMany(fetch = FetchType.LAZY, mappedBy = "patient") List<TransactionNoteDW> notes; }

Categories : Java

Issue with .equals() function in Java
Here's how to debug such an issue. Call the following method with the two strings that look equal but are not: public void dumpString(String s) { System.out.println("Length: " + s.length()); // check their length System.out.println("Value: >" + s + "<"); // check trailing and leading spaces System.out.println("numeric value of characters:"); // check which char differs for (int i = 0; i < s.length(); i++) { System.out.print((int) s.charAt(i)); System.out.print(' '); } } Using a debugger lets you access the same information.

Categories : Java

Java issue with regular expression
Your regular expression will match a filename consisting of exactly 17 digits (0 to 9) ending with ".zip". If your code is allowing longer filenames through, then it's likely to be the fault of the code that uses it, not the regex itself. Can you post some of your code as well?

Categories : Java

java garbage collection issue
You don't need to do anything. As long as the entire object graph is not referenced by any rooted objects, the GC will collect the whole thing automatically. A rooted object is an object the is guaranteed to not be collectible – an object referenced by a static field or by an active stack frame in any thread.

Categories : Java

Java- double variable issue
The issue you deal with is representation error. Type double can not represent some values. Typical solution for this situation is usage of BigDecimal or Integer type.

Categories : Java

Java semi-colon issue
this.logger.info(pdfFile.getName() + " Version " + pdfFile.getVersion() + (" Has Been Enabled!"); should be this.logger.info(pdfFile.getName() + " Version " + pdfFile.getVersion() + " Has Been Enabled!"); You have an extra starting bracket at which needs to be removed (" Has Been Enabled!") ^^^ //Above causing error

Categories : Java

Java applet issue with painting
Tried using paintComponent instead of paint? (replace paint with paintComponent). Also, read about double buffering and why you need it: http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

Categories : Java

writing a file issue in java
Look at the javadoc Throws: FileNotFoundException - If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file SecurityException - If a security manager is present and checkWrite(file.getPath()) denies write access to the file UnsupportedEncodingException - If the named charset is not supported You need to deal with the Exception which the constructor might throw . If you want to declare the PrintWriter as static then you need to use static initializer block. static PrintWriter pw ; static { try{ pw = new PrintWriter("Results.txt", "UTF-8"); } catch(IOException e){ e.printStackTrace(); throw new Runt

Categories : Java

Issue with STAX parsing in Java
The trouble is you create Employee record for dist elements. if ("dist".equals(reader.getLocalName())){ currEmp = new Employee(); currEmp.id = reader.getAttributeValue(null, "id"); } This is followed my multiple employee definition. Effectively making the last element data into Employee record. I would store the id into a variable, say currentDistID and use it with Employee. The employee record should be created for each employee element. code public static void main(String[] args) throws XMLStreamException, FileNotFoundException { List<Employee> empList = null; Employee currEmp = null; XMLInputFactory factory = XMLInputFactory.newInstance(); String currentDistID=null; InputStream inputStream= new FileInputStream("c:\

Categories : Java

Java- starting thread issue
You're modifying shared variables from a thread, and reading them from another, without any kind of synchronization. That's wrong. Every access to a shared variable must be done in a synchronized way, or thread-safe objects (like AtomicInteger for example) should be used. Moreover, the thread modifies the x value in a loop, but never calls repaint(), so there's no reason for the panel to repaint itself.

Categories : Java

java collection sort issue
If two values x and y have the same openTime, then compare(x, y) and compare(y, x) will both return 1, which violates the contract of compare: The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. You haven't ensured that. You need to consider what you want to happen when the openTime values are the same - either return 0, or have some consistent notion of which value should come before the other. Do you have some secondary comparison you could perform, for example?

Categories : Java

Issue Using Java AWT Robot class
I wouldn't be completely surprised if this were forbidden by the OS or environment; however, have you tried adding robot.keyRelease events? At the moment it's as though you're holding the keys down forever. This may be insufficient to fire the appropriate key up/down/press events that the OS uses to recognise this key combination.

Categories : Java

Java Beginner Program Help (if, else issue)
Always use String#equals to compare Strings. == will compare if the references are equal which doesn't really work for comparing equal strings due to how they are stored. if (reverse.equals(word))

Categories : Java

Eclipse java/ant checkstyle issue
which checkstyle should be used/configured in Eclipse? The checkstyle rule LeftCurly defines the placement of left curly braces: eol: The brace must always be on the end of the line. nl: The brace must always be on a new line. nlow: Apply either eol or nl depending on the length of the line. See also the LeftCurly rule in the Block Checks category and the Lcurly property.

Categories : Java

issue with regular expression in java
Why not just use an XML Parser? Element docElem = document.getDocumentElement(); NodeList children = docElem.getChildNodes(); List<String> values = new ArrayList<String>(); for(int x = 0; x < children.getLength(); x++) { // Do what you want with children. That came out wrong. }

Categories : Java

java factory pattern issue
As Jayan mentioned, you should have got a NPE since you are passing null to the getWebDriver method. However, keeping that aside, in your code, you are reading a string using scan.next() statement, but you haven't assigned the read value to the variable type. Saying that, your statement should be as below: Scanner scan = new Scanner(System.in); type = scan.next(); Apart from that, I don't see any use of passing type variable to the getWebDriver method, as you are anyhow, taking the input from user for type in getWebDriver method.

Categories : Java

Issue with Outputing Variables in Java
else System.out.println (num1); System.out.println (num2); needs an opening brace: else { System.out.println (num1); System.out.println (num2); } The code overall(since you're losing your braces everywhere) should read: import java.util.*; public class HigherNumber{ public static void main (String[] args){ int num1 = 0; int num2 = 0; Scanner scannum1 = new Scanner (System.in); Scanner scannum2 = new Scanner (System.in); System.out.print("Enter your first number: "); num1 = scannum1.nextInt(); scannum1.close(); System.out.print("Enter your second number: "); num2 = scannum2.nextInt(); scannum2.close(); if (num1 > num2) { System.out.println (num2); Sys

Categories : Java

Java Date Format Issue
You are using int literals instead of long in your numbers. By default a integral literal is int unless you specify that is long with L at the end. Try this: Date d1 = new Date(1000*1373604190L); (note the L at the end of your literal 1373604190)

Categories : Java

Java starting thread issue
if(shoot) thread.start(); => } After you start your application, it creates a new JFrame, sets its size etc., creates a Thread instance, checks if shoot is true, it is false thus does not start the thread. Afterwards it waits at the point provided above for JFrame to be closed. When you click shoot, your application is still waiting at that point so it never checks if shoot is true or false. What you can do instead would be moving the code above into your key listening method. Don't forget to move shoot into appropriate place too.

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.