Тема: Прошу допомоги з JScrollPane
Не можу помістити JPanel з елементами в JScrollPane. Не прокручується, і взагалі чомусь розташовується з боку. Підкажіть де помилка?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame{
private JButton a = new JButton("my a button");
private JButton b = new JButton("button");
private JButton c = new JButton("button br");
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JLabel label = new JLabel(
"<html>Once upon <br>a time,<br>" +
"a mouse, <br>" +
"a bird, <br>" +
"and <br>a sausage, <br>" +
"entered <br>into <br>" +
"partnership <br>and <br>" +
"set up house <br>together. <br>" +
"For a long <br>time all <br>" +
"went <br>well; <br>" +
"they lived <br>in great <br>comfort, <br>" +
"and <br>prospered <br>so far <br>" +
"as to be <br>able to <br>" +
"add <br>considerably <br>" +
"to their <br>stores.");
public MyFrame(String str){
super(str);
setSize(600, 450);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new GridBagLayout());
JScrollPane sp = new JScrollPane();
sp.setViewportView(panel2);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(sp);
add(panel1, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(2, 2, 2, 2), 0, 0));
add(panel2, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(2, 2, 2, 2), 0, 0));
panel2.setLayout(new GridBagLayout());
panel1.setLayout(new GridBagLayout());
panel1.add(a);
panel2.setVisible(false);
panel2.add(label, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(2,2,2,2),0,0));
panel2.add(b, new GridBagConstraints(0, 1, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(2, 2, 2, 2), 0, 0));
panel2.add(c, new GridBagConstraints(0, 2, 1, 1, 1, 1,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new Insets(2,2, 2, 2), 0, 0));
a.setCursor(new Cursor(Cursor.HAND_CURSOR));
a.addActionListener(new AButtonActList());
b.setCursor(new Cursor(Cursor.HAND_CURSOR));
b.addActionListener(new BButtonActList());
b.setPreferredSize(c.getPreferredSize());
b.setMinimumSize(b.getPreferredSize());
}
private void createUIComponents() {
}
public class AButtonActList implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
panel1.setVisible(false);
panel2.setVisible(true);
}
}
public class BButtonActList implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
panel1.setVisible(true);
panel2.setVisible(false);
}
}
}