我正在尝试在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);
}
}
答案 0 :(得分:2)
您认为该按钮会触发if
和else
语句,但事实并非如此。如果您要按以下方式调整代码:
setColor
,changeColor
或与您的MyDrawPanel
类相似的内容MyDrawPanel#paintComponent
方法以使用固定颜色而不是随机颜色,并仅通过第一步中创建的方法调整颜色MyDrawPanel
事情是,Swing本身可以调用paintComponent
。它不仅在您调用repaint
时调用(这是一件好事,或者您为Swing组件编写的所有代码都将填充repaint
次调用)。
附注:当覆盖paintComponent
方法时,我建议您同时调用super.paintComponent