如何将对象添加到 JPanel 中
How to add a object into a JPanel
我正在尝试将球添加到 JPanel 中,但是我不确定如何执行此操作下面是我目前拥有的用于将球添加到 JPanel 中的代码。我正在尝试在屏幕上的随机位置添加多个球。第一个按预期出现,但除此之外没有出现在屏幕上。
球class;
public class Ball extends Component {
public static double ballX = rand.nextInt(500) + 40;
public static double ballY = rand.nextInt(300) + 10;
public static Ball[] balls = new Ball[20];
public Ball() {
}
public void draw(Graphics g2) {
Color color = new Color(r, g, b);
g2.setColor(color);
g2.fillOval((int) ballX, (int) ballY, 30, 30);
}
}
尝试将球添加到 JPanel 的方法;
public class BallFrames extends JFrame {
/* creates static varibles privite for use withing class and public for
use out side of the class */
public static final JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
public static final JPanel ballPanel = new JPanel();
public static JButton button;
public static JPanel displayPanel = new JPanel(new BorderLayout());
private static int FRAME_WIDTH = 600;
private static int FRAME_HEIGHT = 600;
/**
* constructor called method to create the components
*/
public BallFrames() {
setSize(FRAME_WIDTH,FRAME_HEIGHT);
createComponents(); // creates all compononents
}
/*
* calls helper methods to create all of the componanats needed
*/
private void createComponents() {
ActionListener listener = new BallListener();
createPanel(); // creates a panel
createButtons(listener); // Creates a button
createSlider();
}
/**
* method to create panels
*/
public void createPanel() {
BallComponent component = new BallComponent(); // creates a new BallCompoenet
displayPanel.add(component, BorderLayout.CENTER);
displayPanel.add(controlPanel, BorderLayout.SOUTH); // adds thecontrol panel
add(displayPanel); // adds the dice to the JFrame
}
public static void addBall() throws InterruptedException {
Ball.balls[BallListener.balls] = new Ball();
System.out.println(BallListener.balls); // testing
ballPanel.add(Ball.balls[BallListener.balls]);
// ballPanel.add(ball);
Runnable r = new BallRunnable();
Thread t = new Thread(r);
t.start();
t.join();
ballPanel.repaint();
}
我是怎么画的;
public class BallComponent extends JComponent {
/**
* calls paintComponenet to render images on the screen
*
* @param g
*/
@Override
public void paintComponent(Graphics g) {
int delay = 1000;
super.paintComponent(g); // call to super
Graphics2D g2 = (Graphics2D) g; // recover the graphic
TimerListener listener = new TimerListener();
Timer t = new Timer(delay, listener);
if (BallListener.gameOn == true) {
for(int i = 0; i < BallListener.balls; i++){
Ball.balls[i].draw(g2);
}
BallFrames.displayPanel.repaint();
}
}
ActionListener for the buttons;
public class BallListener implements ActionListener {
public static boolean gameOn = false;
public static int balls = 0;
/**
* gets the which button has been pressed and responds appriately
*
* @param event based on the event it will preform selected actions
*/
@Override
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
switch (action) {
case "start":
gameOn = true;
{
try {
BallFrames.addBall();
} catch (InterruptedException ex) {
Logger.getLogger(BallListener.class.getName()).log(Level.SEVERE, null, ex);
}
balls++;
}
BallFrames.displayPanel.repaint();
break;
case "pause":
break;
}
}
球可运行;
public class BallRunnable implements Runnable {
private static Random rand = new Random();
public static boolean goLeft = true;
public static boolean goRight = false;
public static boolean goUp = false;
public static boolean goDown = false;
public static boolean diagonalUp = false;
public static boolean diagonalDown = false;
public static double speed = 0.2f;
public BallRunnable() {
}
public void run() {
boundsCheckY1();
boundsCheckX1();
boundsCheckY2();
boundsCheckX2();
}
public void boundsCheckX1() {
int temp;
if (Ball.ballX < 1) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = true;
goLeft = false;
goUp = false;
goDown = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = true;
goUp = true;
goDown = false;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = true;
goUp = false;
goDown = true;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = true;
goUp = false;
goDown = false;
goLeft = false;
diagonalUp = true;
diagonalDown = false;
} else if (temp == 5) {
goRight = true;
goUp = false;
goDown = false;
goLeft = false;
diagonalUp = false;
diagonalDown = true;
}
}
}
public void boundsCheckY1(){
int temp;
if (Ball.ballY < 1) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = false;
goLeft = false;
goUp = false;
goDown = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = false;
goUp = false;
goDown = true;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = true;
goUp = false;
goDown = true;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = true;
goUp = false;
goDown = true;
goLeft = false;
diagonalUp = false;
diagonalDown = true;
} else if (temp == 5) {
goRight = false;
goUp = false;
goDown = true;
goLeft = true;
diagonalUp = false;
diagonalDown = true;
}
}
}
public void boundsCheckX2 () {
int temp;
if (Ball.ballX > 559) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = false;
goLeft = true;
goUp = false;
goDown = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = false;
goUp = true;
goDown = false;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = false;
goUp = false;
goDown = true;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = false;
goUp = false;
goDown = false;
goLeft = true;
diagonalUp = true;
diagonalDown = false;
} else if (temp == 5) {
goRight = false;
goUp = false;
goDown = false;
goLeft = true;
diagonalUp = false;
diagonalDown = true;
}
}
}
public void boundsCheckY2() {
int temp;
if (Ball.ballY > 470) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = false;
goLeft = false;
goUp = true;
goDown = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = false;
goUp = true;
goDown = false;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = true;
goUp = true;
goDown = false;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = true;
goUp = true;
goDown = false;
goLeft = false;
diagonalUp = true;
diagonalDown = false;
} else if (temp == 5) {
goRight = false;
goUp = true;
goDown = false;
goLeft = true;
diagonalUp = true;
diagonalDown = false;
}
}
}
}
观众class;
public class BallViewer {
/**
* creates the main frame
*
* @param args
*/
public static void main(String[] args) throws InterruptedException {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
// new BallFrames().setVisible(true);
JFrame frame = new BallFrames(); // creates new JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Multi-Treaded Balls");// Sets the Title
frame.setVisible(true); // Makes the frame visible
frame.setResizable(false);
}
});
}
}
定时器监听器;
public class TimerListener 实现 ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
try {
movement();
} catch (InterruptedException ex) {
Logger.getLogger(TimerListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void movement() throws InterruptedException {
if(goLeft == true) {
Ball.ballX -= speed;
}
if(goRight == true) {
Ball.ballX += speed;
}
if(goUp == true) {
Ball.ballY -= speed;
}
if(goDown == true) {
Ball.ballY += speed;
}
if(diagonalUp == true) {
Ball.ballY += speed / 2;
}
if(diagonalDown == true) {
Ball.ballY -= speed / 2;
}
}
}
我希望能够在给定时间在屏幕上添加多个球,它也像第一个球一样四处移动。
绘画代码仅用于绘画。
你永远不应该 create/start 绘画方法中的计时器。摆脱所有这些代码。
永远不要调用 repaint(),这会导致无限循环。
此外,删除所有动画代码。您的首要任务是在面板上绘制多个球。一旦你开始工作,你就会担心尝试做动画。
无需扩展 JComponent,因为您 class 不是组件。那就是您永远不会将组件添加到面板中。您所做的就是在另一个 class.
中绘制对象
因此您的 BallComponent
class(这是一个组件)需要有一个 ArrayList
来跟踪您要绘制的球对象。所以你需要一个方法来将球对象添加到这个 ArrayList 中。然后 paintComponent()
方法简单地遍历列表并绘制所有球。
查看 Custom Painting Approaches 中的 DrawOnComponent
示例。
您对球的定义 class 表现符合预期:
public class Ball extends Component {
public static double ballX = rand.nextInt(500) + 40;
public static double ballY = rand.nextInt(300) + 10;
public static Ball[] balls = new Ball[20];
public Ball() {
}
public void draw(Graphics g2) {
Color color = new Color(r, g, b);
g2.setColor(color);
g2.fillOval((int) ballX, (int) ballY, 30, 30);
}
}
所有 static
字段在 class 的所有实例之间共享。这就是 static
的意思。所有 Ball
都具有相同的 ballX
和 ballY
坐标。
您要查找的是属于每个单独实例的非static
字段。每次制作新球时,您还必须初始化这些字段。 static
字段仅在加载 class 时初始化一次。我还建议进行一些更改:
- 如果你的x坐标和y坐标只属于一个球,最好做成
private
。
- 扩展
JComponent
而不是 Component
,因为您显然在此处使用了 swing。
- 实施
paintComponent
而不是 draw
。如果没有别的,它将使您的绘图代码需要更少的维护。
这是 class 的一个版本,应该会更好一些:
public class Ball extends JComponent
{
private double ballX;
private double ballY;
public static Ball[] balls = new Ball[20];
public Ball()
{
ballX = rand.nextInt(500) + 40;
ballY = rand.nextInt(300) + 10;
}
public void paintComponent(Graphics g2)
{
Color color = new Color(r, g, b);
g2.setColor(color);
g2.fillOval((int) ballX, (int) ballY, 30, 30);
}
}
我正在尝试将球添加到 JPanel 中,但是我不确定如何执行此操作下面是我目前拥有的用于将球添加到 JPanel 中的代码。我正在尝试在屏幕上的随机位置添加多个球。第一个按预期出现,但除此之外没有出现在屏幕上。
球class;
public class Ball extends Component {
public static double ballX = rand.nextInt(500) + 40;
public static double ballY = rand.nextInt(300) + 10;
public static Ball[] balls = new Ball[20];
public Ball() {
}
public void draw(Graphics g2) {
Color color = new Color(r, g, b);
g2.setColor(color);
g2.fillOval((int) ballX, (int) ballY, 30, 30);
}
}
尝试将球添加到 JPanel 的方法;
public class BallFrames extends JFrame {
/* creates static varibles privite for use withing class and public for
use out side of the class */
public static final JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
public static final JPanel ballPanel = new JPanel();
public static JButton button;
public static JPanel displayPanel = new JPanel(new BorderLayout());
private static int FRAME_WIDTH = 600;
private static int FRAME_HEIGHT = 600;
/**
* constructor called method to create the components
*/
public BallFrames() {
setSize(FRAME_WIDTH,FRAME_HEIGHT);
createComponents(); // creates all compononents
}
/*
* calls helper methods to create all of the componanats needed
*/
private void createComponents() {
ActionListener listener = new BallListener();
createPanel(); // creates a panel
createButtons(listener); // Creates a button
createSlider();
}
/**
* method to create panels
*/
public void createPanel() {
BallComponent component = new BallComponent(); // creates a new BallCompoenet
displayPanel.add(component, BorderLayout.CENTER);
displayPanel.add(controlPanel, BorderLayout.SOUTH); // adds thecontrol panel
add(displayPanel); // adds the dice to the JFrame
}
public static void addBall() throws InterruptedException {
Ball.balls[BallListener.balls] = new Ball();
System.out.println(BallListener.balls); // testing
ballPanel.add(Ball.balls[BallListener.balls]);
// ballPanel.add(ball);
Runnable r = new BallRunnable();
Thread t = new Thread(r);
t.start();
t.join();
ballPanel.repaint();
}
我是怎么画的;
public class BallComponent extends JComponent {
/**
* calls paintComponenet to render images on the screen
*
* @param g
*/
@Override
public void paintComponent(Graphics g) {
int delay = 1000;
super.paintComponent(g); // call to super
Graphics2D g2 = (Graphics2D) g; // recover the graphic
TimerListener listener = new TimerListener();
Timer t = new Timer(delay, listener);
if (BallListener.gameOn == true) {
for(int i = 0; i < BallListener.balls; i++){
Ball.balls[i].draw(g2);
}
BallFrames.displayPanel.repaint();
}
}
ActionListener for the buttons;
public class BallListener implements ActionListener {
public static boolean gameOn = false;
public static int balls = 0;
/**
* gets the which button has been pressed and responds appriately
*
* @param event based on the event it will preform selected actions
*/
@Override
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
switch (action) {
case "start":
gameOn = true;
{
try {
BallFrames.addBall();
} catch (InterruptedException ex) {
Logger.getLogger(BallListener.class.getName()).log(Level.SEVERE, null, ex);
}
balls++;
}
BallFrames.displayPanel.repaint();
break;
case "pause":
break;
}
}
球可运行;
public class BallRunnable implements Runnable {
private static Random rand = new Random();
public static boolean goLeft = true;
public static boolean goRight = false;
public static boolean goUp = false;
public static boolean goDown = false;
public static boolean diagonalUp = false;
public static boolean diagonalDown = false;
public static double speed = 0.2f;
public BallRunnable() {
}
public void run() {
boundsCheckY1();
boundsCheckX1();
boundsCheckY2();
boundsCheckX2();
}
public void boundsCheckX1() {
int temp;
if (Ball.ballX < 1) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = true;
goLeft = false;
goUp = false;
goDown = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = true;
goUp = true;
goDown = false;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = true;
goUp = false;
goDown = true;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = true;
goUp = false;
goDown = false;
goLeft = false;
diagonalUp = true;
diagonalDown = false;
} else if (temp == 5) {
goRight = true;
goUp = false;
goDown = false;
goLeft = false;
diagonalUp = false;
diagonalDown = true;
}
}
}
public void boundsCheckY1(){
int temp;
if (Ball.ballY < 1) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = false;
goLeft = false;
goUp = false;
goDown = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = false;
goUp = false;
goDown = true;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = true;
goUp = false;
goDown = true;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = true;
goUp = false;
goDown = true;
goLeft = false;
diagonalUp = false;
diagonalDown = true;
} else if (temp == 5) {
goRight = false;
goUp = false;
goDown = true;
goLeft = true;
diagonalUp = false;
diagonalDown = true;
}
}
}
public void boundsCheckX2 () {
int temp;
if (Ball.ballX > 559) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = false;
goLeft = true;
goUp = false;
goDown = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = false;
goUp = true;
goDown = false;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = false;
goUp = false;
goDown = true;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = false;
goUp = false;
goDown = false;
goLeft = true;
diagonalUp = true;
diagonalDown = false;
} else if (temp == 5) {
goRight = false;
goUp = false;
goDown = false;
goLeft = true;
diagonalUp = false;
diagonalDown = true;
}
}
}
public void boundsCheckY2() {
int temp;
if (Ball.ballY > 470) {
temp = rand.nextInt(5) + 1;
if(temp == 1) {
goRight = false;
goLeft = false;
goUp = true;
goDown = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 2) {
goRight = false;
goUp = true;
goDown = false;
goLeft = true;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 3) {
goRight = true;
goUp = true;
goDown = false;
goLeft = false;
diagonalUp = false;
diagonalDown = false;
} else if (temp == 4) {
goRight = true;
goUp = true;
goDown = false;
goLeft = false;
diagonalUp = true;
diagonalDown = false;
} else if (temp == 5) {
goRight = false;
goUp = true;
goDown = false;
goLeft = true;
diagonalUp = true;
diagonalDown = false;
}
}
}
}
观众class;
public class BallViewer {
/**
* creates the main frame
*
* @param args
*/
public static void main(String[] args) throws InterruptedException {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
// new BallFrames().setVisible(true);
JFrame frame = new BallFrames(); // creates new JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Multi-Treaded Balls");// Sets the Title
frame.setVisible(true); // Makes the frame visible
frame.setResizable(false);
}
});
}
}
定时器监听器; public class TimerListener 实现 ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
try {
movement();
} catch (InterruptedException ex) {
Logger.getLogger(TimerListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void movement() throws InterruptedException {
if(goLeft == true) {
Ball.ballX -= speed;
}
if(goRight == true) {
Ball.ballX += speed;
}
if(goUp == true) {
Ball.ballY -= speed;
}
if(goDown == true) {
Ball.ballY += speed;
}
if(diagonalUp == true) {
Ball.ballY += speed / 2;
}
if(diagonalDown == true) {
Ball.ballY -= speed / 2;
}
}
}
我希望能够在给定时间在屏幕上添加多个球,它也像第一个球一样四处移动。
绘画代码仅用于绘画。
你永远不应该 create/start 绘画方法中的计时器。摆脱所有这些代码。
永远不要调用 repaint(),这会导致无限循环。
此外,删除所有动画代码。您的首要任务是在面板上绘制多个球。一旦你开始工作,你就会担心尝试做动画。
无需扩展 JComponent,因为您 class 不是组件。那就是您永远不会将组件添加到面板中。您所做的就是在另一个 class.
中绘制对象因此您的 BallComponent
class(这是一个组件)需要有一个 ArrayList
来跟踪您要绘制的球对象。所以你需要一个方法来将球对象添加到这个 ArrayList 中。然后 paintComponent()
方法简单地遍历列表并绘制所有球。
查看 Custom Painting Approaches 中的 DrawOnComponent
示例。
您对球的定义 class 表现符合预期:
public class Ball extends Component {
public static double ballX = rand.nextInt(500) + 40;
public static double ballY = rand.nextInt(300) + 10;
public static Ball[] balls = new Ball[20];
public Ball() {
}
public void draw(Graphics g2) {
Color color = new Color(r, g, b);
g2.setColor(color);
g2.fillOval((int) ballX, (int) ballY, 30, 30);
}
}
所有 static
字段在 class 的所有实例之间共享。这就是 static
的意思。所有 Ball
都具有相同的 ballX
和 ballY
坐标。
您要查找的是属于每个单独实例的非static
字段。每次制作新球时,您还必须初始化这些字段。 static
字段仅在加载 class 时初始化一次。我还建议进行一些更改:
- 如果你的x坐标和y坐标只属于一个球,最好做成
private
。 - 扩展
JComponent
而不是Component
,因为您显然在此处使用了 swing。 - 实施
paintComponent
而不是draw
。如果没有别的,它将使您的绘图代码需要更少的维护。
这是 class 的一个版本,应该会更好一些:
public class Ball extends JComponent
{
private double ballX;
private double ballY;
public static Ball[] balls = new Ball[20];
public Ball()
{
ballX = rand.nextInt(500) + 40;
ballY = rand.nextInt(300) + 10;
}
public void paintComponent(Graphics g2)
{
Color color = new Color(r, g, b);
g2.setColor(color);
g2.fillOval((int) ballX, (int) ballY, 30, 30);
}
}