我正在制作一个程序,它会询问您的姓名和年龄,根据您的回答,它会输出一个文本短语和一个适当的图像,但我的问题是我无法控制网格布局中组件的大小,所以图片被切掉了就在顶部,所以我只能看到一小部分
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 来控制组件的高度,认为它只会使该部分变大,因为宽度已经很好了。