Swing问题,绘制在JTabbedPane上

时间:2011-11-27 20:18:41

标签: swing jpanel jtabbedpane drawstring

在绘制JTabbedPane中的JPanel时,我很难理解并解决问题 基本上我有这个小应用程序绘制统计图形,它是一个简单的JFrame与JTabbedPane。 现在,JTabbedPane有两个选项卡,每个选项卡包含一个JPanel(扩展),一个javax.swing.Timer在按下开始按钮后启动,并在一个JPanel上绘制图形,每秒一个新线,到目前为止一直很好。 如果在计时器运行并在面板上绘图时,我选择另一个选项卡(它仍为空),我看到drawString方法开始在所选面板上绘图,该面板不包含对drawString方法的任何调用, 我将粘贴相关代码:

public class Monitor extends JPanel{

**private Timer timer=new Timer(1000,new PerformanceEvent(this));**


public Monitor(){

    this.setBackground(Color.BLACK);
    this.setPreferredSize(new Dimension(400,211));
    this.setBounds(new Rectangle(16,44,400,211));
    this.setVisible(true);

}

/**
 * This method contains the Graphoc tool to draw on the panel
 * @param g
 */
 public void analize(Graphics g){

if((ammountOfTimesAnalizeCalled / 10)==1){


  g.setColor(Color.red);
  g.drawLine(left1, high1, left2, high2);
  //print high2 variable on file
  Performance.report(high2);

  prepareForNext();
  ammountOfTimesAnalizeCalled++;

  System.out.println(ammountOfTimesAnalizeCalled);
}


 /**
  * This method is used by the GUI to start the timer<br/>
  * The timer starts and will  calls analize
  */
 public void start(){

     timer.start();
 }

     /**
      * This method stops the TimerTask
      */
     public void stop(){
         timer.stop();
     }

}

我还没有报告analize方法的功能,因为它的长而不相关,都是由drawString完成的 这里是空面板,在jtabbed窗格的第二个标签中设置,你可以看到它什么也没做

public class Informations extends JPanel{

/**
 * The constructor initializes the panel's appearence
 */
public Informations(){

    this.setBackground(Color.BLACK);
    this.setPreferredSize(new Dimension(400,211));
    this.setBounds(new Rectangle(16,44,400,211));
    this.setVisible(true);
}

}

JTabbedPane

public class MyPane extends JTabbedPane{

private Monitor monitor=new Monitor();
private Informations informations=new Informations();

public MyPane(){
    monitor.setBounds(new Rectangle(5, 5, 400, 211));
    this.setPreferredSize(new Dimension(420,250));
    this.setBounds(new Rectangle(16,44,420,250));
    this.setVisible(true);
    this.addTab("Performance", monitor);
    this.addTab("Informations", informations);
}

}

这是计时器中的事件处理程序:

public class PerformanceEvent implements ActionListener{

private Monitor monitor=null;

public PerformanceEvent(Monitor monitor){

    this.monitor=monitor;
}

/**
 * Perform the drawing action
 */
public void actionPerformed(ActionEvent event) {

    monitor.analize(monitor.getGraphics());
}

}

希望你有建议,thx

1 个答案:

答案 0 :(得分:0)

你的问题确实很奇怪。从上面的代码看,一切似乎都很好。你能测试一下吗?由于绘图只发生在扩展JPanel的Monitor-class内部,而不是抛出Graphics-object,尝试使用Graphics g = getGraphics();在“analize()”方法中获取Graphics对象。 我不确定它会解决任何问题,但是让一个班级把另一个班级的东西放到现有的东西上似乎很奇怪。