我正在创建一个 Java 应用程序,并希望在应用程序底部有一个栏,我在其中显示一个文本栏和一个状态(进度)栏。
只有我似乎无法在 NetBeans 中找到控件,我也不知道要手动创建的代码。
创建一个带有 BorderLayout 的 JFrame 或 JPanel,给它一个类似BevelBorder或线条边框的东西,这样它就与其余的内容分开,然后在 BorderLayout.SOUTH 处添加状态面板。
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setSize(200, 200);
// create the status bar panel and shove it down the bottom of the frame
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
frame.add(statusPanel, BorderLayout.SOUTH);
statusPanel.setPreferredSize(new Dimension(frame.getWidth(), 16));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
JLabel statusLabel = new JLabel("status");
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
frame.setVisible(true);
这是我机器上上述状态条码的结果:
不幸的是,Swing 没有对 StatusBars 的原生支持。你可以使用一个BorderLayout
和一个标签或任何你需要在底部显示的东西:
public class StatusBar extends JLabel {
/** Creates a new instance of StatusBar */
public StatusBar() {
super();
super.setPreferredSize(new Dimension(100, 16));
setMessage("Ready");
}
public void setMessage(String message) {
setText(" "+message);
}
}
然后在您的主面板中:
statusBar = new StatusBar();
getContentPane().add(statusBar, java.awt.BorderLayout.SOUTH);
来自:http ://www.java-tips.org/java-se-tips/javax.swing/creating-a-status-bar.html
我使用了L2FProd的 swing 库。他们提供的状态栏库非常好。
以下是您将如何使用它:
状态栏在内部将栏区域划分为区域。每个区域都可以包含一个组件(JLabel、JButton 等)。想法是用所需的区域和组件填充栏。
实例化状态栏如下....
import java.awt.Component;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import com.l2fprod.common.swing.StatusBar;
StatusBar statusBar = new StatusBar();
statusBar.setZoneBorder(BorderFactory.createLineBorder(Color.GRAY));
statusBar.setZones(
new String[] { "first_zone", "second_zone", "remaining_zones" },
new Component[] {
new JLabel("first"),
new JLabel("second"),
new JLabel("remaining")
},
new String[] {"25%", "25%", "*"}
);
现在将以上内容添加statusBar
到您拥有的主面板(BorderLayout 并将其设置为南侧)。
请参阅我正在处理的其中一个应用程序的示例屏幕截图(它有 2 个区域)。如果您遇到任何问题,请告诉我......
要获得比公认答案更现代的外观,请使用 GridBagLayout 和 JSeparator:
JPanel outerPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.weighty = 0;
JPanel menuJPanel = new JPanel();
menuJPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
outerPanel.add(menuJPanel, gbc);
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
JPanel contentJPanel = new JPanel();
contentJPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLUE));
outerPanel.add(contentJPanel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 0;
gbc.insets = new Insets(0, 0, 0, 0);
outerPanel.add(new JSeparator(JSeparator.HORIZONTAL), gbc);
outerPanel.add(new JPanel(), gbc);