0

我正在尝试在 JFrame 中的两个按钮上实现动作侦听器,但问题是两个按钮之一正在执行这两个功能;但我还没有配置它这样做。请找到示例代码:-

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MyChangingCirlce implements ActionListener{
JButton colorButton, labelButton;
JLabel myLabel;
MyDrawPanel mdp;
JFrame frame;
   public static void main(String [] args)
   {
    MyChangingCirlce mcc = new MyChangingCirlce();
    mcc.createFrame();
   } 

  public void createFrame()
  {
frame = new JFrame();
colorButton = new JButton("Changing Colors");
labelButton = new JButton("Change Label");
myLabel = new JLabel("BA");
mdp = new MyDrawPanel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


frame.getContentPane().add(BorderLayout.CENTER, mdp);   
frame.getContentPane().add(BorderLayout.SOUTH,colorButton); 
frame.getContentPane().add(BorderLayout.EAST,labelButton);  
frame.getContentPane().add(BorderLayout.WEST,myLabel);
colorButton.addActionListener(this);
labelButton.addActionListener(this);    
frame.setSize(300,300);
frame.setVisible(true);

  } // end of createFrame Method


public void actionPerformed(ActionEvent e)
{
if(e.getSource()== colorButton)
{
frame.repaint();        
}
else
{
myLabel.setText("AB");
}

}   //end of interface method...

}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyDrawPanel extends JPanel{

public void paintComponent(Graphics g)
{
    int red = (int) (Math.random() * 255);
    int green = (int) (Math.random() * 255);
    int blue= (int) (Math.random() * 255);
    Color randomColor = new Color(red,green,blue);
    g.setColor(randomColor);
    g.fillOval(20,70,100,100);
}

}

4

1 回答 1

2

You think the button triggers both the if and else statement but that is not the case. If you would adjust your code in the following way:

  • add a setColor, changeColor or something similar to your MyDrawPanel class
  • adjust the MyDrawPanel#paintComponent method to use a fixed color instead of a random color, and only adjust the color through the method created in the first step
  • your color change button should use the method created in the first step to adjust the color of the MyDrawPanel

The thing is that paintComponent can be called by Swing itself. It is not only called when you call repaint (which is a good thing, or all code you write for Swing components would be filled with repaint calls).

Side note: when overriding the paintComponent method I would recommended to call super.paintComponent as well

于 2012-07-25T19:12:25.573 回答