在Java中将动态按钮添加到jpanel [英] Add dynamic buttons to jpanel in Java

查看:434
本文介绍了在Java中将动态按钮添加到jpanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java编写一个程序,该程序将使一个按钮出现在JPanel中,单击该按钮的位置和时间.为此,我使用以下代码运行方法:

I'm trying to do a program in Java that will make a button appears in a JPanel where and when it's clicked. To do that, I have the method run, with the following code:

 public void run(){
    panel.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e){
            JButton button = new JButton();
            button.setVisible(true);
            button.setAlignmentX(e.getXOnScreen());
            button.setAlignmentY(e.getYOnScreen());
            panel.add(button);
            panel.revalidate();
            panel.repaint();
        }
    });
}

问题是,不要紧记我单击的位置,按钮永远不会出现.

The problem is, nevermind where I click, the buttons never appears.

推荐答案

单击面板时,此代码应使按钮出现.它不会使它出现在光标上,但是应该很容易添加.每次您单击面板时,它也会创建一个新按钮.如果只希望一个按钮,只需将这一行JButton button = new JButton();移动到mousePressed事件之外

This code should make a button appear when the panel is clicked. It will not make it appear at the cursor but that should be easy to add. It will also make a new button every time you click the panel. If you only want one button simply move this line JButton button = new JButton();, outside of the mousePressed event

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    JPanel panel = new JPanel();
    panel.setSize(500, 500);
    frame.add(panel);
    frame.show();
    run(panel);
}

 public static void run(JPanel panel){
        panel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e){
                JButton button = new JButton();
                button.setVisible(true);                 
                panel.add(button);
                panel.revalidate();
            }
       });
}

这篇关于在Java中将动态按钮添加到jpanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