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.

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

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

How to dynamically load a file based on the chosen option value in React

Two select textboxes on my page are named Choose City and Choose District. I also have some files related to cities and districts: // cities.js const cities = { "01": { "name": "City 1", "code": "01" }, ...

After selecting a delivery method, the checkout feature on opencart 1.5.6.4 is malfunctioning

Check out my online shop at store.suhaskhamkar.in. I've set it up using OpenCart version 1.5.6.4, but I'm facing an issue with the checkout process. It seems to get stuck at step #4, which is the Delivery method selection. Upon checking the conso ...

"The changes made to the list are not being accurately displayed by Angular's ng

I am working on a directive that injects dynamic templates during ng-repeat. While I can successfully add items to the list, they do not appear in the view for some reason. It seems like I am missing a crucial piece to make it work correctly. You can find ...

Unreliable Response from JEditable

I have encountered an unusual behavior while using the JEditable jQuery plugin to update data on my webpage. One specific field is not updating as expected, instead displaying the following message: EM29UPDATE NetLog SET grid = 'EM29&apo ...

Preserving CSS styling while loading an HTML page with InnerHTML

By using the following code snippet, I have successfully implemented a feature on my website that allows me to load an HTML page into a specific div container when clicking a link in the menu. However, I encountered an issue where the background color of ...

Implement a mouseover event on the axis label using D3.js and JavaScript

Is it possible to trigger a mouseover event on the y-axis label in a chart? For instance, let's say we have a scatter plot with labels "area1", "area2", and "area3" on the y-axis. When a user hovers over the label "area1", a tooltip should appear disp ...

What is the mechanism by which a custom hook, functioning as a trigger, initiates the re-rendering of a separate function component?

According to the official documentation on Custom React Hooks, one particular use case for utilizing a custom hook is demonstrated through the following example: function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); retur ...

Display the contents in a textarea with modal, not as a string

I'm currently working on implementing a modal overlay window with simplemodal that will display the contents of a text area. My goal is to show the rendered output rather than just the string value. For example, if a user enters HTML or includes an im ...

The perplexing problem of scrolling in Dojox/mobile/scrollableview

I've noticed some scroll issues with the dojox/mobile/ScrollableView (version 1.10+) in my cordova application, specifically on Android phones. This problem seems to be affecting other widget-based architectures and even some store apps as well. I wou ...

Obtain a URL using JavaScript's regular expressions

Is it possible to use JavaScript regex to fetch the first function parameter? For instance, when I click on a tag in this page element, how can I extract the inline link? Here's an example: <li><a href="#blog" data-rel="clos ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

Issue with Vue Loading Overlay Component functionality in nuxt2 .0

I've integrated the vue-loading-overlay plugin into my project. plugins/vueloadingoverlaylibrary.js import Vue from 'vue'; import Loading from 'vue-loading-overlay'; // import 'vue-loading-overlay/dist/vue-loading.css'; ...

What is the process for triggering events when the previous and next buttons are clicked?

Within the jQuery fullcalendar, there are previous and next buttons. Is there a way to trigger specific events when these buttons are clicked? ...

What could be causing the client to not receive the socket.io broadcast in the designated rooms?

My client isn't receiving the broadcast sent to the room. I have tried replacing socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser); and it works, but I prefer using rooms in this scenario. Any ass ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Adjust the canvas size to fit its parent element ion-grid

I am currently working on an Ionic 3 component that displays a grid of images connected by a canvas overlay. I have utilized Ionic's ion-grid, but I am facing an issue with resizing the canvas. The problem is that I cannot determine the correct dimens ...

JavaScript not properly rendering CSS styles

If I insert the following HTML statically, the CSS style is correctly applied. HTML: <li class="connector"> <a href="#"> <img src="css/images/temp/connector2.png" alt="" width="192" height="192"> <span class="sr-only"& ...

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...