下面是我試圖在JFrame上繪製一些圖形的代碼。我試圖設置給出錯誤的JFrame的佈局。但是,如果我沒有設置佈局代碼工作正常,但沒有所需的方式。我找不出什麼問題。請幫忙! =)在JFrame中看不到單個項目?
import java.awt.*;
import javax.swing.*;
class GuiForJFrame extends JFrame {
private FlowLayout layout;
private Container container;
public GuiForJFrame() {
super("Drawing Graphics");
// Setting the Layout
layout = new FlowLayout(FlowLayout.LEFT);
container = getContentPane();
setLayout(layout);
}
}
class GuiForDrawingGraphics extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.RED);
g.fillRect(25, 25, 150, 50);
g.setColor(new Color(156, 32, 111));
g.fillRect(25, 80, 150, 50);
g.setColor(Color.BLACK);
g.drawString("Drawing Graphics in JAVA", 25, 150);
}
}
public class Application {
public static void main(String[] args) {
// Creating the JFrame object
GuiForJFrame jFrame = new GuiForJFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Adding Graphics to JFrame
GuiForDrawingGraphics graphics = new GuiForDrawingGraphics();
jFrame.add(graphics);
jFrame.setSize(500, 200);
jFrame.setVisible(true);
}
}
您正在使用的FlowLayout,然後添加具有的[0,0]較好大小一個JPanel,因此它是有道理的,你會看到什麼。爲什麼使用FlowLayout而不是默認的BorderLayout,在這裏會更有意義? –