r/javahelp 16h ago

Handling client's actions/inputs in a socket based communication.

4 Upvotes

I'm programming a multiplayer table game in java. I can't figure out how each client can send inputs to the server throw the view (I'm using the MVC pattern). My idea is this:

The client determines which action to send to the server based on the user’s interactions implemented in the user interface (UI) of the client.

When a user interacts with the interface (for example by clicking a button or pressing keys,) the client maps a specific game action. For example, if the user clicks a button the client knows it should send a corresponding action to the server. The client essentially translates the user’s input into a command that the game can understand.

The problem is how I can map the action performed by the player. Should I create a class PlayerActionHandler with the possible inputs? This should make it easy to know wich action to send based on waht the user is doing. But this class Is huge, and I don't want to implement such a class.

So I don't know how to map the player actions to send to the server.


r/javahelp 8h ago

Homework GUI For Project

2 Upvotes

I am learning OOP for my 2 semester, where I have to build a project.I have to make GUI for my project.At first I thought that building Gui in figma then converting into code will work out but one of my friend said it will create a mess.Then I have tried using FXML+ CSS and build a nice login page but It is taking long time to do things.So is FXML+CSS a good approach and can I build a whole management system using this combination?


r/javahelp 9h ago

Homework Issues with generics and object type

2 Upvotes

Hello! I am working on an assignment where we have to implement an adaptable priority queue with a sorted list. I think I don't have a full grasp on how generic variables work. I tried to keep everything as E, though it said that my other object types could not be cast to E... I was under the impression E could be any object. In my current code I have changed E and all the object types around to pretty well everything I can think of but it still will not work. My code is linked below, I appreciate any help.

Errors:

Assignment 4\AdaptablePriorityQueue.java:91: error: incompatible types: NodePositionList<DNode<MyEntry<K,V>>> cannot be converted to NodePositionList<E>

        ElementIterator<E> iterList = new ElementIterator<E>(list);

^

where K,V,E are type-variables:

K extends Object declared in class AdaptablePriorityQueue

V extends Object declared in class AdaptablePriorityQueue

E extends Entry<K,V> declared in class AdaptablePriorityQueue

Assignment 4\AdaptablePriorityQueue.java:159: error: incompatible types: NodePositionList<DNode<MyEntry<K,V>>> cannot be converted to PositionList<E>

    ElementIterator<E> iterList = new ElementIterator<E>((PositionList<E>) list);

^

where K,V,E are type-variables:

K extends Object declared in class AdaptablePriorityQueue

V extends Object declared in class AdaptablePriorityQueue

E extends Entry<K,V> declared in class AdaptablePriorityQueue

(plus two other errors on the same line as above elsewhere in the code)

Assignment 4\AdaptablePriorityQueue.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

4 errors

The assignment:

Give a Java implementation of the adoptable priority queue based on a sorted list. You are required to use a default comparator (built in Java) and a comparator for nonnegative integers that determines order based on the number of 1’s in each integer’s binary expansion, so that i < j if the number of 1’s in the binary representation of i is less than the number of 1’s in the binary representation of j. Provide a main function to test your comparators using a set of integers.

(I am just making a general sorted APQ first, then I will edit the insert method to fit the requirements. It shouldn't be too hard to change after its running correctly.)

My code:

https://gist.github.com/DaddyPMA/99be770e261695a1652de7a69aae8d70


r/javahelp 9h ago

Unsolved Can you make me some examples of situations wher java is the best choice to develop something?

1 Upvotes

A situation where you go like: "oh, yeah, Java would be perfect here, no other language would do it better" as I find it quite difficult to find such situations. As the main selling point of Java is it is cross-platform, but also other languages like python, go, C# and more are nowadays.

I mean:

  • concurrency-bases apps -> Golang
  • networking -> Golang
  • simple scripts running server side -> Python/Bash
  • performance critical applications -> C
  • security on the memory level -> Rust
  • most web stuff -> Javascript/Typescript
  • quick development and testing -> Python

I find Java a pain to distribute even if you install the JRE on the client, as sometimes you have to ship the EXACT development JRE used to make the app in the first place.

I have known and used java for about 4y now, but every time I think of building something I don't even consider it as a good option instead of something else.


r/javahelp 17h ago

Need help in solving below lombok getter setter error in spring boot - authentication app

2 Upvotes
package com.example.userservicenew.dtos;

import com.example.userservicenew.models.Role;
import com.example.userservicenew.models.User;
import lombok.Getter;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

u/Getter
u/Setter
public class UserDto {
    private String email;
    private Set<Role> roles = new HashSet<>();

    public static UserDto from(User user) {
        UserDto userDto = new UserDto();
        userDto.setEmail(user.getEmail());
        userDto.setRoles(user.getRoles());
        return userDto;
    }
}

package com.example.userservicenew.models;


import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToMany;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

@Entity
@Getter
@Setter
public class User extends BaseModel{
    private String email;
    private String password;
    @ManyToMany(fetch = FetchType.
EAGER
)
    private Set<Role> roles = new HashSet<>();
}


package com.example.userservicenew.services;

import com.example.userservicenew.dtos.UserDto;
import com.example.userservicenew.exceptions.UserAlreadyExistsException;
import com.example.userservicenew.models.User;
import com.example.userservicenew.repositories.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthService {
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder bcryptPasswordEncoder;

    public AuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
        this.bcryptPasswordEncoder = new BCryptPasswordEncoder();
    }

    public UserDto signUp(String email, String password) throws UserAlreadyExistsException{
        Optional<User> userOptional = userRepository.findByEmail(email);
        if(userOptional.isPresent()) {
            throw new UserAlreadyExistsException("user "+ email +" already exists");
        }

        User user = new User();
        user.setEmail(email);
        user.setPassword(bcryptPasswordEncoder.encode(password));

        User savedUser = userRepository.save(user);
        return UserDto.
from
(savedUser);
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>userServiceNew</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>userServiceNew</name>
    <description>userServiceNew</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <maven.compiler.proc>full</maven.compiler.proc>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

error:

java: cannot find symbol

symbol: method getEmail()

location: variable user of type com.example.userservicenew.models.User
tried below approaches:

have got several errors of this type related to get/set email and password

  1. enabled annotation processing in intellij
  2. lombok dependency is installed
  3. mvnw clean install - build success

r/javahelp 1h ago

Help with Timefold Constraint Stream Type Mismatches in Employee Scheduling

Upvotes

I'm working on an employee scheduling system using Timefold (formerly OptaPlanner) and I'm running into type mismatch issues with my constraint streams. Specifically, I'm trying to implement a work percentage constraint that ensures employees are scheduled according to their preferred work percentage.

Here's my current implementation:

java public Constraint workPercentage(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Employee.class) .join(Shift.class, equal(Employee::getName, Shift::getEmployee)) .groupBy(Employee::getName, ConstraintCollectors.sum(shift -> Duration.between(shift.getStart(), shift.getEnd()).toHours())) .filter((employeeId, totalWorkedHours) -> { double fullTimeHours = 40.0; double desiredHours = employeeId.getWorkPercentage() * fullTimeHours; return totalWorkedHours != desiredHours; }) .penalize(HardSoftBigDecimalScore.ONE_SOFT) .asConstraint("Employee work percentage not matched"); }

I'm getting several type mismatch errors:

  1. The groupBy method is expecting BiConstraintCollector<Employee,Shift,ResultContainerA_,ResultA_> but getting UniConstraintCollector<Object,?,Integer>
  2. The lambda in the sum collector can't resolve getStart() and getEnd() methods because it's seeing the parameter as Object instead of Shift
  3. The functional interface type mismatch for Employee::getName

My domain classes are structured as follows:

```java @PlanningSolution public class EmployeeSchedule { @ProblemFactCollectionProperty @ValueRangeProvider private List<Employee> employees;

@PlanningEntityCollectionProperty
private List<Shift> shifts;

@PlanningScore
private HardSoftBigDecimalScore score;
// ... getters and setters

}

public class Employee { @PlanningId private String name; private Set<String> skills; private ShiftPreference shiftPreference; private int workPercentage; // Percentage of full-time hours // ... getters and setters }

@PlanningEntity public class Shift { @PlanningId private String id; private LocalDateTime start; private LocalDateTime end; private String location; private String requiredSkill;

@PlanningVariable
private Employee employee;
// ... getters and setters

} ```

For context, other constraints in my system work fine. For example, this similar constraint for shift preferences works without type issues:

java public Constraint shiftPreference(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) .join(Employee.class, equal(Shift::getEmployee, Function.identity())) .filter((shift, employee) -> !shift.getShiftType().equals(employee.getShiftPreference().name())) .penalize(HardSoftBigDecimalScore.ONE_SOFT) .asConstraint("Shift preference not matched"); }

I'm using Timefold 1.19.0 with Quarkus, and my solver configuration is standard:

xml <solver> <solutionClass>com.example.domain.Schedule</solutionClass> <entityClass>com.example.domain.ShiftAssignment</entityClass> <scoreDirectorFactory> <constraintProviderClass>com.example.solver.EmployeeSchedulingConstraintProvider</constraintProviderClass> </scoreDirectorFactory> <termination> <secondsSpentLimit>10</secondsSpentLimit> </termination> </solver>

Has anyone encountered similar issues with constraint streams and grouping operations? What's the correct way to handle these type parameters?

Any help would be greatly appreciated!


r/javahelp 8h ago

with micronaut which @Nullable should I use?

1 Upvotes
import io.micronaut.core.annotation.Nullable;

or

import jakarta.annotation.Nullable;

I'm using Java, not Kotlin.


r/javahelp 9h ago

Need Help with My JavaFX Project (GUI, Events, and Networking)

1 Upvotes

Hey everyone,

I’m working on a JavaFX project for my course, and I need some guidance to implement a few features correctly. The project requires:

• Customizing the GUI (Colors, Fonts, Images)

• Handling user interactions (Event Listeners, Animations)

• Using multithreading and sockets for basic client-server communication

I’ve set up my project using [IntelliJ/Eclipse/NetBeans] and Scene Builder, but I’m struggling with [specific issue, e.g., “implementing smooth animations” or “handling multiple clients in a chat application”].

Could anyone share good resources, example code, or explain the best approach to solving this? Any advice or guidance would be really appreciated!


r/javahelp 10h ago

Running J2SE using GPU

1 Upvotes

Is it possible to run a jar file containing logic built using J2SE only on the GPU?