0
JScrollPane
當我給它一個JPanel
時完美工作,然後將JScrollPane
直接添加到JFrame
和frame.getContentPane.add()
。 然而,當我將JScrollPane
添加到JPanel
,然後將JPanel
添加到JFrame
它不起作用。我需要使用第二種方法,因爲我要在JPanel
和JFrame
內添加多個內容,並且需要保持其組織性。這是我的代碼。JScrollPane在JPanel中不起作用
import java.awt.*;
import javax.swing.*;
public class Main {
/**
* @param inpanel asks if the JScrollPane should
* be inside of a JPanel (so other things can also be added)
*/
public static void testScroll(boolean inpanel) {
JFrame f = new JFrame();
f.setLayout(new BorderLayout());
f.setResizable(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.red));
//panel.setLayout(new BoxLayout(panel, 1));
panel.setLayout(new GridLayout(0,1));
for (int i = 0; i < 100; i++) {
JLabel l = new JLabel("hey"+i,SwingConstants.CENTER);
l.setBorder(BorderFactory.createLineBorder(Color.green));
l.setPreferredSize(new Dimension(200,200));
panel.add(l);
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setBorder(BorderFactory.createLineBorder(Color.blue));
//**********THIS DOES NOT WORK HOW I WANT IT TO************
if(inpanel){
JPanel holder = new JPanel();
holder.add(scrollPane);
f.getContentPane().add(holder);
}
//************THIS DOES WORK HOW I WANT IT TO****************
else{
f.getContentPane().add(scrollPane);
}
f.pack();
f.setSize(500, 500);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setVisible(true);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setValue(bar.getMaximum());
bar.setUnitIncrement(50);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
testScroll(false); //OR TRUE
}
};
SwingUtilities.invokeLater(r);
}
}
在main方法,如果我通過假的,它就像我之前提到的,但是當我通過真實的它顯示了無需滾動條。
圖片時傳遞true時
圖片
我需要一種方法來添加JScrollPane
到JPanel
,仍然有它的工作。 在此先感謝!
非常感謝!它現在有效。 –
你爲什麼要調用f.pack()和f.setSize()? – FredK
我只是在測試一些東西,我不會同時使用兩者 –