我正在尝试编写代码来移动椭圆形,因此我将椭圆形设置在透明 JPanel 内(它将成为红色背景上的红色 JPanel)并使用 actionperformed 移动 JPanel。在使 JButton 工作之后,我打算添加键绑定(bind)器。为什么 actionperformed 方法不从 JBUtton 获取信号?
public class PanelExample_Extended{
public static final int OVAL_WIDTH = 20, OVAL_HEIGHT = 20;
public static int x1 = 50, y1 = 100;
JButton upButton;
JPanel transparentPanel;
public class MyGraphics extends JComponent {
private static final long serialVersionUID = 7526472295622776147L;
MyGraphics() {
setPreferredSize(new Dimension(20,20));
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.blue);
g.fillOval(0, 0, OVAL_WIDTH, OVAL_HEIGHT);
}
}
public JPanel createContentPane (){
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
transparentPanel = new JPanel(new BorderLayout());
transparentPanel.setBackground(Color.red);
transparentPanel.setLocation(x1, y1);
transparentPanel.setSize(20,20);
MyGraphics tr = new MyGraphics();
tr.setLocation(0, 0);
transparentPanel.add(tr);
totalGUI.add(transparentPanel);
upButton = new JButton("up");
upButton.setLocation(0,50);
upButton.setSize(50,50);
totalGUI.add(upButton);
totalGUI.setOpaque(true);
return totalGUI;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] ??? [=]");
PanelExample_Extended demo = new PanelExample_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(290, 100);
frame.setVisible(true);
}
public void ActionPerformed(ActionEvent h){
if( h.getSource() == upButton) {
y1 = y1 - 10;
transparentPanel.setLocation(x1, y1);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
最佳答案
没有任何地方调用 addActionListener(...)
。除非您首先将其与监听器“连接起来”,否则任何按钮都无法使用,这是您作为编码人员的责任。
解决方案:在 JButton 上调用 addActionListener(...)
并传入适当的监听器。 JButton tutorial 中对此进行了详细描述(现在添加了链接),如果您认真学习 Swing,我建议您不仅要看它,还要研究它。
编辑:
- 而且你的代码也没有 ActionListener!您真的应该阅读我提供的链接中的教程。
- 正如@Radiodef 指出的那样,您错误地将 actionPerformed 大写了。请务必在所有重写的方法之前加上
@Override
注释,让编译器检查您是否正确执行操作,以及您的方法“签名”是否正确。 - 另外,正如 camickr 指出的那样,x1 和 y1 不应该是静态的。您应该为拥有它们的类提供公共(public)设置方法
setX1(int x1)
和setY1(int y1)
并让需要设置这些字段的类调用这些方法。 - 此外,在移动组件时,请务必在容纳它们的容器上调用
revalidate()
和repaint()
,以便重新定位和重绘它们。<
关于java - 执行的 Action 没有从 jbutton 获得信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19611689/