There is an issue with the functionality of Java code that has been adapted from Javascript logic

I'm currently using NetBeans8 IDE.

Check out this java script function from this Fiddle

 function animate() {
    xnow = parseInt(item.style.left);
    item.style.left = (xnow+1)+'px';
    ynow = parseInt(item.style.top);
    item.style.top = (ynow+Math.sin(2*Math.PI*(xnow/50))*10) + "px";
    setTimeout(animate,20);
}

The developer here creates a moving sine wave using JavaScript.

Following the same concept, with some minor modifications, I've written a Java program using timer t. The equation used is identical to the one above. However, my jRadioButton seems to be moving uncontrollably. Can a moving sine wave be achieved through this method?

Please assist me in resolving this issue. Thank you in advance.

Below is the snippet of my Java code:

Timer t = new Timer(10, new ActionListener() {                                                                                           
    @Override                                                                                                                           
    public void actionPerformed(ActionEvent e) {            
        // AL1 is the name given to radiobutton
        int xnow=AL1.getX()+1;
        int ynow=AL1.getY();
        ynow=(int) (ynow+Math.sin(2*Math.PI*(xnow/50))*10);
        AL1.setLocation(xnow, ynow);
    }                                                                                                                            
});  


private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    // TODO add your handling code here:
    AL1.setLocation(0, 200);
    t.start();
}


javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(Lpne, javax.swing.GroupLayout.DEFAULT_SIZE, 1030, Short.MAX_VALUE)
        .addContainerGap())
);
layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(Lpne, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
);

Could someone help bring my jRadioButton under control?

Thank you to everyone. This marks the final outcome.

https://i.sstatic.net/7xKeZ.png

Answer №1

There are two key issues affecting your logic:

  • Layout: It is crucial to place your Swing Component within a container component that has no layout, essentially acting as a plane without any layout restrictions.

  • Division: The division operator in programming accepts two operands and returns a value. The return type of the division operation is determined by the operand's types. For example, int / short returns an int, while float / int returns a float.

In JavaScript, there is only one type which is number (a set of real numbers), so the result will always be a real number. However, in Java, if you define both operands as int, the result must also be an int. This means that:

30 / 50 = 0;

To ensure a decimal result, you need to make one of the operands a real number. In Java, you can use the Float type for this purpose:

30 / 50F = 0.6;

Here, 50F is a constant float value.

If you modify the code like this:

// Code snippet

within a container like this:

// Container setup

Your logic will then function similar to JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to iterate through an array of objects in Javascript and extract an array of strings

I am dealing with an array of objects that looks like this: [{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}] My goal is to iterate through it and extract an array containing only the keys: ["aaa", "bbb", "ccc"] I am u ...

Missing dots on owl carousel

Currently, I am working on a project that involves using the owlcarousel library in javascript. Everything was running smoothly until I encountered an issue. Although I have set the dots to true in the code, they are not appearing on the carousel. Below i ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

No Angularjs redirection without the "onload" event

In my search for a solution, I came across this answer but it did not quite fit my needs: Pass onload event through redirect The issue I'm facing is that I want the AngularJS section of my application to reload something when the user is redirected ...

Determine the total number of hours along with the precise minutes

Could you assist me with calculating minutes? Here is an example: var time_in = '09:15'; var break_out = '12:00'; var break_in = '13:00'; var time_out = '18:00'; var date = '2018-01-31'; var morning = ( ...

Enhancing connections with JPA

I have recently started working with JPA in conjunction with spring boot and I am still learning about JPA. There are two entities that I am concerned with: User.java @Entity @Table(name = "user") @Data public class User { @Id @GeneratedValue(s ...

Anticipated a response in the form of an object, however, a string was delivered instead

After recently updating to v14 of discordjs, I've been encountering numerous errors, including the one below. It seems a lot has changed since my last coding session, and I'm a bit unsure about what modifications are needed to ensure this ping sl ...

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...

Convert JSON data into the desired format

My JSON input is as follows: [ { "date": { "value": "2022-05-01" }, "parent": { "value": "Choclate" }, ...

Refreshing a Node.js server page upon receiving a JSON update

My web application serves as a monitoring interface for tracking changes in "objects" processed by the computer, specifically when they exceed a certain threshold. The Node Js server is running on the same machine and is responsible for displaying data in ...

Update various components within a container

I have incorporated a function that automatically loads and refreshes content within a div every 10 seconds. Here is the script: $(function () { var timer, updateContent; function resetTimer() { if (timer) { window.clearTimeout(timer); ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

Collecting values using AJAX in Codeigniter from an input file

I have been exploring examples of AJAX code, and I noticed that when using form-data in AJAX, we need to serialize each element individually. While normal data serialization works fine, I encountered an issue when trying to pass the value of an input file ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Unable to retrieve the textual content from an anchor tag

How can I retrieve the text value of a link with "My account" as the anchor text? I'm looking to verify if I am logged in to a website by checking this specific string. I've been struggling to find the correct approach, despite trying various m ...

Clicking on a checkbox and subsequently removing validation through jquery

Situation : When the 'I am Fresher' checkbox is selected, I want to hide the 'Experience field', but still keep its validation visible so that my form cannot be submitted. My Requirement : When the 'I am fresher' checkbox is ...

Executing JavaScript code does not execute CSS code

Having some trouble with my Javascript and CSS. The script is functioning well, but when I use the filtering function, the CSS stops working and only the filtered results are displayed on the HTML page. Looking for advice on how to fix the Javascript. & ...

Custom Java tooltip created specifically for minimize button functionality

Currently, I am setting up a JFrame as shown below. JFrame f=new JFrame("Title"); f.setUndecorated(true); f.getRootPane().setWindowDecorationStyle(JRootPane.FRAME); But, I am looking for a way to present a personalized tooltip text for the JF ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...