![](/img/trans.png)
[英]I can't handle a JButton click event using actionPerformed() method, don't enter in the method, why?
[英]The actionperformed don't get the signals from jbutton
我正在尝试制作一个移动椭圆的代码,所以我将椭圆设置在一个透明的JPanel(它将是红色背景上的红色JPanel)中并使用actionperformed来移动JPanel。 我将使JButton工作后,我打算添加键绑定器。 为什么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教程 (现在添加链接)中都有很好的描述,如果你认真学习Swing,我建议你不要只看它,而是研究它。
编辑:
@Override
注释,让编译器检查你是否正确地执行了它,你的方法“签名”是正确的。 setX1(int x1)
和setY1(int y1)
并且需要设置这些字段的类调用这些方法。 revalidate()
和repaint()
,以便重新定位和重新绘制它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.