[英]Why doesn't my Jpanel borderlayout work as expected?
我在JPanel,JLabel和JButton中添加了2個元素。 我希望它們彼此疊加,所以我使用BorderLayout.NORTH和SOUTH添加它們。
我遇到的問題是JLabel JButton並排坐在彼此旁邊,而不是像預期的那樣彼此疊加。 這個問題可能與我使用borderlayout將其他面板添加到框架的事實有關,如下所示。
這是一個SSCE來演示我的問題。 您會注意到,如果展開窗口,您將看到JLabel左側的JButton。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Question {
/**
* @param args
*/
public static void main(String[] args) {
gui();
}
public static void gui() {
final JFrame theFrame = new JFrame();
theFrame.setSize(550, 290);
theFrame.setLocationRelativeTo(null);
// options for the JComboBox
String[] options = { ("1"), ("2"), ("3") };
final JPanel thePanel = new JPanel();
JLabel aMessage = new JLabel(
"<html>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus<br> lacus eu ante vestibulum tincidunt. Donec venenatis rhoncus justo sit amet <br>gravida. Pellentesque habitant morbi tristique senectus et netus et malesuada<br>est ac mattis. Donec lobortis rhoncus quam. In at vulputate ipsum<br>to fix. Phasellus tempus lacus eu ante vestibulum tincidunt. Donec venenatis rhoncus<br>turpis quam sagittis arcu, non pulvinar purus leo ege.<br><br><br></html>");
aMessage.setVisible(true);
JButton theButton = new JButton();
theButton
.setText("<HTML><FONT color=\"#000099\"><U>Click here</U></FONT>"
+ " if you would like to view some file.</HTML>");
theButton.setBorderPainted(false);
theButton.setOpaque(false);
theButton.setBackground(Color.WHITE);
theButton.setVisible(true);
thePanel.add(aMessage, BorderLayout.NORTH);
thePanel.add(theButton, BorderLayout.SOUTH);
// create second panel
final JPanel secondPanel = new JPanel();
JLabel bMessage = new JLabel("Here's another Jlabel");
final JComboBox cBox = new JComboBox(options);
// would be nice to get bmessage + cBox left aligned
secondPanel.add(bMessage);
secondPanel.add(cBox);
// create third panel
final JPanel thirdPanel = new JPanel();
JLabel cMessage = new JLabel("Here's a third message");
String newString = ("Hello");
JTextField stringInput = new JTextField(newString);
stringInput.setPreferredSize(new Dimension(250, 20));
thirdPanel.add(cMessage);
thirdPanel.add(stringInput);
JButton lastButton = new JButton("A Button");
thirdPanel.add(cMessage);
thirdPanel.add(stringInput);
thirdPanel.add(lastButton);
theFrame.add(thePanel, BorderLayout.NORTH);
theFrame.add(thirdPanel, BorderLayout.SOUTH);
theFrame.add(secondPanel, BorderLayout.CENTER);
theFrame.setVisible(true);
}
}
你在哪里設置thePanel
JPanel的布局? 答:你沒有,所以它默認使用FlowLayout。 解決方案:通過setLayout(...)
將布局設置為您想要的布局
例如,
thePanel.setLayout(new BorderLayout());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.