gpt4 book ai didi

java - boolean 值不适用于图形 java

转载 作者:行者123 更新时间:2023-11-30 08:39:55 25 4
gpt4 key购买 nike

这是我的代码

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);

}

关于java - boolean 值不适用于图形 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35935090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com