JButton定位

时间:2013-10-09 17:54:10

标签: java swing layout jpanel jbutton

好的,所以我正在尝试定位我的JButton但是如果我将“this.setLayout”设置为null我的按钮没有显示但是如果我放置了一个Layout按钮出现。我真的想要定位我的按钮而不是使用布局.. 我已经尝试过使用一个容器,一个面板(如下所示),只是定期......没有用: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) {}
}

2 个答案:

答案 0 :(得分:0)

当你using 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

    }

答案 1 :(得分:0)

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

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