【发布时间】:2013-10-26 20:42:14
【问题描述】:
我正在尝试编写代码来移动椭圆,因此我将椭圆设置在透明的 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();
}
});
}
}
【问题讨论】:
-
你能精简你的代码,让它只包含一个
JButton实现吗? -
这段代码是从一个更大的代码中精简出来的,我试图让它只包含与问题相关的最少组件......
-
但我明白你的意思。我会编辑它。
-
@עמוסרום,你甚至花时间阅读 cmets 吗?在你上次发帖时 (stackoverflow.com/q/19575849/131872) 我说过你不应该使用静态变量。为什么不听建议就发问题???我们为您提供避免当前和未来问题的建议。
-
@camickr:啊,x1 和 y1,我现在看到了。是的,它们不应该是静态的。
标签: java swing jpanel action jbutton