Reputation: 351
I was making a program where it asks for your name and age and depending on your answer it would output a text phrase and an appropriate image but my problem is I cannot control the size of the components in my Grid layout so the picture is chopped off right at the top so I can only see a small portion
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);
}
}
}
This is what I have so far, I'm trying to c to control height of the component thinking it will just make that portion bigger because the width is already fine.
Upvotes: 0
Views: 391
Reputation: 23639
Don't put your answer in the same layout as the GridLayout
for your form. Put it in a place that it has room to stretch.
My suggestion for your situation would be:
JPanel
with a GridLayout
for the LayoutManager.BorderLayout
.Upvotes: 1
Reputation: 2531
Try to get sizeof image by getIconHeight()
and getIconWidth()
then set size of JLabel with this values by calling public void setSize(Dimension d)
, tell me if that worked.
Upvotes: 1