我有使用BorderLayout的JFrame的Java Swing应用程序,里面是使用CardLayout的JPanel。我正在显示3张不同的牌。 如果我手动设置JFrame的大小,那么内容将显示为我想要的内容。带图像的标签位于东南角。
以下是我将其设置为全屏的代码:
Frame[] frames = Frame.getFrames();
JFrame frame = (JFrame) frames[0];
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
//frame.getContentPane().setPreferredSize( Toolkit.getDefaultToolkit().getScreenSize());
frame.setUndecorated(true);
//frame.setSize(600,500);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
使用Netbeans GUI构建器构建卡片,并且布局设置为“Free Design”。
应用程序将全屏显示,我希望该图像的标签是SE角,就像调整大小的窗口一样(图像示例1)。我需要为此更改布局还是其他内容?
答案 0 :(得分:2)
请注意,这些UI在整个UI周围都有一个小边框。要删除它,请注释掉该行:
ui.setBorder(new EmptyBorder(4,4,4,4));
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ImageInSouthEast {
private JComponent ui = null;
ImageInSouthEast() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(4,4,4,4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 2;
gbc.weighty = .5;
gbc.weightx = .5;
gbc.gridx = 0;
gbc.gridy = 0;
// first add the labels
for (int ii=1; ii<5; ii++) {
gbc.gridy = ii;
if (ii==4) {
gbc.gridwidth = 1;
}
JLabel l = new JLabel("Label " + ii);
l.setFont(l.getFont().deriveFont(50f));
ui.add(l, gbc);
}
// now for the image!
BufferedImage bi = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB);
JLabel l = new JLabel(new ImageIcon(bi));
gbc.anchor = GridBagConstraints.LAST_LINE_END;
gbc.gridx = 2;
gbc.weighty = 0;
ui.add(l, gbc);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ImageInSouthEast o = new ImageInSouthEast();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
答案 1 :(得分:0)
如果您只是想删除文字之间的差距,那么您可以使用 BoxLayout
。
通过执行以下操作设置布局:
Container pane = frame.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.add(Box.createHorizontalGlue());
添加元素
public void add(Component comp, int gap){
//comp is the component that will be added
//gap is the extra space after the last component and this
pane.remove(pane.getComponents().length - 1);
pane.add(Box.createVerticalStrut(gap));
pane.add(comp);
//Obviously pane or frame need to be visible to use this method
}
通过执行以下操作添加文字:
add(new JLabel(text), 5);
通过执行以下操作添加图像:
JPanel panel = new JPanel();
panel.add(image, BorderLayout.EAST);
panel.setOpaque(false);
add(Box.createHorizontalGlue(),0);
add(panel,0);