[英]How can insert a JLabel at the center of another JLanel with icon
我有一個Java Swing應用程序。 我想插入一個帶有png圖像的JLabel作為背景,我想在此圖像的中心插入另一個JLabel。 所以我建立了這段代碼:
ImageIcon icon = new ImageIcon(getClass().getResource("/resources/cornometro_white.png"));
labelSfondoTimer = new JLabel(icon);
labelTempoGara = new JLabel();
labelTempoGara.text("pippo");
GridBagConstraints GBC2 = new GridBagConstraints();
Container CR2 = new Container();
GridBagLayout GBL2 = new GridBagLayout();
CR2.setComponentOrientation(ComponentOrientation.UNKNOWN);
CR2.setLayout(GBL2);
labelSfondoTimer.add(CR2);
GBC2 = new GridBagConstraints();
CR2.add(labelTempoGara);
GBC2.gridx=2;
GBC2.gridy=0;
GBC2.anchor= GridBagConstraints.CENTER;
GBL2.setConstraints(labelTempoGara,GBC2);
使用此代碼,我可以在屏幕上看到圖像,但是看不到帶有文本“ pippo”的secondo Label
我也嘗試插入此代碼:
labelSfondoTimer.setObaque(true); 但不起作用。
So, how can i fixed my error?
-因此,例如打印屏幕(基於我對問題的評論JLabel hasn't any LayoutManager in API, JLabel has method for centering, JLabel is transparent by default, GBC without any constraints centering JComponent by default
)
從SSCCE / MCVE形式的代碼中
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class JLabelInJLabel {
private JFrame frame = new JFrame();
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
private JLabel parentJLabel = new JLabel();
private JLabel childJLabel = new JLabel(infoIcon, SwingConstants.CENTER);
private JLabel imageInJLabel = new JLabel(errorIcon, SwingConstants.CENTER);
private JLabel simpleJLabel = new JLabel(warnIcon);
public JLabelInJLabel() {
parentJLabel.setLayout(new GridBagLayout());
parentJLabel.add(childJLabel);
parentJLabel.setBorder(BorderFactory.createLineBorder(java.awt.Color.RED));
imageInJLabel.setBorder(BorderFactory.createLineBorder(java.awt.Color.BLUE));
simpleJLabel.setBorder(BorderFactory.createLineBorder(java.awt.Color.ORANGE));
frame.setLayout(new GridLayout(0, 1));
frame.add(parentJLabel);
frame.add(imageInJLabel);
frame.add(simpleJLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(100, 100);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new JLabelInJLabel());
}
}
我想插入一個帶有png圖像的JLabel作為背景,我想在此圖像的中心插入另一個JLabel
您可以在同一標簽上包含文本和圖標:
JLabel label1 = new JLabel( new ImageIcon(...) );
label1.setText( "Centered Text" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
文本將在圖像上方居中。
您還可以查看以下發布信息: JButton settext特定位置 ,其中包含其他方法,這些方法可為文本位置提供更大的靈活性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.