0

我正在制作一个程序,它会询问您的姓名和年龄,根据您的回答,它会输出一个文本短语和一个适当的图像,但我的问题是我无法控制网格布局中组件的大小,所以图片被切掉了就在顶部,所以我只能看到一小部分

public class eb extends JFrame {

    private JLabel lblQuestion;
    private JLabel lblName;
    private JLabel lblAge;
    private JLabel lblAnswer;
    private JTextField txtName;
    private JTextField txtAge;
    private JButton btnEligible;
    private ImageIcon image1 = new ImageIcon("H:\\NetBeansProjects\\Skill Set 15\\Egilible.jpg");
    private JLabel ImageEligible = new JLabel(image1);
    private ImageIcon image2 = new ImageIcon("H:\\NetBeansProjects\\Skill Set 15\\Unegilible.jpg");
    private JLabel ImageUnegibile = new JLabel(image2);

    public eb() {
        setLayout(new GridLayout(7, 1)); 
        lblQuestion = new JLabel("Are you eligible to vote?");
        add(lblQuestion);
        lblName = new JLabel("Enter your Name");
        add(lblName);
        txtName = new JTextField(15);
        add(txtName);
        lblAge = new JLabel("Enter your Age");
        lblAge.setLocation(lblName.getX(), lblName.getY());
        add(lblAge);
        txtAge = new JTextField(15);
        add(txtAge);
        btnEligible = new JButton("Am I Eligible?");
        add(btnEligible);
        lblAnswer = new JLabel("Answer");
        add(lblAnswer);
        Eligible eligible = new Eligible();
        btnEligible.addActionListener(eligible);
    }

    public class Eligible implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            int nAge = Integer.parseInt(txtAge.getText());
            String sName = txtName.getText();
            GridBagConstraints c = new GridBagConstraints();
            if (nAge > 18) {
                lblAnswer.setText("Step right up " + sName + ", and vote. ");
                c.fill = GridBagConstraints.VERTICAL;
                c.gridheight = 10;
                JPanel p1 = new JPanel();
                p1.add(ImageEligible, c);
                add(p1, c);
            } else {
                lblAnswer.setText("Maybe next time, " + sName);
                JPanel p2 = new JPanel();
                p2.add(ImageUnegibile, c);
                add(p2);
            }
        }
    }

这就是我到目前为止所拥有的,我正在尝试使用 c 来控制组件的高度,认为它只会使该部分变大,因为宽度已经很好了。

4

2 回答 2

1

尝试通过调用获取 sizeof 图像getIconHeight()getIconWidth()然后使用此值设置 JLabel 的大小public void setSize(Dimension d),告诉我这是否有效。

于 2013-11-12T14:21:53.940 回答
1

不要将答案放在与GridLayout表单相同的布局中。把它放在有伸展空间的地方。

我对您的情况的建议是:

  • 将您的标签和文本字段的形式放在JPanelLayoutManagerGridLayout中。
  • 将框架的 contentPane 设置为使用BorderLayout.
  • 将表单添加到 contentPane 的“PAGE_START”。
  • 将答案添加到 contentPane 的“中心”。
于 2013-11-12T14:27:48.237 回答