簡體   English   中英

執行的操作不會從jbutton獲取信號

[英]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,我建議你不要只看它,而是研究它。


編輯:

  • 你的代碼也沒有ActionListener! 你真的應該閱讀我提供的鏈接上的教程。
  • 正如@Radiodef指出的那樣,你已經大寫了actionPerformed錯誤。 確保在所有重寫的方法之前加上@Override注釋,讓編譯器檢查你是否正確地執行了它,你的方法“簽名”是正確的。
  • 此外,正如camickr指出的那樣,x1和y1不應該是靜態的。 您應該為包含它們的類提供公共setter方法, setX1(int x1)setY1(int y1)並且需要設置這些字段的類調用這些方法。
  • 此外,在移動組件時,請務必在容納它們的容器上調用revalidate()repaint() ,以便重新定位和重新繪制它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM