gpt4 book ai didi

java - 为计时器创建 ActionListener

转载 作者:行者123 更新时间:2023-11-30 02:42:26 25 4
gpt4 key购买 nike

我在声明 ActionListener 和创建新 ActionEvent 的细节方面遇到了麻烦。我的目标是创建一个 java.swing.Timer 来运行一些代码来继续播放幻灯片,我只是在努力正确声明计时器以及与之相关的操作。

public abstract class Actions implements ActionListener{
public ActionListener TimePANG = new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){

waitTime = Integer.valueOf(lblWaitput.getText());

if (waitTime <= 0){
waitTime = 60;
}

// METHOD TO CLEAR UP DEBRIS AND TO SPLIT INTO ARRAY
temp = txtList.getText();
temp = temp.toLowerCase();
selects = temp.split(" ");
for (i = 0; i < selects.length; i++){ //CLEANS UP VARIABLES FOR A PROPER PATH TO GRAB IMAGES FROM
selects[i] = "/SlideShow/" + selects[i] + ".jpg";
selectcount++;
} // END OF CLEANING

//START OF SLIDE SHOW
for (x = 0; x <= selectcount; x++){//THE LOOP THAT CYCLES THROUGH THE IMAGES
lblDisplay.setIcon(null);
System.out.println(selects[x]); //THE VARIABLE WHICH THE IMAGE IS IN
lblDisplay.setIcon(new javax.swing.ImageIcon(getClass().getResource(selects[x]))); //DISPLAYING IMAGE
}
}
};
}

我的完整代码如下。

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SlideShow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
*
* @author palaceag196
*/
public class MainSlides extends javax.swing.JFrame{

String[] options = {"Soccer","Basketball","Football","Hockey","Ravioli","Banana","Pizza","Hotdog","Cat","Dog","Bird","Hamster"};
String temp;
String[] selects;
int selectcount;
int i, x;
int waitTime;
// new ImageIcon(getClass().getResource(temp))
/**
* Creates new form MainSlides
*/

public MainSlides() {
initComponents();
}
public abstract class Actions implements ActionListener{
public ActionListener TimePANG = new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){

waitTime = Integer.valueOf(lblWaitput.getText());

if (waitTime <= 0){
waitTime = 60;
}

// METHOD TO CLEAR UP DEBRIS AND TO SPLIT INTO ARRAY
temp = txtList.getText();
temp = temp.toLowerCase();
selects = temp.split(" ");
for (i = 0; i < selects.length; i++){ //CLEANS UP VARIABLES FOR A PROPER PATH TO GRAB IMAGES FROM
selects[i] = "/SlideShow/" + selects[i] + ".jpg";
selectcount++;
} // END OF CLEANING

//START OF SLIDE SHOW
for (x = 0; x <= selectcount; x++){//THE LOOP THAT CYCLES THROUGH THE IMAGES
lblDisplay.setIcon(null);
System.out.println(selects[x]); //THE VARIABLE WHICH THE IMAGE IS IN
lblDisplay.setIcon(new javax.swing.ImageIcon(getClass().getResource(selects[x]))); //DISPLAYING IMAGE
}
}
};
}
/**
* 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() {

jScrollPane1 = new javax.swing.JScrollPane();
listSelect = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
txtList = new javax.swing.JTextArea();
lblWaitput = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
btnStart = new javax.swing.JButton();
lblDisplay = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

listSelect.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Soccer", "Basketball", "Football", "Hockey", "Ravioli", "Banana", "Pizza", "Hotdog", "Cat", "Dog", "Bird", "Hamster" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
listSelect.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listSelectMouseClicked(evt);
}
});
jScrollPane1.setViewportView(listSelect);

txtList.setColumns(12);
txtList.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
txtList.setLineWrap(true);
txtList.setRows(12);
txtList.setAutoscrolls(false);
txtList.setFocusable(false);
jScrollPane2.setViewportView(txtList);

lblWaitput.setText("60");
lblWaitput.setToolTipText("Input wait time here.");

jLabel1.setText("Wait Time:");

btnStart.setText("Start The Show");
btnStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStartActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblWaitput, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
.addComponent(btnStart))
.addComponent(lblDisplay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblWaitput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(btnStart))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblDisplay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);

pack();
}// </editor-fold>

private void listSelectMouseClicked(java.awt.event.MouseEvent evt) {

txtList.setText(txtList.getText() + options[listSelect.getSelectedIndex()] + " ");

// TODO add your handling code here:
}

private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
Timer time = new Timer(waitTime, TimePANG);
time.start();

// END OF SLIDES NOTHING FURTHER
}


/**
* @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(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainSlides.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 MainSlides().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnStart;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel lblDisplay;
private javax.swing.JTextField lblWaitput;
private javax.swing.JList listSelect;
private javax.swing.JTextArea txtList;
// End of variables declaration

}

最佳答案

使用计时器的目的是消除所有循环。

您有一个对象数组,因此您还需要一个索引来跟踪当前正在显示的对象。

因此,当您单击按钮时,您所做的就是启动计时器,然后 ActionListener 将根据当前索引显示对象。

因此“开始”按钮的 ActionListener 中的代码可能类似于:

ActionListener al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String fileName = "..." + selects[selectIndex] + ".jpg";
Icon icon = new ImageIcon( filename );
label.setIcon( icon );
selectIndex++;

if (selectIndex) > selects.length)
selectIndex = 0;
}
};

...

Timer timer = new Timer(waitTime, al);
timer.start();

关于java - 为计时器创建 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248624/

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