【发布时间】:2021-08-02 07:52:09
【问题描述】:
我需要在另一个类中静态调用 homeIcons 方法,但我不知道如何将动作侦听器添加到静态按钮。有没有办法简单地做到这一点?我需要在 CardLayout 中使用此面板来刷新框架。按钮改变了 CardLayout 中的面板,所以我需要动作监听器来工作。
需要添加此面板才能添加到 CardLayout
public class Home extends JFrame implements ActionListener {
//fields
private static JButton sandwich;
private static JButton burger;
private static JButton pancake;
private static JButton ramen;
private static JButton beefWellington;
private static JButton help;
private static JPanel homeBody;
public static JPanel homeIcons() {
JPanel topButtons = new JPanel();
GridLayout topLayout = new GridLayout(1,2);
topButtons.setBorder(BorderFactory.createEmptyBorder(0,120,0,120));
topLayout.setVgap(5);
topLayout.setHgap(150);
topButtons.setLayout(topLayout);
topButtons.setBackground(new Color(200,200,200));
//Level 1, make a sandwich
ImageIcon sandwichImage = new ImageIcon("Resources/sandwichthumbnail.png");
sandwich = new JButton();
sandwich.setIcon(sandwichImage);
sandwich.setHorizontalAlignment(JButton.CENTER);
sandwich.setBackground(Color.WHITE);
sandwich.addActionListener(this);
this.add(sandwich);
topButtons.add(sandwich);
//Level 2, make a burger
ImageIcon burgerImage = new ImageIcon("Resources/burgerthumbnail.png");
burger = new JButton();
burger.setIcon(burgerImage);
burger.setHorizontalAlignment(JButton.CENTER);
burger.setBackground(Color.WHITE);
burger.addActionListener(this);;
this.add(burger);
topButtons.add(burger);
JPanel lowerButtons = new JPanel();
GridLayout lowerLayout = new GridLayout(1,2);
lowerButtons.setBorder(BorderFactory.createEmptyBorder(0,15,0,15));
lowerLayout.setVgap(5);
lowerLayout.setHgap(5);
lowerButtons.setLayout(lowerLayout);
lowerButtons.setBackground(new Color(200,200,200));
//Level 3, make a souffle pancake
ImageIcon pancakeImage = new ImageIcon("Resources/pancakethumbnail.png");
pancake = new JButton();
pancake.setIcon(pancakeImage);
pancake.setHorizontalAlignment(JButton.CENTER);
pancake.setBackground(Color.WHITE);
pancake.addActionListener(this);
this.add(pancake);
lowerButtons.add(pancake);
//Level 4,
ImageIcon ramenImage = new ImageIcon("Resources/ramenthumbnail.png");
ramen = new JButton();
ramen.setIcon(ramenImage);
ramen.setHorizontalAlignment(JButton.CENTER);
ramen.setBackground(Color.WHITE);
ramen.addActionListener(this);;
this.add(ramen);
lowerButtons.add(ramen);
ImageIcon wellingtonImage = new ImageIcon("Resources/wellingtonthumbnail.png");
beefWellington = new JButton();
beefWellington.setIcon(wellingtonImage);
beefWellington.setHorizontalAlignment(JButton.CENTER);
beefWellington.setBackground(Color.WHITE);
beefWellington.addActionListener(this);;
this.add(beefWellington);
lowerButtons.add(beefWellington);
homeBody.add(lowerButtons);
homeBody.add(topButtons);
return homeBody;
}
}
【问题讨论】:
-
为什么按钮需要是静态的?
-
@OneCricketeer 我将它们更改为静态以解决静态引用非静态对象的错误
-
我明白了......那么我的问题是 - 为什么你指的是这些按钮的方法是静态的?
-
@OneCricketeer 另一个类中的 jbutton 静态调用该方法。所以我把方法设为静态也符合
-
static不是你的朋友(在这种情况下),你应该努力学习在没有它的情况下生活
标签: java swing static jbutton actionlistener