gpt4 book ai didi

java - 如何在 JPanel 中绘制矩形

转载 作者:行者123 更新时间:2023-12-01 18:35:45 25 4
gpt4 key购买 nike

我正在尝试在 JFrame 内的 JPanel 内绘制一个矩形。我想使用 PaintComponents(Graphics g) 方法并覆盖它,但由于某种原因,矩形没有像我希望的那样出现在 JPanel 中。任何帮助,将不胜感激。

public class RectangleFrame extends JFrame implements ActionListener {
JPanel buttonPanel;
JButton saveImage;
JButton clearImage;
JCheckBox intersections;
JCheckBox union;
JPanel drawingArea;



public RectangleFrame()
{
super();
setTitle("Rectangles");
setSize(600,600);
setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black));
this.add(buttonPanel, BorderLayout.SOUTH);

intersections = new JCheckBox("Draw Intersections");
buttonPanel.add(intersections);

union = new JCheckBox("Draw Union");
buttonPanel.add(union);

saveImage = new JButton("Save Image");
saveImage.setMargin(new Insets(0,0,0,0));
buttonPanel.add(saveImage);

clearImage = new JButton("Clear Image");
clearImage.setMargin(new Insets(0,0,0,0));
buttonPanel.add(clearImage);

drawingArea = new JPanel();
drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue));
this.add(drawingArea, BorderLayout.CENTER);
}
}

class RectanglePanel extends JPanel
{
public RectanglePanel()
{
super();
}



@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);

g.setColor(Color.BLUE);
g.fillRect(25,25,100,30);
}


}

这是我的主要方法,它位于一个单独的类中:

    public class SwingRectangle
{

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
RectangleFrame frame = new RectangleFrame();
RectanglePanel panel = new RectanglePanel();
frame.setVisible(true);

}

}

最佳答案

您没有将 RectanglePanel 添加到框架中。

drawingArea = new JPanel();

应该是

drawingArea = new RectanglePanel();

其他要点:

  • 您仍然需要重写 paintComponent 而不是 @David 建议的 paintComponents,所以给他+1
  • SwingRectangle 中创建的面板未使用

关于java - 如何在 JPanel 中绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22105489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com