在java中,直到鼠标悬停在按钮上,按钮才会显示

在java中,直到鼠标悬停在按钮上,按钮才会显示,java,swing,Java,Swing,除非我将鼠标悬停在按钮上,否则不会显示JButtons package paint; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;

除非我将鼠标悬停在按钮上,否则不会显示JButtons

package paint;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author Rehan Shakir
 */

public class PaintFrame extends JFrame implements MouseMotionListener,ActionListener
{
  private int x=0; 
  private int y=0;
  private final JButton red,yellow,blue,green;
 private final JPanel p;
  //private final  JLabel l;
  private final  Container c; 
  private Color color;
  public PaintFrame()
  {

     setTitle("Paint");
     setSize(800,600);
     setDefaultCloseOperation(EXIT_ON_CLOSE);
     //setLayout(new FlowLayout());



     p = new JPanel();
     p.setLayout(new GridLayout(4,1));



     red = new JButton("Red");
     red.setBackground(Color.red);
     p.add(red);

     yellow = new JButton("Yellow");
     yellow.setBackground(Color.yellow);
     p.add(yellow);



     blue = new JButton("Blue");
     blue.setBackground(Color.blue);
     p.add(blue);

     green = new JButton("Green");
     green.setBackground(Color.green);
     p.add(green);

     red.addActionListener(this);
     yellow.addActionListener(this);
     blue.addActionListener(this);
     green.addActionListener(this);


     c = this.getContentPane();
     c.setLayout(new BorderLayout());
     JLabel l = new JLabel("Drag the mouse to draw",JLabel.RIGHT);
     c.add(l,BorderLayout.SOUTH);
     c.add(p,BorderLayout.WEST);

     c.addMouseMotionListener(this);
     setVisible(true);     

  }


    @Override
      public void mouseDragged(MouseEvent e )
      {
         x= e.getX();
         y= e.getY();
         repaint();

      }
  @Override
      public void mouseMoved(MouseEvent e)
      {

      }
      @Override
      public void actionPerformed(ActionEvent e)
      {
          String s = e.getActionCommand();
          if(s.equals("Red"))
              color = Color.red;
          else if(s.equals("Yellow"))
              color = Color.yellow;
          else if(s.equals("Blue"))
              color = Color.blue;
          else if(s.equals("Green"))
              color = Color.green;
          else
              color = Color.BLACK;

      }



  @Override
  public void paint(Graphics g)
  {
     g.setColor(color);
      g.fillOval(x, y, 4, 4);
  }

}
主类

public class Paint {
      package paint;

    public static void main(String[] args) {
        // TODO code application logic here
        PaintFrame Jf = new PaintFrame();

    }

}
当我执行这个程序时,屏幕上只显示第一个JButton。我必须将鼠标悬停在其他按钮上,以便它们可以显示在屏幕上


为什么会发生这种情况?

从您的标题中,我可以猜到您在覆盖中没有调用super的绘画方法——我是对的:

@Override
public void paint(Graphics g)
{
   // ********** no super call here! *******
   g.setColor(color);
   g.fillOval(x, y, 4, 4);
}
如果不这样做,就不允许组件进行重要的内部维护绘制,包括子组件的绘制和“脏”像素的移除

这:

可能会解决问题


话虽如此,我必须补充:

  • 不要直接在JFrame中绘制
  • 在扩展JPanel的类的
    paintComponent
    方法重写中进行绘制
  • 在JPanel的重写方法中调用
    super.paintComponent(g)
    (出于相同的原因)
使用BuffereImage的示例:

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

@SuppressWarnings("serial")
public class MainPaintPanel extends JPanel {
    private PaintPanel paintPanel = new PaintPanel();

    public MainPaintPanel() {
        MyMouse myMouse = new MyMouse();
        paintPanel.addMouseListener(myMouse);
        paintPanel.addMouseMotionListener(myMouse);
        JPanel btnPanel = new JPanel(new GridLayout(0, 1, 3, 3));
        addColorButton(btnPanel, Color.RED, "Red");
        addColorButton(btnPanel, Color.YELLOW, "Yellow");
        addColorButton(btnPanel, Color.BLUE, "Blue");
        addColorButton(btnPanel, Color.GREEN, "Green");        

        setLayout(new BorderLayout());
        add(paintPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.LINE_START);
    }

