调整窗口大小或使用滚动条后,绘制组件消失

时间:2017-03-26 14:54:41

标签: java swing jpanel

单击“确定”按钮后,我编写了一个绘制50个矩形的程序。但我不明白为什么它在调整窗口大小后,使用滚动条或再次单击确定后消失。 这是我的代码(我有两个类:drawingPanel和Main) drawingPanel.java:

import javax.swing.*;
import java.awt.*;

public class drawingPanel extends JPanel 
{
    public boolean drawIt = false;
    public int x = 140,y = 0;

    public void paintIt()
    {
        drawIt = true;
        repaint();
    }

    public void paintComponent(Graphics g)
    {

        if (drawIt == true)
            {   
                super.paintComponent(g);    
                for (int i = 1; i <= 50; i++)
                {

                    g.fillRect(x, y, 50, 50);           
                    y += 70;
                }
            }

    }
}

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame 
{
    private drawingPanel draw = new drawingPanel();
    private JPanel controlPanel = new JPanel();
    private JButton ok = new JButton("OK");
    private JScrollPane scroll = new JScrollPane(draw);

    public Main()
    {
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Demo");
        setLayout(new BorderLayout());

        controlPanel.setLayout(new FlowLayout());
        controlPanel.add(ok);
        ok.addActionListener(new okListener());

        draw.setPreferredSize(new Dimension(100,1000));

        add(controlPanel, BorderLayout.NORTH);
        add(scroll,BorderLayout.CENTER);
        setVisible(true);
    }

    private class okListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            draw.paintIt();
        }
    }

    public static void main(String[] args) 
    {
        new Main();
    }
}

请提前帮助我。

1 个答案:

答案 0 :(得分:2)

重新初始化paint组件方法中的x和y字段,以便每次绘制JPanel时它们都不会增加视图:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);  // move this here

    if (drawIt) {
        x = 140;  // add these guys
        y = 0;

        for (int i = 1; i <= 50; i++) {
            // .... etc....

事情应该好好。

与您的问题无关的其他小问题:

  • 应始终调用超级绘画方法,因此请将其从if块中拉出来。
  • 将您的drawingPanel类重命名为DrawingPanel,以使其符合Java约定。
  • 最好将if (drawIt == true) {更改为更简单的if (drawIt) {
  • 轻微狡辩:paintComponent应该是protected,而不是public