我对 Java 编码(以及一般编码)非常陌生。我目前正在学校读 11 年级 CS,但我们所涵盖的所有内容都非常简单。
为了让我们达到高潮,我正在尝试打乒乓球。我意识到我必须使用 JPanel 才能完成我想做的事情,但到目前为止我们只使用 Console,所以我对此一无所知。
无论如何,我在使用已经声明的 JPanel 时遇到了麻烦。关于如何在 JPanel 中绘图的每个解决方案或教程都包含使用完全不同的类,并且我不知道如何将其实现到我预先存在的代码中;那是...
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class pong extends JPanel {
private JFrame f3, f2, f1;
private JPanel pLabel, pButton, pPong1, pPong2;
private JButton b1, b2;
private JLabel lab, score;
int singleScore = 0;
int doubleScore1 = 0;
int doubleScore2 = 0;
int By;
int Bx;
int Paddle1y;
int Paddle2y;
public pong()
{
gui();
}
public void gui()
{
f1 = new JFrame("Pong!");
f1.setVisible(true);
f1.setSize(700, 500);
f1.setResizable(false);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pButton = new JPanel();
pButton.setBackground(Color.BLACK);
pLabel = new JPanel();
pLabel.setBackground(Color.WHITE);
b1 = new JButton("1 Player");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pong1();
}
});
b2 = new JButton("2 Players");
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pong2();
}
});
lab = new JLabel("Welcome to Pong!");
pButton.add(b1);
pButton.add(b2);
pLabel.add(lab);
f1.add(pButton, BorderLayout.SOUTH);
f1.add(pLabel, BorderLayout.CENTER);
}
public void pong1()
{
f1.dispose();
f2 = new JFrame("One Player Pong");
f2.setVisible(true);
f2.setSize(700, 500);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setResizable(false);
pPong1 = new JPanel();
pPong1.setVisible(true);
pPong1.setBackground(Color.WHITE);
score = new JLabel("Score = " + singleScore);
f2.add(pPong1);
pPong1.add(score, BorderLayout.NORTH);
}
public void pong2()
{
f1.dispose();
f3 = new JFrame("Two Player Pong");
f3.setVisible(true);
f3.setSize(700, 500);
f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f3.setResizable(false);
pPong2 = new JPanel();
pPong2.setVisible(true);
pPong2.setBackground(Color.WHITE);
score = new JLabel("Player 1 Score = " + doubleScore1 + " Player 2 Score = " + doubleScore2);
f3.add(pPong2);
pPong2.add(score, BorderLayout.NORTH);
}
public static void main(String[] args)
{
new pong();
}
}
无论如何,非常感谢您能给我的任何帮助。预先感谢您。
最佳答案
您可以覆盖 paintComponent()
来绘制内容,并在想要更新显示时使用 repaint()
来调用它。 Graphics
类中的方法将为您提供帮助,例如 Graphics.drawLine()
、Graphics.fillRect()
等。
关于java - 尝试在已设置的 JPanel 上绘图但失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336348/