我对Java非常陌生。我决定(从零开始)将抽搐脚趾编码作为练习。
无论如何,我试图让'JLabel标签‘的变化,当我点击;从1,然后2,等等,最终,它将改变为其他东西,而不是数字。但是,就目前而言,它适用于一项测试。
‘System.out.println(“点击次数:”+ mouseIn);’工作良好,并产生我想要的输出。在这里可以看到控制台和JFrame/JPanel/JLabel的图片:
( JFrame中的小1是JLabel。我想要匹配控制台中的输出。
我搜索过,搜索过,并尝试了我所知道的一切(这不是很多!)我不能让这该死的事情起作用.我只是在寻求一些指导。主要方法包括构建JFrame/Panel。
代码如下:
来自主类,名为(namone.java出于自己的原因将其命名为此):
public void run(JPanel p) //Takes panel from main method {
for(int i = 0; i < ticList.length; i++){
ticList[i] = new JButton(buttonText); //For every position in
//ticList[], create a JButton object
p.add(ticList[i]);
ticList[i].setPreferredSize(new Dimension(140,140));
ticList[i].addMouseListener(mouse); //Load mouseListner
}
//Set mouseIn to click value in MouseEvents Class
int mouseIn = mouse.getClicks();
//Set text value to text value in MouseEvents class
text = mouse.getText();
//Output...
System.out.println("Number of clicks: " + mouseIn); //For testing
String mouse = Integer.toString(mouseIn); //Convert mouseIn value (from MouseEvents.java) to mouse
JLabel label = new JLabel(); //New JLabel
p.add(label); //Add label to screen
label.setText(mouse); //Set the text of the label to value of mouse
System.out.println(mouse); //For testing
//So I can see if it's working (clicks wise)
}
然后是我的MouseEvents.java类的代码:
public class MouseEvents extends namone implements MouseListener {
int clicks = 1;
String text = "first"; //For testing purposes
public namone game = new namone();
public int getClicks(){
return clicks;
}
public String getText(){
return text;
}
public int intToString(){
Integer.toString(clicks);
return clicks;
}
@Override
public void mouseClicked(MouseEvent e) {
clicks++;
intToString();
JPanel p = new JPanel();
text = "" + clicks;
game.run(p);
}
就像我说的。我对Java非常陌生,我正在努力学习如何用它开发应用程序。我相信这是我自己的无知造成的。
谢谢。
发布于 2014-08-18 09:22:17
假设mouse
是您编写的MouseEvents类型,一种可能是需要将mouse.getText()
传递给对label.setText(.)
的调用。
不管怎么说,你的游戏设置方式对我来说有点奇怪。每当有人点击时,创建一个全新的JPanel
的原因是什么?为什么不维护原始的JPanel并更新它呢?我个人会将一个自定义ActionListener附加到每个JButton上,每次单击按钮时都会运行一些代码。如果这个ActionListener是一个内部类,它还可以查看定义JButton的作用域中的变量。
https://stackoverflow.com/questions/25368339
复制相似问题