3
我在Java中使用GridLayout類來佈局一些UI組件。圖片是在這裏:GridLayout Java中心對齊
我想獲得創建購物車的圖片和相關文字在面板各自的細胞對準中心。有關詳情 - 購物車圖片必須位於面板的灰色單元格的中央。並且JTextArea中的文本也必須中心對齊。你能幫忙嗎?我的代碼已附加。
import javax.swing.*;
import java.awt.*;
class ImageDemo extends JFrame
{
ImageDemo()
{
Container pane = getContentPane();
pane.setLayout(new GridLayout(2,2));
setSize(800,400);
setLayout(new GridLayout(2,2));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cartpane = new JPanel();
cartpane.setLayout(new GridLayout(1,2));
/*
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.SOUTH;
c.fill=GridBagConstraints.BOTH;
cartpane.add(imglabelcart,c);
c.gridx=1;
c.gridy=0;
c.fill=GridBagConstraints.BOTH ;
c.anchor = GridBagConstraints.WEST;
cartpane.add(cartta,c);
*/
ImageIcon iconcart = new ImageIcon("cart.jpg");
JLabel imglabelcart = new JLabel("Create Shopping Cart");
imglabelcart.setIcon(iconcart);
imglabelcart.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabelcart.setHorizontalTextPosition(SwingConstants.CENTER);
JTextArea cartta = new JTextArea();
cartta.setLineWrap(true);
cartta.append("Use the Create Shopping Cart transaction to create a
new shopping cart for your purchases.\n");
cartta.append("You can view the products available in the catalog and select
them to be part of your shopping cart.");
cartpane.add(imglabelcart);
cartpane.add(cartta);
ImageIcon iconapprove = new ImageIcon("approve.jpg");
ImageIcon iconviewpo = new ImageIcon("viewpo.jpg");
ImageIcon iconlogout = new ImageIcon("viewpo.jpg");
JLabel imglabelapprove = new JLabel("Approve Shopping Cart");
JLabel imglabelviewpo = new JLabel("View Purchase Order");
JLabel imglabellogout = new JLabel("Logout");
imglabelapprove.setIcon(iconapprove);
imglabelapprove.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabelapprove.setHorizontalTextPosition(SwingConstants.CENTER);
imglabelviewpo.setIcon(iconviewpo);
imglabelviewpo.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabelviewpo.setHorizontalTextPosition(SwingConstants.CENTER);
imglabellogout.setIcon(iconlogout);
imglabellogout.setVerticalTextPosition(SwingConstants.BOTTOM);
imglabellogout.setHorizontalTextPosition(SwingConstants.CENTER);
pane.setBackground(new Color(156,195,252));
pane.add(cartpane);
pane.add(imglabelapprove);
pane.add(imglabelviewpo);
pane.add(imglabellogout);
setVisible(true);
}
public static void main(String[] args)
{
ImageDemo demoi = new ImageDemo();
}
}
如果這不起作用,可能是什麼原因? –
@JochenReinschlüssel如果使用這種方法,它不起作用,可能是因爲您的JLabel太短,所以即使您將內容居中,它也出現在單元格的左側。增加它的長度。 – FaithReaper