Im developing a system that stores courses that participants can apply to.
I'm presenting the enrollments in a JTree in the courseadministratorGUI.
My problem is that, for every enrollment it's adding a new courseNode.
Been trying for many hours, and hope I can now get some advice that will point me in the correct direction.
Thank you.
private void updateJTree() {
for (Category cat : catcontrol.getAllCategoriesList()) {
category = new DefaultMutableTreeNode(cat);
for (Course c : ccontrol.getAllCourses()) {
if (cat.getIdCategory() == c.getIdCategory()) {
for (Enrollment e : econtrol.getAllEnrollments()) {
if (e.getIdCourse() == c.getIdCourse()) {
if (cat.getIdCategory() == c.getIdCategory() && e.getCourse().equals(c)) {
root.add(category);
}
if (c.getIdCourse() == e.getIdCourse()) {
course = new DefaultMutableTreeNode(c);
category.add(course);
enrollment = new DefaultMutableTreeNode(e.getParticipant().getFirstNames());
course.add(enrollment);
}
}
}
}
}
}
jTree1.setModel(new DefaultTreeModel(root));
jTree1.addTreeSelectionListener(this);
jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}
I am not sure I understand the question, but... why "for every enrollment it's adding a new courseNode"? Because you're telling it to. Right here:
course = new DefaultMutableTreeNode(c);
category.add(course);
enrollment = new DefaultMutableTreeNode(e.getParticipant().getFirstNames());
course.add(enrollment);
Add course, then add an enrollment. Always in pairs. Now I don't know the structure of your data, but I dare say that is not what you want. Can you describe in more detail what Enrollment is (one person? list of people? something else?), and what getParticipant() returns, and what do you want to appear in the tree?
One more comment - you do realise that these two if statements check the same thing, right? You can get rid of the inner one, since it's not doing anything. Or, more likely, rewrite to do something useful (however, as I said, I am not too sure what it is you want to do).
if (e.getIdCourse() == c.getIdCourse()) {
// ...
if (c.getIdCourse() == e.getIdCourse()) {
Related
I am trying to complete a programming task where I load a URL with information on the 2012 NFL team players. I am using a Hashmap (playerIndfo) where the key is 'team' and the values is an arraylist of all the 'PlayerData' (playersInfo). Currently I have written:
if(playerInfo.containsKey(team)) {
playerInfo.get(team).add(player);
}
else {
playersInfo.add(player);
playerInfo.put(team, playersInfo);
}
This seems to add every player to every team, proven by if I attempt to print out information for a certain key, every player is listed. Any help would be appreciated!
I think you have the same playersInfo list for all players. You should create a new one for each team.
if (playerInfo.containsKey(team)) {
playerInfo.get(team).add(player);
} else {
List<Player> playersInfo = new ArrayList<>();
playersInfo.add(player);
playerInfo.put(team, playersInfo);
}
if(playerInfo.containsKey(team)) {
playerInfo.get(team).add(player);
}
else {
List<PlayerData> playersInfo = new ArrayList<>();
playersInfo.add(player);
playerInfo.put(team, playersInfo);
}
Pardon me as I'm quite a beginner in coding. I have tried researching for ways to add some missing record into the lists but still can't seem to fit it correctly into my code.
I have two ArrayLists with different resultsets. Say, the first one is derived in other method and stored in abcList. This list is then used in my current fixChartStats method as a param.
In my code, I will check for the corresponding record in abcList with the second list I derive from the hql query in fixChartStats method.
If the record corresponds, then I'll do the necessary action as shown below to update the ApprovedCount number etc, else i set it to 0.
How do I go about adding the records that are missing in second list I got into the first arraylist (i.e. abcList)? Can anyone here shed some light? Do let me know if my questions are unclear. Thanks in advance, guys!
private void fixChartStats(List<TAbcModel> abcList, Map<String, Object> param, List<IssueModel> issueList, List<DestModel> destList) throws Exception {
//initialize the hql query
//translate all fields from Object[] into individual variable
firstRow = true;
for (TAbcModel abc : abcList) {
if (abc.getId().getAbcYear() = abcYear &&
abc.getId().getAbcMonthId() = abcMonthId &&
abc.getId().getAbcApplAccnId().getAccnId().equalsIgnoreCase(abcApplAccnId.getAccnId()) {
if (firstRow) {
abc.setApprovedCount(abcApprovedCount);
abc.setCancelledCount(abcCancelledCount);
firstRow = false;
} else {
abc.setApprovedCount(0);
abc.setCancelledCount(0);
}
}else{
// How to do the necessary here
// Below is what I've tried
abcList.add(abc);
}
}
}
When I debug, I noticed that it was added into the list. But soon after it was added, ConcurrentModificationException was thrown.
Create a local list and add missing records to it then add all elements from the local list to the abcList
List<TAbcModel> temp = new ArrayList<>();
in your loop:
} else {
temp.add(abc);
}
after loop
abcList.addAll(temp);
I'm back again.
Today I have a question that many people have asked before. The reason I'm asking again is because in all my ~90 minutes of searching, I couldn't find an updated answer. Many answers tell me to use iTag/TagAPI, but I ran into some problems trying to use that, therefore I would not like to use iTag/TagAPI. I'm trying to use packets, and I found one answer, but it too was outdated.
EntityPlayer entityP = ((CraftPlayer) p).getHandle();
entityP.displayName = args[0];
for (Player a: Bukkit.getOnlinePlayers()) {
if (!p.getUniqueId().equals(a.getUniqueId()))
((CraftPlayer) a).getHandle().playerConnection.sendPacket(new PacketPlayOutNamedEntitySpawn(entityP));
}
Here's that thread I was going off of: https://bukkit.org/threads/change-player-name-above-head.162356/
Any help is appreciated!
It is possible to achieve this in 1.8. For convenience, I used ProtocolLib and PacketWrapper.
Since the 1.8 update, the NamedEntitySpawn packet has been modified and changing player's name by modifying that has been no longer supported.(ref)
But this post gave a reference: we can use packet PlayerInfoData. I did some testing, and here's the result(tested against 1.9.2):
Here's the code:
Player theGuyToChangeNameFor = Bukkit.getPlayer("theguy");
PlayerInfoData pid = new PlayerInfoData(WrappedGameProfile.fromPlayer(theGuyToChangeNameFor), 1,
EnumWrappers.NativeGameMode.SURVIVAL,
WrappedChatComponent.fromText("whatever_string"));
WrapperPlayServerPlayerInfo wpspi = new WrapperPlayServerPlayerInfo();
wpspi.setAction(EnumWrappers.PlayerInfoAction.REMOVE_PLAYER);
wpspi.setData(Collections.singletonList(pid));
for(Player p : Bukkit.getOnlinePlayers())
{
if(p.equals(theGuyToChangeNameFor))
{
continue;
}
p.hidePlayer(theGuyToChangeNameFor);
wpspi.sendPacket(p);
}
ProtocolLibrary.getProtocolManager().addPacketListener(
new PacketAdapter(this, PacketType.Play.Server.PLAYER_INFO)
{
#Override
public void onPacketSending(PacketEvent event)
{
if(event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER)
{
return;
}
PlayerInfoData pid = event.getPacket().getPlayerInfoDataLists().read(0).get(0);
if(!pid.getProfile().getName().toLowerCase().equals("theguy")) // Here you can do something to ensure you're changing the name of the correct guy
{
return;
}
PlayerInfoData newPid = new PlayerInfoData(pid.getProfile().withName("HEAD_NAME"), pid.getPing(), pid.getGameMode(),
WrappedChatComponent.fromText("TAB_LIST_NAME"));
event.getPacket().getPlayerInfoDataLists().write(0, Collections.singletonList(newPid));
}
}
);
for(Player p : Bukkit.getOnlinePlayers())
{
if(p.equals(theGuyToChangeNameFor))
{
continue;
}
p.showPlayer(theGuyToChangeNameFor);
}
Explanation:
We use ProtocolLib to modify the PlayerInfoData packets from the server to change the player's display name. (You can see that name tag and tab list name can even be two different values!)
hidePlayer, showPlayer and REMOVE_PLAYER are used to refresh the player's name immediately(otherwise it will require logging out and in again). So far haven't found a better method. If you have one, say it:)
I've got a database of playerdata that has some pre-existing fields from previous versions of the program. Example out-dated document:
{
"playername": "foo"
}
but a player document generated under the new version would look like this:
{
"playername": "bar",
"playercurrency": 20
}
the issue is that if I try to query playercurrency on foo I get a NullPointerException because playercurrency doesn't exist for foo. I want to add the playercurrency field to foo without disturbing any other data that could be stored in foo. I've tried some code using $exists Example:
players.updateOne(new Document("playername", "foo"), new Document("$exists", new Document("playername", "")));
players.updateOne(new Document("playername", "foo"), new Document("$exists", new Document("playercurrency", 20)));
My thought is that it updates only playercurrency because it doesn't exist and it would leave playername alone becuase it exists. I might be using exists horribly wrong, and if so please do let me know because this is one of my first MongoDB projects and I would like to learn as much as I possibly can.
Do you have to do this with java? Whenever I add a new field that I want to be required I just use the command line to migrate all existing documents. This will loop through all players that don't have a playercurrency and set it to 0 (change to whatever default you want):
db.players.find({playercurrency:null}).forEach(function(player) {
player.playercurrency = 0; // or whatever default value
db.players.save(player);
});
This will result in you having the following documents:
{
"playername" : "foo",
"playercurrency" : 0
}
{
"playername" : "bar",
"playercurrency" : 20
}
So I know that it is normally frowned upon on answering your own question, but nobody really posted what I ended up doing I would like to take this time to thank #Mark Watson for answering and ultimately guiding me to finding my answer.
Since checking if a certain field is null doesn't work in the MongoDB Java Driver I needed to find a different way to know when something is primed for an update. So after a little bit of research I stumbled upon this question which helped me come up with this code:
private static void updateValue(final String name, final Object defaultValue, final UUID key) {
if (!exists(name, key)) {
FindIterable iterable = players.find(new Document("_id", key));
iterable.forEach(new Block<Document>() {
#Override
public void apply(Document document) {
players.updateOne(new Document("_id", key), new Document("$set", new Document(name, defaultValue)));
}
});
}
}
private static boolean exists(String name, UUID key) {
Document query = new Document(name, new Document("$exists", true)).append("_id", key);
return players.count(query) == 1;
}
Obviously this is a little specialized to what I wanted to do, but with little revisions it can be easliy changed to work with anything you might need. Make sure to replace players with your Collection object.
I have a set of classes that implement a particular interface and I have a set of checkboxes. I want to throw an error if no checkboxes are selected. If atleast one or more checkboxes are selected, then it should create objects associated with that checkbox.
This is how I done.
interface U { ... }
class A implements U { ... }
class B implements U { ... }
class C implements U { ... }
class Main {
//....
//....
public void findSelectedCheckBoxesAndCreateObjects() {
if(!(checkboxA.isSelected() || checkboxB.isSelected() || checkboxC.isSelected()) {
System.out.println("No checkboxes selected");
return;
}
//if any selected, create associated object
if(checkboxA.isSelected()) new A(file);
if(checkboxB.isSelected()) new B(file);
if(checkboxC.isSelected()) new C(file);
}
}
Now I have 3 problems.
This is just a sample code. Original has 8 checkboxes and classes with more coming.
I can't keep adding || checkboxD.isSelected() every time I have a new class for checking it.
Same thing. I can't keep adding if(checkboxD.isSelected()) new D(file); for every class.
It is very inelegant. Can I have some kind of loop that removes the redundant code?
Please give me your suggestions.
Thank you.
You should use a collection structure to hold your checkboxes and those related classes.
Using a Map you could do something like this:
Map <JCheckBox,Class<U>> uCheck = new HashMap<JCheckBox,Class<U>>();
// add your checkboxes and U-classes to the map
uCheck.put(checkBoxA, A.class);
Now, it's quite easy to get a collection of the classes that need to be instantiated based on the checkbox status:
public Collection<Class<U>> getEnabledClasses(<JCheckBox,Class<U>> checkMap) {
List<Class<U>> result = new LinkedList<Class<U>>();
for (Map.Entry<JCheckBox,Class<U>> entry:checkMap.entrySet()) {
if (entry.getKey().isSelected()) {
result.add(entry.getValue());
}
}
}
Now, a call to getEnabledUs(uCheck) returns a collection of the selected classes. If the collection is empty, there's no selection, hence nothing to do.
for (Class<U> u:getEnabledClasses(...)) {
Constructor<U> cons = u.getConstructor(...);
U instance = cons.newInstance(fileparameter);
instance.doSomething(...);
}
That should get you started.
(*) Disclaimer: this is non-tested code. Rather pseudo-code with crisp detail only where needed.