    class MyMouse extends MouseAdapter {
        Point p1 = null;

        private void moveOval(MouseEvent e) {
            if (p1 == null) {
                return;
            }
            Point p2 = e.getPoint();
            paintPanel.addLine(p1, p2);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            p1 = e.getPoint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            moveOval(e);
            p1 = e.getPoint();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            moveOval(e);
            p1 = null;
        }
    }

    private void addColorButton(JPanel btnPanel, Color color, String name) {
        JButton button = new JButton(new ButtonAction(name, color));
        button.setBackground(color);
        btnPanel.add(button);
    }

    class ButtonAction extends AbstractAction {        
        private Color color;

        public ButtonAction(String name, Color color) {
            super(name);
            this.color = color;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            paintPanel.setOvalColor(color);
        }
    }


    private static void createAndShowGui() {
        MainPaintPanel mainPanel = new MainPaintPanel();

        JFrame frame = new JFrame("Painting GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

非常感谢,所有按钮都显示出来了,但通过调用super.paint,它会更改我的program@rehanshakir:变化——怎么会这样?@rehanshakir:另外,在你的问题中,你没有告诉我们你的程序想要的行为,因此,我们无法猜测我的答案中断了什么功能。基本上,我的程序是一个简单的绘图程序,当我在方法paintComponent中调用super.paint并执行我的程序时,只有一个点出现在我的鼠标指针后面,框架上没有绘制任何内容。@rehanshakir:这是需要放在主体中的关键信息问题。如果你想画画,那么你将要画线,而不是点,否则快速鼠标拖动将显示为点。您需要绘制到BuffereImage或创建这些线的ArrayList,并在paintComponent方法中使用for循环绘制它们。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class MainPaintPanel extends JPanel {
    private PaintPanel paintPanel = new PaintPanel();

    public MainPaintPanel() {
        MyMouse myMouse = new MyMouse();
        paintPanel.addMouseListener(myMouse);
        paintPanel.addMouseMotionListener(myMouse);
        JPanel btnPanel = new JPanel(new GridLayout(0, 1, 3, 3));
        addColorButton(btnPanel, Color.RED, "Red");
        addColorButton(btnPanel, Color.YELLOW, "Yellow");
        addColorButton(btnPanel, Color.BLUE, "Blue");
        addColorButton(btnPanel, Color.GREEN, "Green");        

        setLayout(new BorderLayout());
        add(paintPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.LINE_START);
    }

    class MyMouse extends MouseAdapter {
        Point p1 = null;

        private void moveOval(MouseEvent e) {
            if (p1 == null) {
                return;
            }
            Point p2 = e.getPoint();
            paintPanel.addLine(p1, p2);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            p1 = e.getPoint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            moveOval(e);
            p1 = e.getPoint();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            moveOval(e);
            p1 = null;
        }
    }

    private void addColorButton(JPanel btnPanel, Color color, String name) {
        JButton button = new JButton(new ButtonAction(name, color));
        button.setBackground(color);
        btnPanel.add(button);
    }

    class ButtonAction extends AbstractAction {        
        private Color color;

        public ButtonAction(String name, Color color) {
            super(name);
            this.color = color;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            paintPanel.setOvalColor(color);
        }
    }


    private static void createAndShowGui() {
        MainPaintPanel mainPanel = new MainPaintPanel();

        JFrame frame = new JFrame("Painting GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
@SuppressWarnings("serial")
class PaintPanel extends JPanel {
    private static final int PREF_W = 800;
    private static final int PREF_H = 600;
    private static final int OVAL_WIDTH = 4;
    private static final Stroke BASIC_STROKE = new BasicStroke(OVAL_WIDTH);
    private BufferedImage img;
    private Color ovalColor;

    public PaintPanel() {
        img = new BufferedImage(PREF_W, PREF_W, BufferedImage.TYPE_INT_ARGB);
    }

    public void addLine(Point p1, Point p2) {
        if (img != null && ovalColor != null) {
            Graphics2D g2 = img.createGraphics();
            g2.setStroke(BASIC_STROKE);
            g2.setColor(ovalColor);
            g2.drawLine(p1.x, p1.y, p2.x, p2.y);
            g2.dispose();
            repaint();
        }
    }

    public void setOvalColor(Color ovalColor) {
        this.ovalColor = ovalColor;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }
}