[英]Java JList GUI formatting
我在為正在開發的程序格式化GUI時遇到麻煩。 我需要在上面有一個JList的四個按鈕。 我的JList一直顯示在我所有按鈕的旁邊,而不是它們的上方。 有人能指出我正確的方向來解決我的問題嗎?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test extends JPanel {
private static final long serialVersionUID = 1L;
private JList jlist;
public static void main(String[] args) {
JFrame boxOptions = new JFrame("Calculator");
boxOptions.setSize(0,0);
boxOptions.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boxOptions.setResizable(false);
boxOptions.setLayout(new BorderLayout());
boxOptions.add(new Test(), BorderLayout.CENTER);
boxOptions.pack();
boxOptions.setLocationRelativeTo(null);
boxOptions.setVisible(true);
}
public Test(){
setLayout(new GridLayout(1, 4, 5, 5));
add(new JButton("add"));
add(new JButton("Check In"));
add(new JButton("Check Out"));
add(new JButton("Delete"));
String[] Titles = {"one", "two", "three"};
jlist = new JList(Titles);
jlist.setVisibleRowCount(3);
add(new JScrollPane(jlist), BorderLayout.NORTH);
}
}
您正在將Test JPanel類的布局設置為GridLayout,然后嘗試使用BorderLayout.NORTH說明符向其添加組件-該說明符不適用,因為該說明符僅適用於BorderLayout,對於使用GridLayout沒有意義測試JPanel。
解決方案:嵌套JPanels。 讓外部JPanel使用BorderLayout,並使用BorderLayout.NORTH說明符將列表的JScrollPane添加到該外部JPanel,然后創建一個使用GridLayout的內部JPanel,該JPanel保存您的JButton,並將其添加到BorderLayout中的主要外部JPanel中。中心位置。
不過,最重要的是:閱讀Swing教程,您可以在這里找到它們,特別是有關使用布局管理器的部分,因為您無需猜測這些東西。
首先,BorderLayout參數僅在布局為BorderLayout時使用。 您可以改用GridBagLayout。 示例代碼如下
setLayout(new GridBagLayout());
add(new JButton("add"), new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
add(new JButton("Check In"), new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
add(new JButton("Check Out"), new GridBagConstraints(2, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
add(new JButton("Delete"), new GridBagConstraints(3, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
String[] Titles = {"one", "two", "three"};
jlist = new JList(Titles);
jlist.setVisibleRowCount(3);
add(new JScrollPane(jlist), new GridBagConstraints(0, 0, 4, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
這是您所期望的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.