因此,我创建了一个程序,在文本框中接受圆的半径,在随机点中创建随机颜色的圆,并使用另一个按钮清除所有圆的页面。我遇到的问题是我的被覆盖的paint()。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class PushPanel extends JPanel
{
private JButton newb;
private JButton clear;
private JLabel label;
private int x, y, width, r;
private int color;
private JTextField radius;
public PushPanel()
{
newb = new JButton("New");
clear = new JButton("Clear");
radius = new JTextField(5);
radius.addActionListener(new TextListener());
newb.addActionListener(new ButtonListener());
clear.addActionListener(new ButtonListener2());
label = new JLabel ("Circle creator", SwingConstants.CENTER);
add(radius);
add (newb);
add (clear);
add(label);
setPreferredSize(new Dimension(300,300));
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
paintComponent(getGraphics());
}
public void paintComponent(Graphics page)
{
Random rand = new Random();
int redValue = rand.nextInt(255);
int greenValue = rand.nextInt(255);
int blueValue = rand.nextInt(255);
Color clr = new Color(redValue, greenValue, blueValue);
Random generator = new Random(101);
x = generator.nextInt();
y = generator.nextInt();
width = r*2;
page.setColor(clr);
page.fillOval(x,y,width,width);
}
}
public class ButtonListener2 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
paintComponent(getGraphics());
}
public void paintComponent(Graphics page)
{
page.setColor(Color.white);
}
}
public class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String text = radius.getText();
r = Integer.parseInt(text);
}
}
}
This is the driver class, pretty basic
public class Circle
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Circle stuff");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
PushPanel panel = new PushPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:0)
你实际上没有告诉我们问题是什么,但我敢打赌,因为你的paintComponent()方法在你的ButtonListener类中,而不是你的PushPanel类。
此外,除非你真的知道自己在做什么,否则你永远不应该在组件上调用getGraphics()。推荐阅读:http://docs.oracle.com/javase/tutorial/uiswing/painting/