-1

好的,所以我正在尝试定位我的 JButton,但如果我将“this.setLayout”设置为 null,我的按钮不会显示,但如果我放置一个布局,按钮就会出现。我真的想定位我的按钮而不是使用布局..我尝试过使用容器,面板(见下文),只是经常..没有任何效果:l

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BingoHelper extends JFrame implements WindowListener, ActionListener{
    JTextField text = new JTextField(20);
    JPanel pnlButton = new JPanel();
    private JButton b; {
            b = new JButton("Click to enter name");
            }

    public void actionPerformed (ActionEvent e) {
        String fn = JOptionPane.showInputDialog("Username:");
        String sn = JOptionPane.showInputDialog("Password:");
        JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE);
        text.setText(fn + " " + sn);
        b.setVisible(false);
        text.setVisible(true);
    } 

    public BingoHelper(){
        super("BINGO");
        this.setLayout(new GridBagLayout());
        add(text);
        text.setVisible(false);
        this.add(pnlButton);
        pnlButton.add(b);
        pnlButton.setVisible(true);
        pnlButton.setLocation(800,800);
        b.setVisible(true);
        b.setPreferredSize(new Dimension(150,40));
        b.addActionListener(this);
    }

    public void windowClosing(WindowEvent e) {
        dispose();
        System.exit(0);

    }
    public void windowOpened(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
}
4

2 回答 2

0

当您使用 Null Layout时,您必须使用按钮位置和按钮大小的button.setBounds(x, y, width, height);方法定位 JButton 。现在让我们查看您的代码:(x, y)(width, height)

        add(text);
        text.setVisible(false);
        //this.add(pnlButton);
        pnlButton.setLayout(null); // setting the null layout to the button panel
        pnlButton.add(b);      
        //pnlButton.setVisible(true); // why do you need it ? it is already true
        //pnlButton.setLocation(800,800);  // weired location, remove it 
        //b.setVisible(true);    // why do you need it? it is already true
        //b.setPreferredSize(new Dimension(150,40));
         b.setBounds(20, 20, 100, 30); // putting setBounds here
        b.addActionListener(this);

         setContentPane(pnlButton);   //set the pnlButton as content pan

    }
于 2013-10-09T18:05:36.977 回答
0

您正在使用 GrigBagLayout,您应该使用 GridBagConstraints 来添加和定位组件的位置。

有关 Grigbaglayout 的更多信息,请参阅链接:https ://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

于 2015-08-28T08:52:38.770 回答