首先這是一項家庭作業,所以解釋和指針比平面解決方案更受歡迎。我們正在學習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