我正在嘗試將內容添加到 mainPanel 和 mainpanel 到 mainScrollPane。但是,會顯示一個空對話框。
重要提示:必須使用 JPanel 和 JScrollPane 來實作...
`setModal(true);
setTitle("Edit item");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(400, 700));
JScrollPane mainScrollPane = new JScrollPane();
mainScrollPane.add(mainPanel);
setLayout(new BorderLayout());
add(mainScrollPane);
mainPanel.add(new JLabel("ID: "));
mainPanel.add(txtID = new JTextField(item.getID()));
mainPanel.add(new JLabel("Description: "));
mainPanel.add(txtDescription = new JTextField(item.getDescription()));
pack();
setVisible(true);`
感謝你們
uj5u.com熱心網友回復:
重要提示:必須使用 JPanel 和 JScrollPane 來實作...
JScrollPane mainScrollPane = new JScrollPane();
mainScrollPane.add(mainPanel);
您不應該將組件直接添加到滾動窗格中。相反,您需要將組件添加到viewport滾動窗格中。
這可以通過使用來完成:
JScrollPane mainScrollPane = new JScrollPane(mainPaneol);
//mainScrollPane.add(mainPanel);
或者
JScrollPane mainScrollPane = new JScrollPane();
//mainScrollPane.add(mainPanel);
mainScrollPane.setViewportView(mainPanel);
然后滾動窗格會像您的代碼當前那樣添加到框架中。
請注意,您不會注意到滾動窗格的使用,因為當前沒有理由顯示滾動條。所以真的不需要使用滾動面板,你可以直接將面板添加到框架中。
uj5u.com熱心網友回復:
請提供一個最小的可重現示例。它可能如下所示:
MyFrame.java
import javax.swing.*;
import java.awt.*;
class Item {
String id;
String description;
Item(String id, String description) {this.id = id;this.description = description;}
String getId() {return id;}
String getDescription() {return description;}
}
public class MyFrame extends JFrame {
Item item = new Item("007", "Special watch");
public MyFrame() {
// setModal(true);
setTitle("Edit item");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(400, 700));
mainPanel.add(new JLabel("ID: "));
mainPanel.add(new JTextField(item.getId()));
mainPanel.add(new JLabel("Description: "));
mainPanel.add(new JTextField(item.getDescription()));
/* From Oracle's documentation, see link below:
Creates a JScrollPane that displays the contents of the
specified component, where both horizontal and vertical
scrollbars appear whenever the component's contents are
larger than the view.
*/
JScrollPane mainScrollPane = new JScrollPane(mainPanel);
// Just to show the bars
mainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
getContentPane().add(mainScrollPane); // <- This makes it shine!
pack();
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
$ javac MyFrame.java
$ java MyFrame
等等:

https://docs.oracle.com/javase/8/docs/api/javax/swing/JScrollPane.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482327.html
