所以我将此代码添加到JFrame中,其中包含其他布局管理器和组件。
private JPanel testing123() {
JPanel j = new JPanel(new FlowLayout());
jbtOk = new JButton("OK");
jbtOk.setMnemonic('K');
jbtExit = new JButton("Exit");
jbtExit.setMnemonic('x');
add(jbtOk);
add(jbtExit);
j.add(jbtOk);
j.add(jbtExit);
return j;
}
没有这个代码,JFrame看起来很好,但是当我添加它时,它会在这两个按钮下添加大量的空白空间。为什么会这样?
这复制了它:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class Test extends JFrame implements ActionListener, KeyListener {
JButton jbtOk, jbtExit;
JPanel p = new JPanel(new GridLayout(0,1));
JPanel gui = new JPanel(new BorderLayout(2,2));
public Test() {
super("t");
//setSize(300,300);
setVisible(true);
JPanel test = test();
JPanel testing = testing();
JPanel testing123 = testing123();
p.add(test);
p.add(testing);
p.add(testing123);
this.getContentPane().add(p);
pack();
}
private JPanel test() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel labelFields = new JPanel(new BorderLayout(2,2));
labelFields.setBorder(new TitledBorder("m"));
p.add(gui);
p.add(labelFields);
JPanel labels = new JPanel(new GridLayout(0,1,1,1));
labels.setBorder(new TitledBorder("a"));
JPanel fields = new JPanel(new GridLayout(0,1,1,1));
fields.setBorder(new TitledBorder("b"));
p.add(labels);
p.add(fields);
add(fields);
add(p);
return gui;
}
private JPanel testing() {
JPanel guiCenter = new JPanel(new FlowLayout(FlowLayout.CENTER));
guiCenter.setBorder(new TitledBorder("n"));
guiCenter.add(new JScrollPane(new JTextArea(5,30)));
gui.add(guiCenter, BorderLayout.CENTER);
return guiCenter;
}
private JPanel testing123() {
JPanel j = new JPanel(new FlowLayout());
jbtOk = new JButton("OK");
jbtOk.setMnemonic('K');
jbtExit = new JButton("Exit");
jbtExit.setMnemonic('x');
//add(jbtOk);
//add(jbtExit);
j.add(jbtOk);
j.add(jbtExit);
return j;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
“我想摆脱OK和Exit按钮下的额外空间。”
问题是您使用GridLayout
会使所有JPanel
大小相同。您应该做的是将前四个JPanel
包裹在GridLayout
中,然后保留BorderLayout
的默认JFrame
,将JPanel
添加到{{1} } BorderLayout.CENTER
并将JFrame
按钮添加到JPanel
。这应该可以解决问题
BorderLayout.PAGE_END
完整运行代码
public Test() {
super("t");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel test = test();
JPanel testing = testing();
JPanel testing123 = testing123();
p.add(test);
p.add(testing);
add(p, BorderLayout.CENTER); <---
add(testing123, BorderLayout.PAGE_END); <---
pack();
setVisible(true);
}