我正在制作一个程序,它要求你的名字和年龄,根据你的答案,它会输出一个文字短语和一个合适的图像但我的问题是我无法控制我的网格布局中的组件的大小所以图片在顶部被切断,所以我只能看到一小部分
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);
}
}
}
这就是我到目前为止所做的,我正试图控制组件的高度,以为它会使该部分更大,因为宽度已经很好了。
答案 0 :(得分:1)
尝试通过getIconHeight()
和getIconWidth()
获取sizeof图像,然后通过调用public void setSize(Dimension d)
将此值设置为JLabel的大小,告诉我这是否有效。
答案 1 :(得分:1)
不要将答案放在与表单GridLayout
相同的布局中。把它放在有伸展空间的地方。
我对你的情况的建议是:
JPanel
中,GridLayout
用于LayoutManager。BorderLayout
。