JLabel coloring and making transparent - java

I'm trying to color and make transparent the same JLabel When I click on it.
int leftP=4; //initialized at start of code
if (leftP>0){
if (lbl.getBackground()!=Color.YELLOW){
lbl.setBackground(Color.yellow);
lbl.setOpaque(true);
leftP--;
}else{
lbl.setOpaque(false);
lbl.repaint();
leftP++;
}
}
The problem here is that when leftP>0 if checks if the Background of the Label is already Yellow. if it is ... it uncolor it but if its not it colors it.
It works for the first time.
I click on label and it becomes yellow and leftP=3.
I reclick on label it becomes without yellow color as background and leftP=4.
When I click the third time. I expect it to become Yellow with leftP=3 ... but unfortunately I don't understand why it remains without color and it continues entering in ELSE Loop whenever I click on label.

setOpaque() will not change the background color, so it is still yellow.
Try
lbl.setOpaque(false);
lbl.setBackground(Color.BLACK);
Or better use another marker, eg. your own variable.

Add a try catch statement and Remaint the label everytime after color change using lbl.repaint();
try{
int leftP=4; //initialized at start of code
if (leftP>0){
if (lbl.getBackground()!=Color.YELLOW){
lbl.setBackground(Color.yellow);
lbl.setOpaque(true);
lbl.repaint();
leftP--;
}else{
lbl.setOpaque(false);
lbl.repaint();
leftP++;
}
}
}catch(Exception ee){
ee.printStackTrace();
}

Related

Is there any way where a javafx button can listen from different event handlers?

Am new to javafx. I wanted to write a simple javafx program that when clicking a button for the first time, the color of a rectangle should change to something else, e.g green, and when clicking it for the second time, the color should change back to the original color.
But the button is only allowing a single click only?
Help if there is any solution on this.
Here is a code.
You can try using simple boolean value to check if color has been changed before:
boolean flag = false;
#FXML
private void onButtonClick(){
if (flag){
//change to e.g. red
} else {
//change to e.g. green
}
flag = !flag;
}
This code is simple and if you want only to change between two colors it will be enough :)

how to change background color back and forth eg red and green when clicked using only 1 jbutton

so what I'm trying to do is creating a button that when clicks, turns the background color to be green. once its clicked on again, it turns red. And repeat basically. So im looking for some help that show me how I can do this.
this is what I've done so far
class colorText implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Go")) {
panel.setBackground(Color.GREEN);
}
}
}
I tried doing it by doing this but I get an error and was wondering either how to get around it or a new a way of doing it
if (e.getActionCommand() == Color.GREEN) {
panel.setBackground(Color.RED);
}
Your attempted solution doesn't work because (as we can see from the first example), e.getActionCommand() returns a String - and likely will always return "Go" when they click on your button.
What you need is some way of determining the state; telling the difference between "I should make the background red now" and "I should make the background green now". There are two ways of doing this that come to mind:
1) Check the current background colour
If the API lets you query the background colour and compare against a constant, you could check it like so:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Go")) {
if (panel.getBackground() == Color.RED) {
panel.setBackground(Color.GREEN);
} else { // could check for GREEN background here
panel.setBackground(Color.RED)
}
}
}
Possible downsides to this approach:
You might not be able to (reliably) read back the colour that you set. Either it's not exposed in the panel's API, or the value you get back does not equate to the Color constants for some reason (e.g. the read value has an alpha channel while the constants do not)
This only works if this method is the only way that the background gets modified. If any other code were to modify the background, you'd not have an accurate record of what your previous button press did. This is potentially a big issue as it means this code doesn't play nicely with other functionality.
2) Store a flag and flip it each time
This approach involves storing an explicit field that lets you know what to set the background to next. This could just be a boolean, like so:
private boolean greenIsNext = true
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Go")) {
Color nextColour = greenIsNext ? Color.GREEN : Color.RED
panel.setBackground(nextColour);
// Flip the flag
greenIsNext = !greenIsNext
}
}
This is likely the cleaner way to handle this behaviour, as pressing the button will alternate between setting the background green and red regardless of what else is going on with the page.

changing the imageview effect on javafx

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<>();

Replacement of a JPanel element without adding to the end of the panel?

