首先这是一项家庭作业,所以解释和指针比平面解决方案更受欢迎。我们正在学习swing,并且正在练习单独的ActionListeners(奖金问题,为什么你会在一个内部类中使用一个单独的类,看起来内部类更简单,不容易出错而不会丢失任何真正的能力)。我遇到的问题是将Frame作为参数传递,以便单独的类可以访问它需要的工具,然后使用单独的类实际更改显示。该项目应该像幻灯片一样工作,有一个计时器作为默认开关,但也可以实现手动移动的按钮。ActionListener在一个单独的类
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.*;
import java.io.File;
public class SliderFrame extends JFrame{
public SliderFrame(){
File file1 = new File("images"); //change as necessary
File file = new File("images\\CMU");
File[] paths;
paths = file.listFiles();
//file1
ImageIcon left = new ImageIcon("backward.png");
ImageIcon right = new ImageIcon("forward.png");
JButton btnLeft = new JButton(left);
btnLeft.addActionListener(new MyActionListener(this));
JButton btnRight = new JButton(right);
btnRight.addActionListener(new MyActionListener(this));
JTextField jtfTitle = new JTextField("Welcome to CMU!");
JLabel jlbMain = new JLabel();
new Timer(2000, new MyActionListener(this)).start();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add("PAGE_START", jtfTitle);
panel.add("Center", jlbMain);
panel.add("LINE_START", btnLeft);
panel.add("LINE_END", btnRight);
add(panel);
setTitle("CPS240 SlideShow");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
JFrame frame = new SliderFrame();
btnRight.addActionListener(new MyActionListener(frame));
}
}
然后我的ActionListener类
import java.awt.event.*;
import javax.swing.*;
//does it need to extend SliderFrame? Originally I thought it would help with some of my errors
public class MyActionListener extends SliderFrame implements ActionListener {
JFrame frame;
public MyActionListener(JFrame frame) {
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof Timer){
//here's where I need to be able to change the 'main' label in the frame
} else if(e.getSource() == btnRight){
//trying to figure out if the left or right button was pushed
} else{
}
}
}
我不知道如果我的错误的根源在于我如何设置格式下手,或者如果我只是没有得到的东西。任何帮助或意见将不胜感激。
大部分情况都是合理的,并且已经实现,但是我仍然遇到了一个错误,试图将各种组件从SliderFrame类实现到MyActionListener类,以发送回SliderFrame类。 ex。我需要MAL能够使用路径[]发送到SF类中的下一个/上一个幻灯片方法,以了解它在哪里以及它将要发往哪里。这仅仅是错误地引入SF的问题? – Thailer
所以,'paths'应该是一个实例字段。当前幻灯片的索引也应该是一个实例字段。有关更多详细信息,请参阅[了解班成员](https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html)。 – MadProgrammer