我有一个JPanel,其中包含另一个JPanel,我将使用SpringLayout在其上放置一个JButton。但出于某种原因,JButton没有被绘制出来。但是,如果我使用绝对定位而不是布局管理器,JButton就会被绘制出来。如果在设置JButton约束后打印出SpringLayout的边界,则得到宽度和高度为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 (没有窗口生成器),如果这很重要的话,我正在运行OpenSuse。
发布于 2015-03-10 09:22:13
innerPanel变量显然是InnerPanel构造函数中的null。
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);
}
}https://stackoverflow.com/questions/28947517
复制相似问题