图形和与JApplet的部件绘图/摇摆?(Drawing with graphics and wit

2019-10-16 23:45发布

基本上我有一个JApplet的,试图与图形(即g.drawOval(10,10,100,100),还包括JCompotents(即一个JButton),什么情况是,重绘能得到真正古怪的画。

有时,图形会笼络小工具或VIS-反之亦然。 这是不可靠的,并导致不可预知的行为。

(巴顿也永远是这些图形的顶部)

我打它周围试图推翻或手工绘制组件,改变订单等,但觉得我失去了一些东西很基本的在这里。 任何人都有一个模板或同时使用g.drawXXX和JCompotents正确的方法是什么?

Answer 1:

同样,只要按照我的建议,

可以肯定从来没有直接在JApplet的,而是在一个JPanel或在其contentPane的(这是一个JPanel)来绘制。 确保在此JPanel的的paintComponent(...)方法来绘制。

和它的工作原理:

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);
         }
      }
   }
}

另外,请检查秋千绘画教程包括基本绘画教程和高级教程绘画 。

关于这一点,更多的是伟大的书,请考虑购买巨富客户端通过切特·哈泽和罗曼盖伊。 你会不会后悔购买! 这是最好的Java书籍,我自己一个人。



文章来源: Drawing with graphics and with widgets in JApplet/Swing?