java 向 JDialog 添加按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5837067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:02:31  来源:igfitidea点击:

Adding buttons to a JDialog?

javaswingjbuttonjdialog

提问by Stan

I'm trying to make a JButton on a JDialog, but, the button will cover the entire JDialog, any help on this? This is what it looks like:

我正在尝试在 JDialog 上创建一个 JButton,但是,该按钮将覆盖整个 JDialog,对此有什么帮助吗?这是它的样子:

enter image description here

在此处输入图片说明

This is how I create the JDialog and the JButton:

这就是我创建 JDialog 和 JButton 的方式:

class MenuStoreHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = (int) dim.getWidth();
        int screenHeight = (int) dim.getHeight();

        JDialog g = new JDialog();
        g.setTitle("The Store");
        g.setSize(200, 200);
        g.setLocation(screenWidth / 2 - 150, screenHeight / 2 - 150);

        JButton b = new JButton("Buy");
        b.addActionListener( new StoreItem1Handler() );
        b.setVisible(true);
        g.add(b);

        g.setVisible(true);
    }
}

I'm just going to post my full MrStan.class, here it is:

我只是要发布我完整的 MrStan.class,这里是:

package Progress;

public class MrStan extends JPanel{

    private Timer timer = new Timer();
    public static int points;
    static File h = new File("text.txt");
    public ImageIcon bg = new ImageIcon("D:/MrStan/bg.png");
    static JMenuBar menubar;
    Formatter x;
    JMenu menu;
    JMenuItem menuitem;

    double version = 0.3;

    class todoTask extends TimerTask{
        public void run(){ 
            points += 1;
            repaint();
        }
    }

    public int getPoints(){
        return points;
    }

    public void setPoints( int points ){
        this.points = points;
    }

    public MrStan(){
        setIgnoreRepaint(true);

        menubar = new JMenuBar();
        menu = new JMenu("Menu");
        menu.setMnemonic(KeyEvent.VK_F);
        menu.getAccessibleContext().setAccessibleDescription("Menu");
        menubar.add(menu);

        menuitem = new JMenuItem("Store (S)", new ImageIcon("coins.png"));
        menuitem.setMnemonic(KeyEvent.VK_S);
        menuitem.addActionListener( new MenuStoreHandler() );
        menu.add(menuitem);

        menuitem = new JMenuItem("Reset Points (R)", new ImageIcon("delete.png"));
        menuitem.setMnemonic(KeyEvent.VK_R);
        menuitem.addActionListener( new MenuResetPointHandler() );
        menu.add(menuitem);

        // add a separator
        menu.addSeparator();

        menuitem = new JMenuItem("Exit (E)", new ImageIcon("cross.png"));
        menuitem.setMnemonic(KeyEvent.VK_E);
        menuitem.addActionListener( new MenuExitHandler() );
        menu.add(menuitem);

        timer.schedule(new todoTask(), 0, 2000);

    }

    class MenuStoreHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){

            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            int screenWidth = (int) dim.getWidth();
            int screenHeight = (int) dim.getHeight();

            JDialog g = new JDialog();
            g.setTitle("The Store");
            g.setSize(200, 200);
            g.setLocation(screenWidth / 2 - 150, screenHeight / 2 - 150);

            JButton b = new JButton("Buy");
            b.addActionListener( new StoreItem1Handler() );
            b.setVisible(true);
            g.add(b);

            g.setVisible(true);
        }
    }

    class StoreItem1Handler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.out.println("Store-Button 1 pressed.");
        }
    }

    class MenuExitHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.exit(1);
        }
    }

    class MenuResetPointHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            points = 0;
            repaint();
            JOptionPane.showMessageDialog(null, "Points have been reset.");
        }
    }

    public void paint(Graphics g){
        g.setColor(Color.WHITE);
        bg.paintIcon(this,g,0,0);
        g.setColor(Color.BLACK);
        g.drawString("Points: " + points, 75, 95);
        g.drawString("Version: " + version, 2, 10);
    }

    public static void main(String[] args){

        final MrStanCreateFile g = new MrStanCreateFile();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
            public void run(){
                if(h.exists()){
                    g.openFile();
                    g.addRecords();
                    g.closeFile();
                }else{
                    System.out.println(h.getName() + "does not exist, not saving.");
                }
            }
        }, "Shutdown-thread"));

        readIt();

        //Create new JFrame
        JFrame frame = new JFrame();
        frame.setTitle("MrStan");
        frame.setSize(200, 200);
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setJMenuBar(menubar);

        //Set location of JFrame
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = (int) dim.getWidth();
        int screenHeight = (int) dim.getHeight();
        frame.setLocation(screenWidth / 2 - 200, screenHeight / 2 - 200);

        //Set ContentPane to JPanel
        MrStan panel = new MrStan();
        frame.setContentPane(panel);

        //Make the user not be able to resize
        frame.setResizable(false);

        //Make the JFrame visible
        frame.setVisible(true);
    }

    public static void readIt(){
        MrStanReadFile r = new MrStanReadFile();
        r.openFile();
        r.readFile();
        r.closeFile();
    }

}

Why is this covering my ENTIRE JDialog? I'm using the basic Layout Manager, it should just be fine.

为什么这覆盖了我的整个 JDialog?我正在使用基本的布局管理器,应该没问题。

回答by Bala R

Seems to work fine for me. Did you do call setLayout(null) for the dialog?

对我来说似乎工作正常。您是否为对话框调用了 setLayout(null) ?

This is what I tried

这是我试过的

JDialog dialog = new JDialog();
dialog.setSize(300, 200);
dialog.setLayout(null);



JButton button = new JButton("Testbutton!");
button.setVisible(true);
button.setBounds(10,10,40,40);
dialog.add(button);

//Make dialog visible
dialog.setVisible(true);

And usually it's not a good practice to not use a layout manager. Things can get complicated very quickly. Layout Managers help a lot.

通常不使用布局管理器不是一个好习惯。事情会很快变得复杂。布局管理器有很大帮助。

回答by Anthony Accioly

Try adding the button to the contentPane first and setting the bounds later.

尝试先将按钮添加到 contentPane,然后再设置边界。

Container pane = dialog.getContentPane();
pane.setLayout(null);
JButton button = new JButton("Testbutton!");
pane.add(button);
button.setBounds(10,10,40,40);

回答by camickr

The real problem for you code is that you add the components to the dialog AFTER you set the dialog visible. The second setVisible() does nothing because its already visible.

您代码的真正问题是在将对话框设置为可见后将组件添加到对话框中。第二个 setVisible() 什么都不做,因为它已经可见。

That is why you should be learning from the examples in the Swing tutorial. The examples show you the proper way to create a simple GUI.

这就是为什么您应该从 Swing 教程中的示例中学习的原因。这些示例向您展示了创建简单 GUI 的正确方法。