我有一个JFrame,在其中我以一种适合自己喜好的顺序自定义了按钮。看起来像这样:Menu for Traverse Operation
我应该在ActionListener类中使用什么操作来调用已声明的按钮?我声明了三个JButton,但是我只在ActionListener类上调用了一个按钮来显示错误。错误是(e.getSource == b1)。不知道要替换什么,导致该行在我的JPanel类中起作用。
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
class FeedTheDogMenu extends JFrame{
private JFrame f = new JFrame("Operation Menu");
Selection handle;
FeedTheDogMenu(){
handle = new Selection();
JButton b1 = new JButton("Forward Traverse");
b1.setBounds(20, 30, 150, 25);
JButton b2 = new JButton("Backward Traverse");
b2.setBounds(20, 60, 150, 25);
JButton b3 = new JButton("Random Traverse");
b3.setBounds(20, 90, 150, 25);
JLabel label = new JLabel();
label.setBounds(25, 10, 450, 15);
label.setText("Choose an operation: ");
JLabel l1 = new JLabel();
l1.setBounds(195, 28, 200, 15);
l1.setText("In this menu, you will be");
JLabel l2 = new JLabel();
l2.setBounds(195, 46, 200, 15);
l2.setText("able to witness three");
JLabel l3 = new JLabel();
l3.setBounds(195, 64, 200, 15);
l3.setText("different operations");
JLabel l4 = new JLabel();
l4.setBounds(195, 82, 200, 15);
l4.setText("in which the agent will");
JLabel l5 = new JLabel();
l5.setBounds(195, 100, 200, 15);
l5.setText("perform to find the dog.");
JLabel author = new JLabel();
author.setBounds(23, 160, 200, 15);
author.setText("Feed the Dog v 0.1.3");
JLabel pow = new JLabel();
pow.setBounds(23, 173, 200, 15);
pow.setText("Powered by BlueJ");
JLabel intelprop = new JLabel();
intelprop.setBounds(190, 173, 170, 15);
intelprop.setText("(c) 2018, James Vausch");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(label);
f.add(l1);
f.add(l2);
f.add(l3);
f.add(l4);
f.add(l5);
f.add(author);
f.add(pow);
f.add(intelprop);
f.setSize(380,235);
f.setLocation(150, 150);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(handle);
b2.addActionListener(handle);
b3.addActionListener(handle);
add(f, handle);
}
class Selection implements ActionListener{
public void actionPerformed(ActionEvent e){
if ("Forward Traverse".equals(e.getSource())) {
JOptionPane.showMessageDialog(null, "Hello");
FeedOp feed = new FeedOp();
feed.display();
feed.assignDog();
feed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
if (e.getSource() == b1) {
//
}
}
}
}
这将是很大的帮助,谢谢!
答案 0 :(得分:0)
JButton b1 = new JButton("Forward Traverse");
“ b1”变量定义为局部变量,因此只能在定义该变量的方法中进行引用。
如果希望ActionListener能够引用该变量,则需要将其定义为该类的实例变量(与定义“句柄”变量的方式相同)。
也:
if ("Forward Traverse".equals(e.getSource())) {
该代码不会执行任何操作,因为getSource()方法不会返回String。阅读ActionEvent
的API。