Millie Millie - 1 month ago 13
Java Question

Correlating JButton with Functionality, Changing the color of a line

I am new to JButton and JFrame and just trying to learn some basics, about how logic should work and what the code should look like. Here, I have created an idea of logic, but it doesn't work. I am not sure if I just need to tweak something or if I'm going about this completely wrong. Again, I'm new to this, just trying to learn the basics. Thank you for any help. What it should do is change the color of the line when the button is clicked. :)

JButton yellow = new JButton();

public SimplePaint(){

JPanel panel=new JPanel();
yellow.setBackground(Color.yellow);
panel.add(yellow);

public void paint(Graphics g) {

super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Float(0, 250, 2000, 300);
g2.setColor(Color.MAGENTA);
g2.draw(line);

JButton color = null;

if (color == yellow) {
g2.setColor(Color.YELLOW);
}


Update: I have implemented the below answer, and I think I am getting closer, but the functionality is still not working. Here is the updated code:

JButton action =new JButton();
JButton red = new JButton();
JButton blue = new JButton();

public SimplePaint() {

blue.setBackground(Color.BLUE);
panel.add(blue);

red.setBackground(Color.RED);
panel.add(red);

public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Float(0, 250, 2000, 300);
g2.setColor(Color.MAGENTA);
g2.setStroke(new BasicStroke(3));
g2.draw(line);

action.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == blue) {
g2.setColor(Color.BLUE);
}
else if(e.getSource() == red) {
g2.setColor(Color.RED);
}
repaint();
}
});

}

Answer

You need to add a listener to the buttons, so they can trigger actions

jBUtton.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    System.out.println("Button Pressed");
    //pressed = !pressed; // if you want to toggle
    pressed = true;
    this.repaint(); // you need to refresh the screen 
  } 
} );

after that

if(pressed)
    g2.setColor(Color.YELLOW);
else
    g2.setColor(Color.MAGENTA);
Comments