2012-07-11 22 views
1

基本上我有一个试图绘制图形的JApplet(例如,g.drawOval(10,10,100,100),也包括JCompotents(即JButton)),重绘会变得非常古怪。有时,图形会笼络小工具或VIS-反之亦然。这是不可靠的,并导致不可预知的行为。使用图形和JApplet/Swing中的小部件绘图?

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

我已经与它试图重写玩耍了或手动绘制组件,更改顺序等,但认为我错过了一些非常基本的东西。任何人都有一个模板或使用g.drawXXX和JCom的正确方法potents?

+1

您需要在您绘制的地方以及任何其他相关代码中显示您的代码。否则,我们不知道你可能会做错什么。此外,请不要直接在JApplet中绘制,而应该在JPanel或其contentPane(它是一个JPanel)中绘制。确保绘制这个JPanel的paintComponent(...)方法。 – 2012-07-11 01:10:17

+1

检查[通常的嫌疑犯](http://stackoverflow.com/a/11389042/230513),并将您的代码与此['AnimationTest'](http://stackoverflow.com/a/3256941/230513)进行比较。 – trashgod 2012-07-11 01:17:25

+1

@ user1516346:当然在网站上有很多*例子,在这个网站上有一些我自己写的。不停寻找!而你的问题就是你在我的第一篇文章中没有遵循我的任何建议。你仍然直接在applet中绘图。 – 2012-07-11 02:06:25

回答

3

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

一定从来没有直接绘制在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); 
     } 
     } 
    } 
} 

另外,请检查秋千绘画教程包括Basic Painting TutorialAdvanced Painting Tutorial

对于一个伟大的书籍和更多,请看由Chet Haase和Romain Guy购买Filthy Rich Clients。你不会后悔购买!这是我拥有的最好的Java书籍之一。

+2

不客气。请阅读我在答案底部链接到的有关细节的教程。然后跑步,不要走到书店,买Haase和Guy的[Filthy Rich Clients](http://filthyrichclients.org/),去了解你需要知道的一切以及更多! – 2012-07-11 02:22:09