我想绘制一个基本对象到JPanel ,虽然它似乎并没有工作。Java绘制到JPanel(调试)
我敢肯定,我做错了什么与在paint方法 被称为
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
public class testGui {
static colors gc_colors;
static gui gc_gui;
public static void main(String[] args) {
gc_colors = new colors();
gc_gui = new gui();
gc_gui.cv_frame.setVisible(true);
}
public static class colors {
Color cv_ltGrey;
Color cv_mdGrey;
Color cv_dkGrey;
public colors() {
cv_ltGrey = Color.decode("#DDDDDD");
cv_mdGrey = Color.decode("#CCCCCC");
cv_dkGrey = Color.decode("#111111");
}
}
public static class gui {
JFrame cv_frame;
JPanel cv_panel;
JPanel cv_content;
public gui() {
cv_frame = new JFrame();
cv_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cv_frame.setTitle("Test GUI");
cv_frame.setSize(600, 400);
cv_frame.setLayout(new FlowLayout());
cv_panel = new JPanel();
cv_panel.setBackground(gc_colors.cv_ltGrey);
cv_panel.setPreferredSize(new Dimension(500, 300));
cv_frame.add(cv_panel);
cv_content = new content();
cv_panel.add(cv_content);
}
}
public static class content extends JPanel {
public void paint(Graphics graphic) {
super.paint(graphic);
draw(graphic);
}
public void update() {
repaint();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.setPaint(gc_colors.cv_ltGrey);
graphic2D.fillRect(10, 10, 100, 100);
}
}
}
我有我的GUI其中我加入一个JPanel来(浅灰色之一)的一类。 然后我试图添加我的绘图,使用名为content的JPanel扩展类 。
当我运行它虽然它似乎创建了我想要的灰色JPanel,但 绘图只是一个小小的白色方形,我不知道为什么。
覆盖getPreferredSize并为组件 – MadProgrammer
我返回一个合适的尺寸说实话我不知道你的意思 – Trent
'content'从'JPanel'扩展了''getPreferredSize'',你需要重写这个方法,就像你做了'paint'一样,并返回一个合适的大小对于组件,否则它将默认为'0x0' – MadProgrammer