package Input;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class ProgramEditor2 {
JFrame frame;
JPanel contactListPanel;
ArrayList<JButton> program;
public ProgramEditor2() {
initialize();
}
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LineEditor.main((JButton) arg0.getSource(),program,contactListPanel);
}
};
public void initialize() {
frame = new JFrame();
frame.setSize(471, 298);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
frame.getContentPane().setLayout(new BorderLayout());
program = new ArrayList<JButton>();
// Set layout for contactListPane
contactListPanel = new JPanel();
contactListPanel.setLayout(new GridLayout(15, 1)); // 15 rows, 1 column
contactListPanel.setMinimumSize(new Dimension(471, 298));
contactListPanel.setPreferredSize(new Dimension(471, 298));
contactListPanel.setMaximumSize(new Dimension(471, 298));
for (int i = 0; i < 1; i++) {
JButton button = new JButton();
button.addActionListener(al);
contactListPanel.add(button);
}
JScrollPane scrollPane = new JScrollPane(contactListPanel);
scrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main(String[] args) {
new ProgramEditor2();
}
}
我正在尝试在滚动面板上方添加一个JLabel,并在它下面添加两个JButton。我相信问题是我在第57行将框架布局设置为BorderLayout。我怎样才能解决这个问题?< / p>
答案 0 :(得分:3)
首先仔细查看How to Use BorderLayout
我正在尝试在滚动面板上方添加一个JLabel
frame.add(new JLabel("Hello"), BorderLayout.NORTH);
和它下面的两个JButtons
使用&#34;复合布局&#34;通过使用具有不同布局管理器的不同容器来满足内部组件的要求,然后将此容器添加到父容器,例如
JButton btn1 = ...;
JButton btn2 = ...;
JPanel buttons = new JPanel();
buttons.add(btn1);
buttons.add(btn2);
frame.add(buttons, BorderLayout.SOUTH);
frame.setSize(471, 298);
而不是JFrame#pack
,但我只会在您建立基本用户界面之后执行此操作。frame.getContentPane().setLayout(null);
有点无意义frame.setVisible(true);
应在最终建立UI后调用,否则可能不会显示某些组件etMinimumSize
,setPreferredSize
,setMaximumSize
,如果您不小心,它们会对布局产生负面影响。有关更多讨论,请参阅Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?。如果您想更改JScrollPane
的工作方式,请改用Scrollable
界面