Adding multiple instances of a JPanel class without replacing them

Currently, I am facing an issue where I have created a class that extends JPanel (shown below) and I am attempting to add multiple instances of this class to another JPanel.

public class DOBGui extends JPanel {
  private static String dayList[] = {bunch of days};
  private static JComboBox dobDay = new JComboBox(dayList);
  private static String monthList[] = {bunch of months};
  private static JComboBox dobMonth = new JComboBox(monthList);
  private static String yearList[] = {bunch of dates};
  private static JComboBox dobYear = new JComboBox(yearList);

  public static String DOBString() {

    int dayInt = dobDay.getSelectedIndex() + 1;
    int monthInt = dobMonth.getSelectedIndex() + 1;
    String year = dobYear.getSelectedItem().toString();

    String day = "" + dayInt;
    if (day.length() == 1) {
      day = "0" + day;
    }

    String month = "" + monthInt;
    if (month.length() == 1) {
      month = "0" + month;
    }

    return day + month + year;
  }

  public DOBGui() {
    add(dobDay);
    add(dobMonth);
    add(dobYear);
  }

  void reset() {
    dobDay.setSelectedIndex(0);
    dobMonth.setSelectedIndex(0);
    dobYear.setSelectedIndex(0);
  }
}

My problem arises when I try to add this JPanel to another JPanel twice by creating two instances of the DOBGui class, but it ends up overwriting the first one.

questionsPanel.add(new JLabel("Date for budget skills training session"), "wrap");
DOBGui budgetSkillsDate = new DOBGui();
budgetSkillsDate.reset();
questionsPanel.add(budgetSkillsDate, "wrap");

questionsPanel.add(new JLabel("Date for cooking course training session"), "wrap");
DOBGui cookingCourseDate = new DOBGui();
cookingCourseDate.reset();
questionsPanel.add(cookingCourseDate, "wrap");

Answer №1

The reason for this behavior is that all the fields you have defined are of static type. So when you invoke the reset method on panel1, it executes the following:

 void reset() {
    dobDay.setSelectedIndex(0);
    dobMonth.setSelectedIndex(0);
    dobYear.setSelectedIndex(0);
 }

Essentially, you are resetting the day, month, and year. Then you reset them back to their initial values. When you call reset on the second panel, you are essentially working with the same instance of dobDay, dobMonth, and dobYear since they are static fields.

Answer №2

To summarize, it is important that the fields are not static.

Static fields are not specific to individual objects but are shared across all instances of a class. For example, consider objects with serial numbers. Each object should have its own unique serial number, making the "serial number" field an instance field. However, the field containing the "next serial number to issue" belongs to the class and is used when creating new instances.

When you encounter the error "non-static XXX cannot be accessed from static context," it usually means you should be using an instance of the class rather than the class itself.

Consider the method DOBString(). Without proper documentation, it appears to return a string representation of the date selected by the object. Since each DOBGui object can have a different date, making this method static would not make sense. It should not be called on the class as a whole but on individual instances.

In conclusion, all elements specific to an individual panel (fields and methods) should not be static. This applies to both the fields and methods.

When it comes to event listeners, ensure that they are linked to the correct instance. If you want an event listener to display the date from a specific panel, it should call the DOBString() method on that particular instance, not on the class.

Remember, it is crucial that you work with instances of DOBGui, not the class itself. Instances represent specific dates, while the class should not be used to represent a date.

Additional Notes:

  • Methods should not begin with a capital letter. This convention is important for code clarity and syntax highlighting.
  • Adding more documentation to your code is highly recommended. Comments help others understand your intentions and make the code more maintainable.

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

Is it necessary to convert an HTMLCollection or a Nodelist into an Array in order to create an array of nodes?

Here we go again with the beginner guy. I'm working on this exercise from a book called "Eloquent JavaScript". The goal is to create a function similar to "getElementByTagName". However, the first function below is not returning anything and the secon ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Confirming user credentials for every page

I am currently working with an HTML page that includes front end PHP for server side scripting. One issue I have encountered is the configuration page, which can be accessed by disabling JavaScript in Mozilla settings. My current validation method relies ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

Unable to close expanded grid item using close button

Currently, I am working on a simple 3 column grid where each grid item consists of an image and a close button. The functionality I want to achieve is that when a grid item is clicked, the image should expand and the close button should become visible. Th ...

What is the process for obtaining a new token in a Linnworks embedded application?

I decided to share my issue on this platform since the support from Linnworks is virtually non-existent. My dilemma involves a private embedded app created within Linnworks that showcases orders in spreadsheet format. The app, constructed using Vue.js and ...

Rendering HTML is not supported by AngularJS on Android 19 with version 4.4.4 and Safari 8.0.5

I have been working on an AngularJS app that is being displayed in a Webview on Android. Everything was functioning properly until yesterday when I started encountering issues with Angular not rendering the DOM correctly. I have tested the app on various v ...

What mistakes am I making in this PHP code as I try to work with the select option?

Currently, I am developing a form that involves selecting values. If the user chooses 'yes', I want to display a text box section. However, the code below is not functioning as expected. <select id="gap" name="gap" onclick="gap_textbox();"> ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

Dynamically extract key values from JSON data and display them on an HTML page with checkboxes for selection. Generate a new JSON object containing

I am facing the challenge of parsing an unknown JSON with uncertain key-value pairs. As I do not have prior knowledge of the keys to access, my goal is to traverse through every key in the JSON and display all keys and their corresponding values on the scr ...

What is the reason for requiring CORS activation on the tomcat application?

I'm currently running an application on a tomcat 8 server, using a domain and an Angular web app. However, I've encountered some issues with the web app not functioning properly when trying to connect to the tomcat application without enabling fi ...

Experiencing receiving a null value for an XML-formatted string following the process of

I am new to android development and I am currently working on a project where I need to call a webservice that returns a JSON string as a response. This JSON string contains an XML formatted string as one of the entries. String jsoncontent=restTemplate.ge ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

Utilizing AJAX and JavaScript to generate a table using the AJAX response and placing it within a <div> element

I am currently passing the response of this action in text form, but I would like to display it in a table format. Is there a way to do this? function loadAditivos(){ $('#aditivoAbertoInformacoesTexto').html('<div id="loaderMaior ...

Moving data from one table to another and making changes or removing it

After successfully adding data from one table to another using .click, I encountered an issue. Whenever I utilize the search field in the top table, it clears the appended rows in the bottom table. I am looking for a solution to have these tables generate ...

Calculating Object's Position with Velocity Results in NaN

My goal is to have my canvas arcs (representing dog objects) follow the mouse cursor's movements. However, when I check the position or velocity of the objects using console.log, it shows Vector{ x: NaN, y: NaN} A strange observation is that if I di ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...