因此,我正在编写一个程序,希望在该程序中有一个单独的JFrame,其中包含一个单独颜色的JPanel标题,并在其正下方有一个独立JPanel中的按钮网格。到目前为止,我的程序运行得很好,只是标题String没有显示在NORTH面板中。相反,我得到了一个盒子,里面有设定的背景颜色,中间有一个灰色的小盒子。我想知道我是否没有正确设置面板的大小?
我听说这可以使用JLabel完成,但当我尝试这样做时,它不会显示我设置的背景色。
因此,有人能告诉我如何使用JPanel(最好是因为我想知道它是如何工作的以及我缺少什么)或JLabel实现以下目标吗:用String填充标题中间的灰色小框。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example {
public static void main(String[] args) {
// Initialize a panel for the header, and mainGrid which will contain buttons
JPanel panel = new JPanel();
JPanel header = new JPanel();
JPanel mainGrid = new JPanel();
// Initialize the header
DisplayPanel message = new DisplayPanel();
header.setBackground(Color.ORANGE);
header.add(message);
// Initialize the mainGrid panel
mainGrid.setLayout(new GridLayout(2,2,2,2));
mainGrid.add(new JButton("1"));
mainGrid.add(new JButton("2"));
mainGrid.add(new JButton("3"));
mainGrid.add(new JButton("4"));
// Add the two subpanels to the main panel
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH); // The issue is this panel isn't displaying the String created in DisplayPanel
panel.add(mainGrid, BorderLayout.CENTER);
// Add main panel to JFrame
JFrame display = new JFrame("Test");
display.setContentPane(panel);
display.setSize(200,100);
display.setLocation(500,200);
display.setVisible(true);
display.setResizable(false);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class DisplayPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("header" , 20, 20); // The string I want to be displayed
}
}
}
我非常感谢任何人的帮助或意见,因为我学习Java才几个月,这是我的第一篇帖子。提前谢谢。
此外,如果您有任何关于写作的一般提示,我们将不胜感激。
我想知道您的问题是否是将消息JPanel嵌套在标头JPanel中,而容器标头JPanell使用JPanel默认的FlowLayout。因此,它所包含的组件不会自行扩展,并且会保持非常小。
- 考虑给标题JPanel一个BorderLayout,以便消息在其中展开,或者
- 使用JLabel来显示文本,而不是JPanel的paintComponent方法。JLabel的大小应该足够大,可以显示其文本。如果您这样做并希望它显示背景色,那么您所要做的就是在JLabel上调用
setOpaque(true)
,然后就完成了设置
实际上,如果嵌套JLabel,那么就没有必要使其不透明。只需这样做:
JPanel header = new JPanel();
JPanel mainGrid = new JPanel();
JLabel message = new JLabel("Header", SwingConstants.CENTER);
header.setBackground(Color.ORANGE);
header.setLayout(new BorderLayout());
header.add(message);
我强烈建议使用GUI构建器WYSIWYG IDE,如NetBeans,在那里你可以轻松地将组件拖放到需要的位置。如果你正在做任何复杂的GUI布局,试图编写和维护代码可能是疯狂的(在我看来,这是荒谬的)。
您尝试实现的布局在NetBeans中是微不足道的。