我试图将JPanel中的一个部分包含在整个水平范围内的JTextPane中;但你可以看到它只是一个小裂缝。
为什么GridBagConstraints.HORIZONTALL填不起作用?
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class TestJPanel extends JFrame{
JTextPane crtAnswer;
public static void main(String[] args){
new TestJPanel();
}
TestJPanel(){
//setup
JPanel p = new JPanel();
p.setLayout( new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setLocation(200, 50);
setPreferredSize(new Dimension(600, 674)); //width by height. (was 474,674) .. then (was 574,674)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
crtAnswer = new JTextPane(){
public boolean isEditable(){ //don't let user edit label
return false;
};
};
crtAnswer.setAlignmentX(CENTER_ALIGNMENT);
crtAnswer.setText("");
crtAnswer.setFont(new Font("Arial", Font.BOLD, 22));
//center text
StyledDocument doc = crtAnswer.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
//constraints: crt answer
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0,0, 5, 0);
p.add(crtAnswer, c);
add(p);
setVisible(true);
}
}
答案 0 :(得分:1)
您尚未将p的布局设置为GridBagLayout
。所以当然它不会起作用