我试图用我在过去六个月的Java编程中学到的知识来重建经典的Pong游戏。但是,即使看起来很简单,画线也不是问题之一。
public static void main(String[] args) {
Pong p = new Pong();
p.setVisible(true);
}
/**
* The Constructor
*/
public Pong() {
makeFrame();
draw(getGraphics());
}
/**
* Making the frame for the game
*/
public void makeFrame() {
// Frame stuff goes here
}
/**
* Drawing the in-games lines
*/
public void draw(Graphics g) {
super.paint(g);
g.setColor(Color.white);
g.drawLine(400, 0, 400, 550);
}
我似乎无法画线。关于我在做什么错的任何想法吗?
我想把线放在屏幕中间。
编辑:
要感谢回答问题的家伙。你们有很多荣誉!我真的很感谢答案和提供的链接! :)
最佳答案
在Swing中,您不负责绘画,该工作属于RepaintManager
。它基于许多因素决定什么时候喷涂。
推荐的执行自定义绘画的机制是创建一个自定义类,从JPanel
之类扩展并覆盖其paintComponent
方法。如果要更新组件,则可以通过调用其repaint
方法来请求重新粉刷该组件。
没错,这只是一个请求。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class QuickPaint {
public static void main(String[] args) {
new QuickPaint();
}
public QuickPaint() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private int paints = 0;
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
paints++;
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
g.drawLine(width / 2, 0, width / 2, height);
g.drawLine(0, height / 2, width, height / 2);
g.drawLine(0, 0, width, height);
g.drawLine(0, height, width, 0);
String text = "Repainted " + paints + " times";
FontMetrics fm = g.getFontMetrics();
int x = (width - fm.stringWidth(text)) / 2;
int y = ((height - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(text, x, y);
}
}
}
详细了解Performing Custom Painting和Painting in AWT and Swing ...
关于java - 在黑色JFrame上画线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16496064/