这是我的代码
package javaapplication7;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Graphics2D;``
import java.util.*;
import java.io.*;
public class JavaApplication7 extends JPanel implements ActionListener{
JButton j = new JButton();
boolean drawHello = true;
boolean drawWorld = false;
String hello = "Hello";
String World = "World";
public JavaApplication7(){
this.setLayout(new BorderLayout());
add(j,BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
boolean drawWorld = true;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (drawHello)
g.drawString(hello, 50, 50);
if (drawWorld)
g.drawString(World, 70, 70);
}
public static void main(String[] args) {
JFrame f = new JFrame("Swing Paint Demo");
JavaApplication7 j7 = new JavaApplication7();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250,250);
f.setVisible(true);
f.add(j7);
}
}
我不明白您已经定义了一个Boolean
,然后actionPerformed()
只需删除Boolean
以下内容就创建了另一个:
public void actionPerformed(ActionEvent e) {
drawWorld = true;
repaint();
}
因为您已经在那里创建了它:
public class JavaApplication7 extends JPanel implements ActionListener{
JButton j = new JButton();
boolean drawHello = true;
boolean drawWorld = false; //<------
还添加
j.addActionListener(this);
像这样 :
public JavaApplication7(){
this.setLayout(new BorderLayout());
j.addActionListener(this);
add(j,BorderLayout.NORTH);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句