我有一个JPanel,包含另一个JPanel,我使用SpringLayout在其上放置一个JButton。但出于某种原因,JButton并没有被绘制出来。 但是,如果我使用绝对定位而不是布局管理器,则会绘制JButton。 如果在设置SpringLayout的约束后打印出JButton的边界,我得到宽度和高度为0的位置(0,0)。 通过手动设置JButton的大小(调用setSize()),我可以以正确的大小绘制JButton,但不能在正确的位置绘制。
到目前为止,这是我的代码的精简版本:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class Panel extends JPanel {
private JPanel innerPanel;
public Panel(){
innerPanel = new InnerPanel();
this.setLayout(null);
innerPanel.setBounds(30, 30, 100, 200);
this.add(innerPanel);
this.setOpaque(false);
}
public class InnerPanel extends JPanel {
private SpringLayout layout;
private JButton someButton;
public InnerPanel() {
layout = new SpringLayout();
this.setLayout(layout);
someButton = new JButton("X");
someButton.setPreferredSize(new Dimension(45, 25));
layout.putConstraint(SpringLayout.NORTH, someButton, +5, SpringLayout.NORTH, innerPanel);
layout.putConstraint(SpringLayout.EAST, someButton, -5, SpringLayout.EAST, innerPanel);
this.add(someButton);
this.setOpaque(false);
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new Panel());
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
SpringLayout只是将一个JButton放在JPanel上可能看起来有点过于复杂,但我计划向JPanel添加更多组件,我需要SpringLayout。
我正在使用Eclipse(没有Window Builder)而且我正在运行OpenSuse,如果它有任何重要性。
答案 0 :(得分:0)
在innerPanel
的构造函数中,null
变量显然是InnerPanel
。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Panel2 extends JPanel {
private JPanel innerPanel;
public Panel2() {
super(new BorderLayout());
innerPanel = new InnerPanel();
//this.setLayout(null);
//innerPanel.setBounds(30, 30, 100, 200);
this.add(innerPanel);
this.setOpaque(false);
}
private /* TEST static */ class InnerPanel extends JPanel {
private SpringLayout layout;
private JButton someButton;
public InnerPanel() {
super();
layout = new SpringLayout();
this.setLayout(layout);
someButton = new JButton("X");
//someButton.setPreferredSize(new Dimension(45, 25));
System.out.println(innerPanel); //TEST
//layout.putConstraint(SpringLayout.NORTH, someButton, +5, SpringLayout.NORTH, innerPanel);
//layout.putConstraint(SpringLayout.EAST, someButton, -5, SpringLayout.EAST, innerPanel);
layout.putConstraint(SpringLayout.NORTH, someButton, +5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.EAST, someButton, -5, SpringLayout.EAST, this);
this.add(someButton);
this.setOpaque(false);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(new Panel2());
f.setSize(800, 600);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}