Im trying to make a java game where when the players health reaches 0 the game should end but currently when my progress bar reaches 0 nothing happens here is my code is there something wrong with it?
JProgressBar healthProgressBar = new JProgressBar();
lblHealth.setLabelFor(healthProgressBar);
healthProgressBar.setStringPainted(true);
healthProgressBar.setValue(100);
healthProgressBar.setMinimum(0);
healthProgressBar.setBounds(318, 103, 166, 20);
mainGame.add(healthProgressBar);
if(healthProgressBar.getValue() <= healthProgressBar.getMinimum())
{
frame5.setVisible(false);
frame7.setVisible(true);
}
You are actually checking it right after setting the value to 100, so it always returns false.
Instead, you can use a listener for example:
healthProgressBar.addChangeListener(e -> {
if (healthProgressBar.getValue() <= healthProgressBar.getMinimum()) {
frame5.setVisible(false);
frame7.setVisible(true);
}
});
Other way would be changing the frames where you set the value to the healthProgressBar.
You're calling this code,
if(healthProgressBar.getValue() <= healthProgressBar.getMinimum())
in the same region where you create your JProgressBar and not where the state of the JProgressBar is being changed, so it makes sense that the if block test will never be true. A solution is to call this if test where your JProgressBar is being changed. But also re-think your desire to swap JFrames. Instead the user is much better off if you would re-set a single game JFrame.
You are checking the value only once, when it is still 0
Related
list.getSelectionModel().addListSelectionListener(e -> {
timer = new Timer( DELAY, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0) {
StockItem p = list.getSelectedValue();
label.setText(p.toString2());
label.setLocation(label.getLocation().x+1, label.getLocation().y);
if(label.getLocation().x >= frame.getWidth()) {
label.setLocation(0-label.getWidth(),label.getLocation().y);
}
}
});
timer.start();
});
I created a list selection listener to check which current items are being selected inside of a JList, and whatever item is being selected will call a toString() method in another class and set this as the text for a JLabel. However, I just implemented moving text on my JLabel and every time an item in the JList is selected, the speed of the JLabel will increase. I would like it so the speed stays constant but i'm not sure how to do that.
The part of the code that controls the speed is
label.setLocation(label.getLocation().x+1, label.getLocation().y);
Any explanations would be very appreciated thank you
every time an item in the JList is selected, the speed of the JLabel will increase.
Because your code starts another Timer with each selection.
A Timer will keep running until you stop it. Since you never stop it you will have multiple Timers running at the same time.
You want to define your Timer outside of the ListSelectionListener.
Then the logic inside the listener becomes something like:
(if !timer.isRunning())
timer.start();
Or the question is do you even need the ListSelectionListener?
You could just start the Timer automatically when you class is created. Each time it fires the logic will get the selected value.
Of course with this approach you need to make sure the getSelectedValue() method doesn't return null (as no item will be selected when the GUI is first displayed).
I have a UI in which I want to display a popup with a slider bar, with a message, and have the user be able to click OK or Cancel after choosing a value (or not). JOptionPane has various show methods that seem like they'd be useful, but I was unable to find much about making them do what I want.
This is actually a question that I had to root around to find an answer to, and I'll provide it below. I hope it will be useful to someone else.
The examples I was able to find had the standard flaw of examples: they weren't close enough to what I wanted to tell me how to do this, and didn't explain enough about how things worked to alter them on my own. I finally ran across a tutorial which explained that the "messages" in the dialog could be components, and the JOptionPane code would render them. This example uses a JSlider, I assume other JComponents could be used as well.
The documentation also talks about what to do if you want to "display the dialog directly", but I never did figure out what they meant by that.
I stumbled around in various forms of JOptionPane methods before figuring out the following:
/**
* display the dialog for entering the number of spots to move the first
* marble chosen after a 7 is played. Returns 0 if the user cancelled this
* operation.
*/
#Override
public int getMoveCount()
{
int moveCount = 0;
JSlider slider = createSlider();
JPanel sliderPanel = createSliderPanel("myMessage", slider);
String title = "myTitle";
int dialogResponse = JOptionPane.showOptionDialog
(this, // I'm within a JFrame here
sliderPanel,
title,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null
);
if (JOptionPane.OK_OPTION == dialogResponse)
{ moveCount = slider.getValue(); }
else { moveCount = 0; } // works for cancel button, red 'x', and keyboard escape key
return moveCount;
}
private JSlider createSlider()
{
JSlider slider = new JSlider(1,7);
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setValue(7); // default to 7
return slider;
}
I'm trying to light up each time the image being pressed and in case if it's been pressed again I want it to go to the original lighting
// Effect To light up the image once it been pressed to green
Lighting lighting = new Lighting();
lighting.setDiffuseConstant(1.0);
lighting.setSpecularConstant(0.0);
lighting.setSpecularExponent(0.0);
lighting.setSurfaceScale(0.0);
lighting.setLight(new Light.Distant(45, 45, Color.GREEN));
// Effect to show the unavailable images which can't be pressed
Lighting lighting_red = new Lighting();
lighting_red.setDiffuseConstant(1.0);
lighting_red.setSpecularConstant(0.0);
lighting_red.setSpecularExponent(0.0);
lighting_red.setSurfaceScale(0.0);
lighting_red.setLight(new Light.Distant(45, 45, Color.RED));
// the original effect and the one to change back the green effect once it being pressed again
Lighting orginalLighting = new Lighting();
orginalLighting.setDiffuseConstant(1.0);
orginalLighting.setSpecularConstant(0.0);
orginalLighting.setSpecularExponent(0.0);
orginalLighting.setSurfaceScale(0.0);
orginalLighting.setLight(new Light.Distant(85, 85, Color.LIGHTGREY));
// To initialize the original imageview and set its original effect
for(int i = 0;i<30;i++){
seats[i] = new ImageView(seats_image);
seats[i].setEffect(orginalLighting);
}
for(int i=0;i<30;i++){
Node seat = seats[i];
seat.setOnMouseClicked(e->{
if(seat.getEffect()!=lighting_red){
seat.setEffect(lighting); }
if(seat.getEffect()==lighting){
seat.setEffect(orginalLighting); }
});
}
I wanted to change the image effect in case if is not red to green. And if I already press it and I press it again to the original effect but somehow once I press any image nothing change.
Hint: if I remove the second if, the image will change to green if I press it as long as it is not red. But once I added the second if nothing happen at all it seems like every time I press it change to the original which change nothing in the image
Your logic is wrong. Your current implementation is:
If the current effect is originalLighting, the first if condition will be true, so you change the effect to lighting.
Then the second if condition will also be true (since the effect is now lighting), so you immediately change the effect back to originalLighting.
You need something like:
if(seat.getEffect() == lighting) {
seat.setEffect(originalLighting);
} else if (seat.getEffect() == originalLighting) {
seat.setEffect(lighting);
}
(Note that if you lay your code out properly, these errors are much easier to see and fix.)
Creates a List<Integer> to store the ID of each image depending on the index and each time you press the image you run a method to check the ID then you make the change depending on the ID and the number of time the image was pressed:
1)-if the image is in the original state, then you increment in the list of 1 and apply the effect.
2)-if the image has already been pressed you decrement by 1 and you apply the effect.
//Create and initialize the List with a loop (length 30 images here)
List<Integer> pressCount = new ArrayList<>();
I have this loop
while (true) {
game.update();
view.repaint();
Thread.sleep(DELAY);
}
In the game.update various components of the game have their position changed and those updates are reflected when the repaint() method is called on the view. The view extends JComponent and loops through the game objects and calls their print methods.
What I want to do is have a boolean called nextLevel in the game and if it's true Flash text on the screen for the player to notify them that they're going onto the next level. Maybe flash 4-5 times. Then continue the game.
Is this possible? I have been playing around with Thead.Sleep() but this only seems to pause the displaying and in the background the game is still going on.
Any ideas on how to do this?
Maybe you want to avoid threading by using a Timer object.
an example like that could be
int flashTimer = 0;
if(nextLevel) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//flash something method here
flashTimer++;
}
});
timer.start();
}
and then check your flashTimer if it reaches the number you want then just stop the timer by timer.stop();
Just an idea which seems to me a bit simpler. the 1000 value is milliseconds which is passed and executes the code inside the actionPerformed method every 1 sec.
Hope it helped
I'd like to ask is it possible to stop knob moving further upon hit certain value in JScrollBar ?
For example, set the minimum and maximum value of a vertical scroll bar to 0 and 100. If the user scroll the knob till 60, he or she should not be able to move knob up further but able to move knob down.
Hence, I have simply wrote following adjust listener:
class MyAdjustmentListener2 implements AdjustmentListener
{
public void adjustmentValueChanged(AdjustmentEvent e)
{
label.setText("New Value is " + e.getValue() + " ");
if (e.getValue() < 60 )
{
vbar.setValue(60);
}
}
}
The label is a JLabel I used to monitor the adjusted value, the vbar is a vertical JScrollBar instance. Above code will force the knob jump back to value 60 if user try to move it above the value 60. This slightly different from what I want to achieve.
I have looked into the API of JScrollBar, I didn't found any straight method provided to use. Please share some hints to me here. Thank you for your time and suggestion.