我正在尝试制作一个移动椭圆的代码,所以我将椭圆设置在一个透明的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();
}
});
}
}
答案 0 :(得分:3)
任何地方都无法拨打addActionListener(...)
。没有按钮可以工作,除非你第一次与听众“勾结”,这是你作为编码员的责任。
解决方案:在JButton上调用addActionListener(...)
并传入适当的侦听器。这一点在JButton tutorial(链接现已添加)中有详细描述,如果您认真学习Swing,我建议您不仅要看它,还要研究它。
编辑:
@Override
注释,让编译器检查您是否正确执行,方法“签名”是正确的。setX1(int x1)
和setY1(int y1)
提供类,并且需要设置这些字段的类调用这些方法。revalidate()
和repaint()
,以便重新定位和重新绘制它们。