[英]Java Swing, having a JComponent and a JPanel
I'm trying to add a JComponent to a JPanel and then display it in a window. 我正在尝试将JComponent添加到JPanel,然后在窗口中显示它。 I'm pretty sure I've got it right, but only the button in the panel shows ups. 我敢肯定我做对了,但是只有面板上的按钮才会显示出来。
//Component class
JFrame window=new JFrame("This is a window");
RcComponent component=new RcComponent();
JButton button= new Button("This is a button");
JPanel panel=new JPanel();
panel.add(component);
panel.add(button);
window.add(panel);
window.setVisible(true);
Only the button shows up in the created window. 在创建的窗口中仅显示按钮。 I'm not quite sure what I'm doing wrong. 我不太确定自己在做什么错。
By default a JPanel uses a FlowLayout and a FlowLayout respects the preferred size of all components added to it. 默认情况下,JPanel使用FlowLayout,并且FlowLayout遵守添加到其中的所有组件的首选大小。
If RcComponent is a custom component then you need to override the getPreferredSize()
method to return the Dimension of the component. 如果RcComponent是自定义组件,则需要重写getPreferredSize()
方法以返回组件的Dimension。
@Override
public Dimension getPreferredSize()
{
return new Dimension(...);
}
If you don't override this method, then the preferred size is 0, so there is nothing to display: 如果不重写此方法,则首选大小为0,因此无任何显示:
I believe you have missed the layout manager. 我相信您已经错过了布局经理。
https://www.google.com/#q=java%20layout https://www.google.com/#q=java%20layout
public static void main(String[] args) {
JFrame window=new JFrame("This is a window");
JButton button= new JButton("This is a button");
JLabel lbl= new JLabel("This is a label");
JPanel panel=new JPanel();
panel.setLayout(new GridLayout());
panel.add(button);
panel.add(lbl);
window.add(panel);
window.setSize(new Dimension(200, 200));
window.setLocationRelativeTo(null);
window.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
window.setVisible(true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.