这是我的代码的样子
import java.awt.*;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
MyDrawPanel shape = new MyDrawPanel();
frame.getContentPane().add(shape);
frame.setSize(500,500);
frame.setVisible(true);
}
}
class MyDrawPanel extends JPanel{
public void paintComponent (Graphics g) {
g.setColor(Color.ORANGE);
g.fillRect(20, 50, 100, 100);
}
}
当我运行它时,显示的唯一东西是框架,而不是实际形状。有什么我想念的吗?
答案 0 :(得分:2)
请注意,此答案不能回答您直接的问题,即为什么发布的代码不起作用,因为尽管您的代码有问题,但仍应显示正方形。但话虽如此,这篇文章的目的是为“更好的”做法提供一些建议:
@Override
批注这是您的代码的更好表示:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
public class Test2 extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private static final Color RECT_COLOR = Color.ORANGE;
private static final int RECT_WIDTH = 100;
private static final int INIT_X = 20;
private static final int INIT_Y = 50;
private int rectX = INIT_X;
private int rectY = INIT_Y;
public Test2() {
// TODO any initialization code goes here
}
// override annotation
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// avoid magic values and numbers
g.setColor(RECT_COLOR);
g.fillRect(rectX, rectY, RECT_WIDTH, RECT_WIDTH);
}
// best way to set size safely
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Test2 mainPanel = new Test2();
JFrame frame = new JFrame("Test2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
// be sure to start the GUI on the event thread
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}