我正在创建一个简单的java项目,想知道如何使用变量名创建Rectangle
,如下所示:
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle background = new Rectangle(0, 100, 500, 400);
我目前有这个代码可以填充:
public void draw(Graphics g) {
g.setColor(darkGreen);
g.fillRect(header.x, header.y, header.width, header.height);
g.setColor(tan);
g.fillRect(background.x, background.y, background.width, background.height);
}
然而,当我运行代码时没有出现任何内容,我不知道其他任何错误,但以下是其他错误:
package trivia;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Main extends JPanel{
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#E9E0D6");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle background = new Rectangle(0, 100, 500, 400);
@Override
public void paint(Graphics g) {
}
public void draw(Graphics g) {
g.setColor(darkGreen);
g.fillRect(header.x, header.y, header.width, header.height);
g.setColor(tan);
g.fillRect(background.x, background.y, background.width, background.height);
}
public static void main(String[] args) {
int HEIGHT = 500;
int WIDTH = 500;
JFrame mainFrame = new JFrame("Mini Tennis");
mainFrame.setSize(HEIGHT, WIDTH);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
}
}
非常感谢任何帮助!
答案 0 :(得分:1)
您需要先向Main
添加JFrame
(该类)的新实例。在paint(Graphics g)
,您需要致电draw(g)
。我个人使用高级双缓冲,所以它不会一直闪烁 - > https://github.com/czipperz/CLibrary/blob/master/src/io/czipperz/github/cLibrary/game/CGameFrame.groovy#L123(这是Groovy代码,但它基本上是Java)。
答案 1 :(得分:0)
我注意到你创建了Main类,它在主类文件中扩展了JPanel(这不是一个好习惯),而且这个类也没有在静态主类中实例化。 主要课程是这样的:
package trivia;
import javax.swing.JFrame;
public class Trivia {
public static void main(String[] args) {
int HEIGHT = 500;
int WIDTH = 500;
MyPanel myPanel = new MyPanel();
JFrame mainFrame = new JFrame("Mini Tennis");
mainFrame.setSize(HEIGHT, WIDTH);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.add(myPanel);
mainFrame.validate(); // Don't forget to validate frame or repaint.
}
}
将两个文件分开会更简单。尝试在新文件中添加该类,以便创建例如MyPanel.java:
package trivia;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JPanel;
public class MyPanel extends JPanel{
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#389900");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle background = new Rectangle(0, 100, 500, 400);
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
g.setColor(darkGreen);
g.fillRect(header.x, header.y, header.width, header.height);
g.setColor(tan);
g.fillRect(background.x, background.y, background.width, background.height);
}