class MyPanel extends JPanel
{
private JButton btn;
private JButton btn1;
private Graphics g = this.getGraphics();public MyPanel()
{
btn = new JButton("click me");
add(btn);
btn1 = new JButton("click me");
add(btn1);
btn1.addActionListener(new actionClick());
btn.addActionListener(new actionClick());
}public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(20,20,200,200);
}class actionClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== btn1)
g.drawString("btn1 clicked",94,68);//此处如果换为System.out.println("btn clicked");////////////////////////////////////////////////则不会出现异常,为什么?
if(e.getSource()== btn)
g.drawString("btn clicked",50,80);//此处如果换为System.out.println("btn clicked");
/////////////////////////////////////////////则不会出现异常,为什么? }
}
}//运行之后,会有异常不知道是什么原因。
{
private JButton btn;
private JButton btn1;
private Graphics g = this.getGraphics();public MyPanel()
{
btn = new JButton("click me");
add(btn);
btn1 = new JButton("click me");
add(btn1);
btn1.addActionListener(new actionClick());
btn.addActionListener(new actionClick());
}public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(20,20,200,200);
}class actionClick implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== btn1)
g.drawString("btn1 clicked",94,68);//此处如果换为System.out.println("btn clicked");////////////////////////////////////////////////则不会出现异常,为什么?
if(e.getSource()== btn)
g.drawString("btn clicked",50,80);//此处如果换为System.out.println("btn clicked");
/////////////////////////////////////////////则不会出现异常,为什么? }
}
}//运行之后,会有异常不知道是什么原因。
现在eclipse很不爽fangshk2007 eclipse怎么调试?能简单的说一下吗?
我想我点击button后才执行 g.drawString("btn1 clicked",94,68);
按你说的在paintComponent方法里做?
那我应该怎么做呢??????
import java.awt.event.*;
import javax.swing.*;public class MyPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton btn;
private JButton btn1;
private Graphics g;
private int x;//绘图的X坐标
private int y;//绘图的Y坐标
public MyPanel() {
btn = new JButton("click me1");
add(btn);
btn1 = new JButton("click me");
add(btn1);
btn1.addActionListener(new actionClick());
btn.addActionListener(new actionClick());
x = 100;
y = 100;
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
g = this.getGraphics();
g.drawString("btn clicked", x, y);
}
class actionClick implements ActionListener {
public void actionPerformed(ActionEvent e){
if(e.getSource() == btn1) {
x = 160;
y += 10;
update(g);
}
if(e.getSource() == btn) {
x = 100;
y += 10;
update(g);
}
}
}
public static void main(String arg[]) {
JFrame f = new JFrame();
f.add(new MyPanel());
f.setSize(400, 400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}