0

根据事件委托模型,我采用了一个处理程序类。

package simple;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonHandler implements ActionListener {

    MainFrame frame;

    public ButtonHandler(MainFrame frame) {
        this.frame = frame;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        MyThread thread = new MyThread(frame);
        Thread mthread = new Thread(thread);            
        mthread.start();
    }    
}

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,

一个用于创建框架的 MainFrame 类

package simple;

import java.awt.Graphics;    
import javax.swing.JButton;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {
    JButton btnStart = new JButton("Start");
    int xPos1,xPos2;    
    public MainFrame()
    {           
        setSize(700, 600);
        setLayout(null);
        setVisible(true);           
        xPos1=10;
        xPos2=600;
        btnStart.setBounds(590, 30, 100, 30);
        add(btnStart);
        btnStart.addActionListener(new ButtonHandler(this));            
        paint(null);            
        setDefaultCloseOperation(EXIT_ON_CLOSE);            
    }

    @Override
    public void paint(Graphics g) {
        g.drawString("Seed", xPos1, 50);
        g.drawString("Infotech", xPos2, 550);
    }
}

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

一个实现可运行接口的线程类

package simple;

public class MyThread implements Runnable {

    MainFrame frame;        

    public MyThread(MainFrame frame) {
        super();
        this.frame = frame;
    }

    @Override
    public void run() {

        while(true)
        {
            frame.repaint();
            try {
                frame.xPos1++;
                frame.xPos2--;
                Thread.sleep(10);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }               
        }
    }    
}

///////////////////////////////////////// /////////// 和一个仅用于主要方法的类

package simple;

public class Test {

    public static void main(String[] args) {
        new MainFrame();
    }
}

谁能说出我对java编程概念不熟悉的问题。

4

1 回答 1

1
  1. 覆盖paint顶级容器 ( JFrame)
  2. 不打电话super.paint(g);
  3. 打电话paint(null)
  4. setLayout(null)

通过查看在容器中执行自定义绘制布局组件来担任明星

代替使用 a Thread,您可能会发现 ajavax.swing.Timer更有用。查看Swing 中的并发以获取更多详细信息

于 2013-10-16T19:39:06.050 回答