3

The following program segment generates the output within the red box as shown in the figure:

st = c.con.createStatement();
rs = st.executeQuery("SELECT itemName, itemMaxQty, itemImage FROM item");

while(rs.next()){
    JPanel itemPanel = new JPanel();

    itemPanel.setLayout(new BoxLayout(itemPanel, BoxLayout.PAGE_AXIS));
    JPanel componentPanel = new JPanel();
    componentPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel itemName = new JLabel(rs.getString(1));
    ImageIcon itemImage = new ImageIcon(rs.getString(3));
    Image scaleImage = itemImage.getImage().getScaledInstance(120, 120, Image.SCALE_SMOOTH);
    JLabel imageHolder = new JLabel(new ImageIcon(scaleImage));
    JSpinner quantityField = new JSpinner();
    Dimension d = quantityField.getPreferredSize();
    d.width = 60;
    d.height = 30;
    quantityField.setPreferredSize(d);

    componentPanel.add(imageHolder);
    componentPanel.add(quantityField);
    itemPanel.add(componentPanel);
    itemPanel.add(itemName);

    add(itemPanel);
}

program output

I know that probably some parts of the code are not the best way to do it, but that is what I can do for now in line with the knowledge that I have.

I actually have two problems here.

First, I don’t understand why the itemName's value (Cupcake Stand, chafers, etc) are centred.

1. How do I make it left centred such that it is aligned with its corresponding picture on top?

Second, as you can see, there is a large space in between the componentPanel (the picture and the JSpinner) and the itemName. I think it’s because the height allotted for itemName is the same as that for the componentPanel. So

2. How do I make itemName immediately below the componentPanel?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Satellite Sage
  • 440
  • 1
  • 4
  • 13
  • My first suggestion is that you separate the SQL from the construction of the view. In other words, read from the database, build a model using plain Java objects, and build your view from the Java objects. As far as your actual questions, take a look at the GridBagLayout. This layout gives you more control over the placement of your Swing components. – Gilbert Le Blanc Feb 19 '20 at 10:09

1 Answers1

0

You can do that by changing the LayoutManager of itemPanel to BorderLayout (with that line itemPanel.setLayout(new BorderLayout());), and add the component to itemPanel in that way:

itemPanel.add(componentPanel, BorderLayout.CENTER);
itemPanel.add(itemName, BorderLayout.SOUTH);
Programmer
  • 803
  • 1
  • 6
  • 13