【发布时间】:2015-04-07 04:23:54
【问题描述】:
首先,这是一项家庭作业,因此解释和指示优于平面解决方案。我们正在学习摇摆,并且正在练习单独的类 ActionListeners(额外的问题,你为什么要在内部类上使用单独的类,看起来内部类更简单,更不容易出错,而不会失去任何真正的能力)。我遇到的问题是将 Frame 作为参数传递,以便单独的类可以访问它需要的工具,然后使用单独的类来实际更改显示。该项目应该像幻灯片一样工作,有一个计时器作为默认开关,但也实现了手动移动的按钮。
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{
}
}
}
我不确定我的错误的根源在于我如何设置开始的格式,或者我只是没有得到任何东西。任何帮助或意见将不胜感激。
【问题讨论】: