Почему полоса прокрутки JScrollPane присутствует с самого начала приложения?JAVA

Программисты JAVA общаются здесь
Anonymous
Почему полоса прокрутки JScrollPane присутствует с самого начала приложения?

Сообщение Anonymous »

Я пытаюсь создать графический интерфейс на Java с помощью Netbeans. Я использую форму JFrame. Внутри него JScrollPane содержит JPanel. В JScrollPane свойству verticalScrollBarPolicy присвоено значение "AS_NEEDED", чтобы прокручивать только в том случае, если содержимое слишком велико.

Но моя проблема в том, что вертикальная полоса прокрутки присутствует с самого начала приложения. Как это решить?

Я поместил метод setLayout в свой JPanel в своем конструкторе (который раньше был в моем методе jMenuItem1ActionPerformed), и он, кажется, работает.

Однако у меня есть еще одна небольшая проблема. когда я открываю несколько файлов, их разделяет слишком большой промежуток (чего не происходит, когда файлов много).

Ниже представлен визуальный IHM, свойства JPanel и JScrollPane и созданный код.

Изображение
Изображение
Изображение


public class Items_IHM extends javax.swing.JFrame {

JCheckBox checkBox;
List listOfCheckBox = new ArrayList();
File[] allFiles;
File folder;

/**
* Creates new form Items_IHM
*/
public Items_IHM() {
initComponents();
panel.setLayout(new GridLayout(0, 1, 10, 10));
this.setLocationRelativeTo(null);
}

@SuppressWarnings("unchecked")
// //GEN-BEGIN:initComponents
private void initComponents() {

srollPane = new javax.swing.JScrollPane();
panel = new javax.swing.JPanel();
buttonExecute = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

srollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
srollPane.setMinimumSize(new java.awt.Dimension(300, 400));
srollPane.setPreferredSize(new java.awt.Dimension(200, 300));

javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 339, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 477, Short.MAX_VALUE)
);

srollPane.setViewportView(panel);

buttonExecute.setText("Execute");
buttonExecute.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExecuteActionPerformed(evt);
}
});

jMenu1.setText("Fichier");

jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Ouvrir");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);

jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("Quitter");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);

jMenuBar1.add(jMenu1);

jMenu2.setText("Editer");
jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonExecute, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(srollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(srollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonExecute, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// //GEN-END:initComponents

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
Preferences preferences = Preferences.userRoot();
String path = preferences.get("DEFAULT_PATH", "");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setCurrentDirectory(new File(path));
int returnVal = fileChooser.showOpenDialog(null);

if (returnVal == JFileChooser.APPROVE_OPTION) {
// allNameFilesTextArea.setText("");
folder = fileChooser.getSelectedFile();
fileChooser.setCurrentDirectory(folder);
preferences.put("DEFAULT_PATH", folder.getAbsolutePath());
allFiles = folder.listFiles(new FilenameFilter() {
public boolean accept(File folder, String name) {
return name.toLowerCase().endsWith(".csv");
}
});
listOfCheckBox.clear();
panel.removeAll();
panel.revalidate();
panel.repaint();
for (int i = 0; i < allFiles.length; i++) {
checkBox = new JCheckBox(allFiles.getName());
listOfCheckBox.add(checkBox);
panel.add(checkBox);
}
}
}//GEN-LAST:event_jMenuItem1ActionPerformed

private void buttonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteActionPerformed
Items_Application itemsApp;
try {
if (listOfCheckBox.size() > 0) {
itemsApp = new Items_Application(folder.getPath());
for (int i = 0; i < listOfCheckBox.size(); i++) {
if (listOfCheckBox.get(i).isSelected()) {
itemsApp.loadInItem(allFiles.getPath());
}
}
itemsApp.buildListOfItemsWithSamePartNb();
itemsApp.buildListOfItemsWithSameThalesNb();
itemsApp.writeOutItems(folder.getPath());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}//GEN-LAST:event_buttonExecuteActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
System.exit(0);
}//GEN-LAST:event_jMenuItem2ActionPerformed

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutor ... /plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Items_IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Items_IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Items_IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Items_IHM.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Items_IHM().setVisible(true);
}
});
}

Вернуться в «JAVA»