After reading this answer, I came to using getPreferredSize instead of setPreferredSize. But I still can't use the @Override getPreferredSize
, but that's not the main problem I'm facing right now.
I have a CardLayout
application which calls a class called HiraganaData
HiraganaData is a class which extends a JPanel
so it can be used by the CardLayout
, but it also has 2 more JPanel
s on it, one for a "back" button and one for the rest of buttons, before using this idea I was using a JTable, but faced problems on making cells as buttons, so I dropped the idea and came with this new one using GridLayout
. Some of the buttons will be disabled, anyway I can do that and won't include that code since it's not relevant.
So my actual question or problem is:
- How can I add a
JScrollPane
only tobuttonsPanel
, did my best trying to add it even to the whole "global" pane w/o success.
This is the most aproximate GUI I can do with the same code of my class I just added a JFrame to it.
Not sure if relevant, but I'm using a CardLayout
with different sizes, in the way @MadProgrammer suggested on this answer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.DefaultCellEditor;
import java.awt.Dimension;
public class HiraganaPage extends JPanel {
JFrame frame = new JFrame("Hello");
JButton kanas[][] = new JButton[26][5];
JButton backButton = new JButton("back");
JPanel backPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
public static void main(String args[]) {
new HiraganaPage();
}
public HiraganaPage() {
JPanel pane = new JPanel();
backPanel.add(backButton);
buttonsPanel.setLayout(new GridLayout(0, 5));
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.add(backPanel);
//pane.setPreferredSize(new Dimension(500, 500));
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 5; j++) {
kanas[i][j] = new JButton("1");
buttonsPanel.add(kanas[i][j]);
}
}
JScrollPane scroll = new JScrollPane(buttonsPanel);
pane.add(buttonsPanel);
this.add(pane, BorderLayout.CENTER);
frame.add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(50, 50);
frame.setSize(300, 300);
}
}
This is how it looks like in my complete application
And this is how it looks like in the MCVE.