Java 无法将变量传递给其他类
我正在尝试创建一个计时器,该计时器将显示在JLabel内部,我知道代码本身的工作原理与我使用System.out.println尝试的一样,但我不知道如何使另一个类看到JLabel 我是一个完全的初学者,从昨天早上开始就一直在努力想办法。我试着用谷歌搜索,看视频教程,阅读教程,找到类似的问题,使用getter和setter,使用不同的变量。没有任何帮助。我确实意识到这是一个非常容易的问题,但我无法解决它,我真的非常感谢任何形式的帮助 包含计时器代码的类:Java 无法将变量传递给其他类,java,Java,我正在尝试创建一个计时器,该计时器将显示在JLabel内部,我知道代码本身的工作原理与我使用System.out.println尝试的一样,但我不知道如何使另一个类看到JLabel 我是一个完全的初学者,从昨天早上开始就一直在努力想办法。我试着用谷歌搜索,看视频教程,阅读教程,找到类似的问题,使用getter和setter,使用不同的变量。没有任何帮助。我确实意识到这是一个非常容易的问题,但我无法解决它,我真的非常感谢任何形式的帮助 包含计时器代码的类: package Timernew
package Timernew;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class newTimer {
Timer timer = null;
int counter = 5;
int delay = 1500;
//method that will be called when the timer needs to start
public void startTimer() {
ActionListener action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (counter == 0) {
timer.stop();
lblTimerE.setText("Time up");
} else {
lblTimerE.setText("Wait for " + counter + " sec");
counter--;
}
}
}; //end of action performed statement
timer = new Timer(delay, action);
timer.setInitialDelay(0);
timer.start(); //this will start the timer
} //end of method
}
package Timernew;
import javax.swing.JLabel;
public class Easy extends javax.swing.JFrame {
newTimer time = new newTimer();
/**
* Creates new form Easy
*/
public Easy() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblTimerE = new javax.swing.JLabel();
btnStart = new javax.swing.JButton();
lblWordE = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(204, 255, 0));
lblTimerE.setText(" ");
btnStart.setText("Start");
btnStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStartActionPerformed(evt);
}
});
lblWordE.setText(" ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(134, 134, 134)
.addComponent(lblTimerE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 243, Short.MAX_VALUE)
.addComponent(btnStart)
.addGap(58, 58, 58))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(196, 196, 196)
.addComponent(lblWordE, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(lblTimerE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(btnStart)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addComponent(lblWordE, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(54, 54, 54))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
time.startTimer();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Easy().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton btnStart;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel lblTimerE;
public javax.swing.JLabel lblWordE;
// End of variables declaration
}
包含JLabel和触发器按钮的类:
package Timernew;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class newTimer {
Timer timer = null;
int counter = 5;
int delay = 1500;
//method that will be called when the timer needs to start
public void startTimer() {
ActionListener action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (counter == 0) {
timer.stop();
lblTimerE.setText("Time up");
} else {
lblTimerE.setText("Wait for " + counter + " sec");
counter--;
}
}
}; //end of action performed statement
timer = new Timer(delay, action);
timer.setInitialDelay(0);
timer.start(); //this will start the timer
} //end of method
}
package Timernew;
import javax.swing.JLabel;
public class Easy extends javax.swing.JFrame {
newTimer time = new newTimer();
/**
* Creates new form Easy
*/
public Easy() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblTimerE = new javax.swing.JLabel();
btnStart = new javax.swing.JButton();
lblWordE = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(204, 255, 0));
lblTimerE.setText(" ");
btnStart.setText("Start");
btnStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStartActionPerformed(evt);
}
});
lblWordE.setText(" ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(134, 134, 134)
.addComponent(lblTimerE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 243, Short.MAX_VALUE)
.addComponent(btnStart)
.addGap(58, 58, 58))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(196, 196, 196)
.addComponent(lblWordE, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(lblTimerE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(btnStart)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addComponent(lblWordE, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(54, 54, 54))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
time.startTimer();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Easy().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton btnStart;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel lblTimerE;
public javax.swing.JLabel lblWordE;
// End of variables declaration
}
我复制了您的代码,并对其进行了一些调整:因为您似乎需要在
NewTimer
类中使用JLabel,所以我将其作为构造函数参数传递。我没有触及代码的其余部分,因为这不是问题的一部分
public class Easy extends javax.swing.JFrame {
/**
* @param args
* the command line arguments
*/
public static void main(final String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (final javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (final ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final InstantiationException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> new Easy().setVisible(true));
}
NewTimer time;
// Variables declaration - do not modify
public javax.swing.JButton btnStart;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel lblTimerE;
public javax.swing.JLabel lblWordE;
// End of variables declaration
/**
* Creates new form Easy
*/
public Easy() {
initComponents();
}
private void btnStartActionPerformed(final java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
time.startTimer();
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form
* Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblTimerE = new javax.swing.JLabel();
btnStart = new javax.swing.JButton();
lblWordE = new javax.swing.JLabel();
time = new NewTimer(lblTimerE);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// Rest of your code...
}// </editor-fold>
}
public class NewTimer {
JLabel lblTimerE;
Timer timer = null;
int counter = 5;
int delay = 1500;
public NewTimer(final JLabel lbl) {
lblTimerE = lbl;
}
// method that will be called when the timer needs to start
public void startTimer() {
final ActionListener action = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent event) {
if (counter == 0) {
timer.stop();
lblTimerE.setText("Time up");
} else {
lblTimerE.setText("Wait for " + counter + " sec");
counter--;
}
}
}; // end of action performed statement
timer = new Timer(delay, action);
timer.setInitialDelay(0);
timer.start(); // this will start the timer
} // end of method
}
public类Easy扩展javax.swing.JFrame{
/**
*@param args
*命令行参数
*/
公共静态void main(最终字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*
*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。有关详细信息,请参阅
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
试一试{
对于(最终javax.swing.UIManager.LookAndFeelInfo信息:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(最终类NotFoundException ex){
getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(最终实例化异常异常){
getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(最终非法访问例外){
getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(final javax.swing.UnsupportedLookAndFeelException ex){
getLogger(Easy.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(()->new Easy().setVisible(true));
}
新时间;
//变量声明-不修改
public javax.swing.JButton btnStart;
public javax.swing.JPanel jPanel1;
public javax.swing.JLabel lblTimerE;
public javax.swing.JLabel lblWordE;
//变量结束声明
/**
*轻松创建新表单
*/
公共轻松(){
初始化组件();
}
私有void btnStartActionPerformed(最终java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
time.startTimer();
}
/**
*从构造函数中调用此方法来初始化表单。警告:不要修改此代码。此方法的内容始终由表单重新生成
*编辑。
*/
@抑制警告(“未选中”)
//
私有组件(){
jPanel1=newjavax.swing.JPanel();
lblTimerE=newjavax.swing.JLabel();
btnStart=newjavax.swing.JButton();
lblWordE=newjavax.swing.JLabel();
时间=新的新时间(lbltimer);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
//剩下的代码。。。
}//
}
公共类新定时器{
JLabel-lblTimerE;
计时器=空;
int计数器=5;
int延迟=1500;
公共新计时器(最终JLabel lbl){
lblTimerE=lbl;
}
//方法,该方法将在计时器需要启动时调用
公共无效startTimer(){
最终ActionListener操作=新建ActionListener(){
@凌驾
已执行的公共无效操作(最终操作事件){
如果(计数器==0){
timer.stop();
lblTimerE.setText(“时间到了”);
}否则{
lblTimerE.setText(“等待”+计数器+“秒”);
计数器--;
}
}
};//执行的操作结束语句
定时器=新定时器(延迟、动作);
timer.setInitialDelay(0);
timer.start();//这将启动计时器
}//方法结束
}
请发布一个lbltimer
变量,该变量在newTimer
类中不存在(该类应称为newTimer
,顺便说一句)-->您需要将其作为参数传递,或通过getter访问它感谢您的帮助,因为我使用的是netbeans,我无法编辑代码的某些部分,主要是“时间=新的新时间(lbltimer);“。我将尝试更多,然后以另一种方式从头开始。为什么您不能编辑部分代码?它无法编译?(可能是正常的…)