我正在尝试编写代码来移动椭圆,因此我将椭圆设置在透明的 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();
}
});
}
}