我想繪製一個基本對象到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