我只想数点jlabel。我想,我已经尝试了网站上发布的所有解决方案,但我找不到任何解决方案。我是初学者,有一个月的时间学习Java。如果我的问题太愚蠢,我很抱歉。
package asdf;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.JLabel;
public class asd extends JFrame implements ActionListener {
int a=0; // variable
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
asd window = new asd();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public asd() {
super();
Timer time=new Timer(1000, this);
time.start();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(20, 11, 137, 111);
frame.getContentPane().add(panel);
panel.setLayout(null);
***JLabel Jtable = new JLabel();
Jtable.setBounds(0, 25, 127, 58);
Jtable.setText("" + a);
panel.add(Jtable);***
System.out.println(a); //it is counting on console but in Jlabel variable is not.
}
@Override
public void actionPerformed(ActionEvent arg0) {
a++;
initialize();
}
}
我只想数点jlabel。我想,我已经尝试了网站上发布的所有解决方案,但我找不到任何解决方案。我是初学者,有一个月的时间学习Java。如果我的问题太愚蠢,我很抱歉。
答案 0 :(得分:0)
您不应该在执行的每个操作上初始化新框架和所有组件,您应该只更新标签的文本。您可以通过JLabel.setText https://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html#setText(java.lang.String)
执行此操作int a = 0; // variable
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
asd window = new asd();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public asd() {
super();
Timer time=new Timer(1000, this);
time.start();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private JLabel label;
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(20, 11, 137, 111);
frame.getContentPane().add(panel);
panel.setLayout(null);
label = new JLabel();
label.setBounds(0, 25, 127, 58);
label.setText("" + a);
panel.add(label);
System.out.println(a); //it is counting on console but in Jlabel variable is not.
}
@Override
public void actionPerformed(ActionEvent arg0) {
a++;
label.setText("" + a);
}