关于JButton重写getX(),getY()

编程入门 行业动态 更新时间:2024-10-10 19:18:16

关于JButton<a href=https://www.elefans.com/category/jswz/34/1769232.html style=重写getX(),getY()"/>

关于JButton重写getX(),getY()

首先说结论:
1.在JPanel实例中,不设定setLayout(null)的话,JButton的setBounds方法失效.

2不要在JButton中重写getX()和getY()方法,因为虽然JButton中没有这两个方法,但是JComponent中却有,而且每次对象使用x或y变量时都会调用一次get方法.

最近在重构一个是男人就坚持30秒小游戏,原代码文件只有一个。包含各种内部类,方法调用盘根错节,注释也少,加上自己萌新,打算用来练手。。
先把每行代码加上了注释之后,再把方法和类按照调用顺序排好,查看起来算是没那么费劲了,就打算将其中的类分别进行梳理封装,一开始就遇到一个问题,解决之后发文纪录下。
上代码

public class GameMain extends JFrame{public static final int WIDTH=700;public static final int HEIGHT=WIDTH;private JPanel jPanel;private JLabel jLabel;private ArrayList<Shoot> shList = new ArrayList<Shoot>();public GameMain() {super();//窗口尺寸this.setSize(WIDTH, HEIGHT);//监听窗口方法,关闭窗口时,结束程序this.addWindowListener(new java.awt.event.WindowAdapter() {public void windowClosing(java.awt.event.WindowEvent e) {System.exit(1);}});//设置窗口标题this.setTitle("模拟撑过30秒的小DEMO复刻版");//设置窗口可见this.setVisible(true);//设置窗口的背景和this.setContentPane(getJPanel());}/*** 游戏窗口背景* @return*/private JPanel getJPanel() {jPanel = new JPanel();//布局为空,很重要!注释掉setBounds失效!jPanel.setLayout(null);//背景色jPanel.setBackground(new Color(1, 1, 1));return jPanel;}public void start() {for(int i=0;i<100;i++) {Shoot shoot = new Shoot();jPanel.add(shoot);Thread sh = new Thread(shoot);sh.start();}}public static void main(String[] args) {GameMain game = new GameMain();game.start();}
}
public class Shoot extends JButton implements Runnable{private static final int length =10;private int x = 20;private int y = 20;private int xSpeed = 5;private int ySpeed = 5;public Shoot() {//设定方块位置resultLocal();//设定方块属性setBounds(x, y, length, length);}public void run() {while(true) {try {x+=xSpeed;y+=ySpeed;setLocation(x, y);Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}}}public int getxSpeed(int x) {return x-this.x;}public int getySpeed(int y) {return y-this.y;}public int getX() {return (int)(Math.random());}public int getY() {return y;}

一开始运行之后是这样的

如果将setLayout(null)注释的话

会有按钮不按设定的size显示

十分古怪的是,不论如何设定,图标都只在最左出现并向下移动,可是控制台的中输出的x却明明一直都在变化…

后来找半天才发现getX()中的值因为强转的关系永远返回0,设定(int)(Math.random()*700)之后方块在窗口中乱闪才觉得哪里不对劲。

之后搜了下…恩是方法中的getX()方法覆盖了JComponent中的getX(),本来打算在其出界后可以调用方法直接初始化坐标,没想到却出了这么个岔子哈哈。。

Ctrl+T查看了下继承关系,上面确实有JComponent

更多推荐

关于JButton重写getX(),getY()

本文发布于:2024-02-07 13:33:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重写   JButton   getY   getX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!