1
繼續從一個簡單的程序開始寫一天,我有一個新的查詢。我希望程序在面板中間畫一個黑色圓圈。稍後我將使用按鈕來移動圓圈,但我還沒有在那個舞臺上。該程序運行時沒有錯誤,我用下面的按鈕得到一個白色面板,但在白色面板中間沒有黑色圓圈。我搜索了一些以前推薦使用paintComponent的帖子,我已經完成了,但我錯過了一些東西,因爲它不像我期望的那樣工作,並且repaint()也不起作用。任何提示感激地收到。即使當我畫它時,也是空白的JPanel
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);
}
}
非常感謝您的回覆和代碼。我會努力通過它,希望我會理解。我沒有遇到你給我的鏈接......我讀了一些其他的指南,但我仍然無法弄清楚他們的錯誤。 – Zaw
通過它,我想我明白了。當你的程序在面板上繪製時,它很奇怪,不能直接控制它。我還想爲你整理按鈕並將它們放在面板上 - 我還沒有閱讀框架佈局,這是我很快就要做的事情。 – Zaw