I posted a question earlier about this but the solution never worked and now it's under different circumstances. I'm making a "penny pitch" program, that, when the "confirm" button is pressed, a randomized number will dictate which spot on the board(the board is fill with image icons) the "penny" will fall, and in the process it removes the image icon that use to occupant the chosen space.
I set up a GridBagLayout to constrain each icon down, and my button has no problem removing the chosen spot, but it can not find a way for it to add a new icon in it's place. It just gets adds onto the end of the JPanel.
Heres my coding for the button:
private class AddListener implements ActionListener {
public void actionPerformed(ActionEvent a){
if (a.getSource()== confirm) {
if (numberToss >0){
thrown = pitch.nextInt(25) + 1;
System.out.println(thrown);
//kol is an array to check for repeated numbers in randomization
if (kol.contains(thrown)==false){
input.remove(spot.get(thrown));
//spot is a map to set icons down with a association with number
spot.put(thrown, bSet);
input.add((spot.put(thrown, bSet)));
repaint();
kol.add(thrown);
}
else {
JOptionPane.showMessageDialog(null, "Your toss landed onto an occupied spot; you receive no points");
}
numberToss--;
}
else{
JOptionPane.showMessageDialog(null, "Out of tosses.");
}
}
}
Anyone happen to know how to replace the new icon (bSet) with the former? Thanks in advance!

Controlling the background color of a JTextField with a mouse clicked event

I'm currently working on a program of mine for personal development as a programmer and I have hit a miniature brick wall of frustration on this mouseclicked event I'm working on. When I thought up the procedure in my mind and on the white board I saw it utilizing a switch statement to get the job done. I have met with no success with this plan. I have since experimented with a few other control structures, but nothing seems to work the problem is controlling the control structure inside the mouseClicked event. I'll provide some relevant example code to try to communicate my objective. Note that I know the provided code is bad. I'm just trying to communicate an idea.
The goal is to be able to have the box start out green, then the user can click the box turn it red, click again it goes white, and one last time it goes back to green. For some reason this is beyond me at the moment. Any and all help will be greatly appreciated. Thanks in advance!
//This component allows the user to store information on current unit identifier. Maybe necessary to pass this in as an arguement to the PssGui since there is no accounting for callsigns.
//This component also needs to be updated with a mouse click event that can turn the color of the box to reflect the tooltip text.
unitId = new JTextField();
unitId.setEditable(false);
unitId.setBackground(Color.GREEN);
unitId.setHorizontalAlignment(SwingConstants.CENTER);
unitId.setToolTipText("<html>SHADE CELLS TO REFLECT CURRENT UNIT STATUS:" + "<br/>GREEN-MC" + "<br/>RED-NMC" + "<br/>WHITE-UNIT IN TRANSISTION</html>");
unitId.setText("A 4/5");
unitId.setBounds(0, 116, 79, 172);
getContentPane().add(unitId);
unitId.setColumns(10);
unitId.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
//Fill with sweet code to change the color of this box accordingly.
//use an Int and a while loop or something so that every click increments the Int
//then each int value corresponds to a color
// have a statement at the end that resets the int back to zero to keep the colors in the loop
//I.E int color = 0, mouse click happens int color = 1, now color =1 which turns the box red,
//color can never be greater than 3, when it is, we set color back to zero.
for(int i = 0; i<=3; i++){
switch (i){
case 1: unitId.setBackground(Color.GREEN);
break;
case 2: unitId.setBackground(Color.red);
break;
case 3: unitId.setBackground(Color.white);
break;
}
}//end while
//System.out.println(i);
}
});
Addendum:
I fixed my own problem. I knew it was going to be something trivial and I apologize if posting here was a waste of server resources. I was massively frustrated last night when I was trying to solve this problem. Here is the functional code. The lesson to remember here is to take a break and don't always try to force the solution.
unitId = new JTextField();
unitId.setEditable(false);
unitId.setBackground(Color.GREEN);
unitId.setHorizontalAlignment(SwingConstants.CENTER);
unitId.setToolTipText("<html>SHADE CELLS TO REFLECT CURRENT UNIT STATUS:" + "<br/>GREEN-MC" + "<br/>RED-NMC" + "<br/>WHITE-UNIT IN TRANSISTION</html>");
unitId.setText("A 4/5");
unitId.setBounds(0, 116, 79, 172);
getContentPane().add(unitId);
unitId.setColumns(10);
unitId.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
//Fill with sweet code to change the color of this box accordingly.
//use an Int and a while loop or something so that every click increments the Int
//then each int value corresponds to a color
// have a statement at the end that resets the int back to zero to keep the colors in the loop
//I.E int color = 0, mouse click happens int color = 1, now color =1 which turns the box red,
//color can never be greater than 3, when it is, we set color back to zero.
if(starter==0){
unitId.setBackground(Color.GREEN);
starter++;
}
else if(starter==1){
unitId.setBackground(Color.WHITE);
starter++;
}
else if(starter==2){
unitId.setBackground(Color.RED);
starter++;
}
else{
starter=0;
unitId.setBackground(Color.GREEN);
}
//System.out.println(i);
}
});

Categories

Resources