这个问题解释了,无论我做什么,我都无法修改我的布尔字段。以下代码是我正在进行的任务中的一个类,但我需要能够修改布尔值才能执行此操作,因为某些原因我无法做到这一点因此我不确定是什么&。 #39; s继续:
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class Test extends JPanel implements ActionListener {
private String senderName,reciverName,message;
private int w=250,velx=13,x=330,senderW=350,senderH=100,reciverW=350,reciverH=270,messageW=350,messageH=50;
private Timer tm = new Timer(50, this);
private boolean something=true;
public void setSomething(boolean s){
something=s;
}
public Test(String s1,String s2, String s3){
String cutString1 = s1.substring(0, Math.min(15, s1.length()));
String cutString2 = s2.substring(0, Math.min(15, s2.length()));
String cutString3 = s3.substring(0, Math.min(30, s3.length()));
senderName=cutString1;
reciverName=cutString2;
message=cutString3;
setSomething(false);
//Even though I set it to false it still holds true and won't print it out
if(something=false){
System.out.print("Something");
}
setLayout(null);
timer();
}
public void timer(){
tm.setInitialDelay(10000);
tm.start();
}
public void paintComponent(Graphics g){
setOpaque(true);
super.paintComponent(g);
Font font1 = new Font( "TimesRoman", Font.BOLD, 17);
Font font2 = new Font( "TimesRoman", Font.BOLD, 30);
g.setColor(Color.CYAN);
g.fillRect(330, 30, 250, 390);
g.setFont(font1);
g.setColor(Color.BLUE);
g.drawString(message, messageW, messageH);
g.setColor(Color.RED);
g.fillRect(x, 30, w, 390);
g.setColor(Color.BLUE);
g.setFont(font2);
g.drawString(senderName, senderW, senderH);
g.drawString("To",430, 200);
g.drawString(reciverName, reciverW, reciverH);
}
public void anime(){
w=w-velx;
repaint();
}
public void actionPerformed(ActionEvent e){
anime();
}
public static void main(String[] args){
JFrame frame2 = new JFrame();
frame2.add(new Test("something","something","something"));
frame2.setTitle("Title");
frame2.setSize(700,500);
frame2.setResizable(true);
frame2.setLocationRelativeTo(null);
frame2.setVisible(true);
}
}
答案 0 :(得分:4)
您使用分配检查变量something
,该变量始终为false
,因此永远不会达到您的print
语句:
if (something = false) {
使用布尔检查的简短形式可以避免这种类型的错误:
if (!something) {
答案 1 :(得分:2)
if语句由一个布尔表达式后跟一个或 更多陈述。
更改此
if(something=false){
System.out.print("Something");
}
与
if(!something){ // for false check }
或
if(something) // for true check
示例为什么if(boolean = boolean)不是编译时错误
public static void main(String[] args) {
boolean test = true;
int a = 0;
boolean test1 = false;
test1 = (test = true); // no error boolean expression
test = (a = 1); // compile error not a boolean expression
if(test = false)
{
}
System.out.println("" + test);
}