【发布时间】:2013-12-17 13:14:05
【问题描述】:
从我前几天开始编写的一个简单程序继续,我有一个新的查询。我希望程序在面板中间画一个黑色圆圈。稍后我将使用按钮来移动圆圈,但我还没有在那个阶段。程序运行没有错误,我得到一个白色面板,下面有我的按钮,但白色面板中间没有黑色圆圈。我搜索了一些以前推荐使用paintComponent 的帖子,我已经这样做了,但是我遗漏了一些东西,因为它没有按我的预期工作,并且repaint() 也不起作用。感谢您收到任何提示。
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovingArrows extends JFrame implements ActionListener {
private JButton buttonUp, buttonDown, buttonLeft, buttonRight;
private JPanel panel;
private int xCircleCentre, yCircleCentre;
final int xCircleCentreStarting = 250, yCircleCentreStarting = 250;
final int RADIUS = 20;
public static void main(String[] args) {
// TODO Auto-generated method stub
MovingArrows frame = new MovingArrows();
frame.setSize(550, 600);
frame.setVisible(true);
frame.createGUI();
// frame.repaint();
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.setBackground(Color.white);
window.add(panel);
buttonUp = new JButton("Up");
buttonDown = new JButton("Down");
buttonLeft = new JButton("Left");
buttonRight = new JButton("Right");
window.add(buttonUp);
window.add(buttonDown);
window.add(buttonLeft);
window.add(buttonRight);
buttonUp.addActionListener(this);
buttonDown.addActionListener(this);
buttonLeft.addActionListener(this);
buttonRight.addActionListener(this);
// panel.repaint();
Graphics paper = panel.getGraphics();
paintComponent(paper);
}
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillOval(xCircleCentreStarting - RADIUS, yCircleCentreStarting
- RADIUS, RADIUS * 2, RADIUS * 2);
}
@Override
public void actionPerformed(ActionEvent event) {
Graphics paper = panel.getGraphics();
paper.setColor(Color.black);
paper.fillOval(xCircleCentreStarting - RADIUS, yCircleCentreStarting
- RADIUS, RADIUS * 2, RADIUS * 2);
}
}
【问题讨论】:
标签: java swing drawing jpanel paintcomponent