下面是我试图在 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);
}
}
最佳答案
如另一个答案中所述,自定义绘制的面板没有固有尺寸。它应该返回适合内容的首选大小。然后我们只需要在添加后pack()
frame。
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);
}
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.pack();
jFrame.setVisible(true);
}
}
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 Dimension getPreferredSize() {
return new Dimension(300,200);
}
}
关于java - 在 JFrame 中看不到单个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615552/