1

楕円を移動するコードを作成しようとしているので、透明な 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();
        }
    });
}
}
4

1 に答える 1