Drawing with graphics and with widgets in JApplet/Swing?

荒凉一梦 提交于 2019-12-11 13:04:06

问题


Basically I have a JApplet that tries to draw with the graphics (ie, g.drawOval(10,10,100,100) and also include JCompotents (ie. JButton). What happens is that the repaint can get really wacky.

Sometimes the graphics will draw over widgets or vis-versa. It's not reliable and leads to unpredictable behavior.

(Button also always be on top of those graphics)

I've played around with it trying to override or manually draw components, changing orders, etc, but think I'm missing something very fundamental here. Anyone have a template or the correct way to use both g.drawXXX and JCompotents?


回答1:


Again, just follow what I recommended,

be sure never to draw directly in the JApplet but rather in a JPanel or in its contentPane (which is a JPanel). Make sure to draw in this JPanel's paintComponent(...) method.

and it works:

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;

import javax.swing.*;

public class Test2 extends JApplet {


   public void init() {
      try {
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
               Test2BPanel panel = new Test2BPanel();
               setContentPane(panel);
            }
         });
      } catch (InvocationTargetException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }


}

class Test2BPanel extends JPanel {
   private String[] backgroundImageFileNames = { "test", "test", "test" };

   private JButton refreshButton;
   private JComboBox backgroundList;

   public Test2BPanel() {

      setBackground(Color.white);

      setLayout(new FlowLayout());

      refreshButton = new JButton("replant new forest");
      refreshButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {

         }

      });
      add(refreshButton);

      backgroundList = new JComboBox(backgroundImageFileNames);
      backgroundList.setSelectedIndex(2);
      add(backgroundList);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      paintIt(g);
   }

   public void paintIt(Graphics g) {
      for (int i = 0; i < 200; i++) {
         for (int j = 0; j < 200; j++) {
            g.setColor(Color.red);
            g.drawOval(10 * i, j, 10, 10);
         }
      }
   }
}

Also, please check the Swing painting tutorials including the Basic Painting Tutorial and the Advanced Painting Tutorial.

For a great book on this and more, please look into buying Filthy Rich Clients by Chet Haase and Romain Guy. You won't regret the purchase! It's one of the best Java books that I own.



来源:https://stackoverflow.com/questions/11424180/drawing-with-graphics-and-with-widgets-in-japplet-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!