How to scroll my JPanel - java

I'm creating a list of bank movements with the following code. pane is a JPanel and array is an ArrayList that contains respectively amount and description data. Setting is a little icon that allow you to modify each movement.
MouseClass is a class that extends MouseAdapter that I've created to add "k" index to mouseClicked method. I'm new with java gui programming. I'd like to know if there is a quick method to add a scroll to my panel
JLabel[] movement = new JLabel[array.size()];
JLabel[] description = new JLabel[array.size()];
JLabel[] data = new JLabel[array.size()];
JLabel[] setting = new JLabel[array.size()];
System.out.println(array.size());
int i = 0;
for(int k=0; k<array.size(); k++){
movement[k] = new JLabel("");
movement[k].setForeground(SystemColor.text);
movement[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
movement[k].setBounds(17, i, 145, 30);
movement[k].setText(array.get(array.size() - k - 1).getAmount() + "€");
panel.add(movement[k]);
description[k] = new JLabel("");
description[k].setForeground(SystemColor.text);
description[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
description[k].setBounds(187, i, 274, 30);
description[k].setText(array.get(array.size() - k - 1).getDescription());
panel.add(description[k]);
data[k] = new JLabel("");
data[k].setForeground(SystemColor.text);
data[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
data[k].setBounds(478, i, 145, 30);
data[k].setText(array.get(array.size() - k - 1).getDate());
panel.add(data[k]);
setting[k] = new JLabel();
setting[k].setIcon(new ImageIcon(List.class.getResource("/it/andreavaiuso/financemanager/images/edit.png")));
setting[k].setForeground(SystemColor.text);
setting[k].setFont(new Font("Segoe UI", Font.PLAIN, 20));
setting[k].addMouseListener(new MouseClass(array.size() - k - 1) {
#Override
public void mouseClicked(MouseEvent arg0) {
Modify mdf = new Modify(this.index);
mdf.setVisible(true);
dispose();
}
});
setting[k].setBounds(640, i, 82, 30);
panel.add(setting[k]);
i += 40;
}
But I don't know how to scroll it. I've tried woth JScrollPane but don't work!
I'm sure there is a simplest way to add these items to my panel...

I've tried woth JScrollPane but don't work!
Well I see lots of code with setBounds(...) which implies you are using a null layout.
Don't use a null layout. Swing was designed to be used with layout managers. In fact the scroll pane will only work when used with a layout manager because the scroll pane needs to know the preferred size of the panel so it can determine when you use scrollbars.
I would also suggest you should also be using a JTable for something like this. It is more efficient because you don't need to create individual components for each row of data. Read the section from the Swing tutorial on How to Use Tables for more information and examples.

For a JScrollPane you need, 1 JScrollPane, 1 JList and one DefaultListModel.
First you add your items to DefaultListModel, then you add the model to the JList and then you make a JSCrollPane with passing as argument your JList
Example:
DefaultListModel model = new DefaultListModel<String>();
JList list = new JList<String>();
model.addElemenet("1");
model.addElemenet("3");
model.addElemenet("2");
list.setModel(model);
JScrollPane scrollPane = new JScrollPane(list);

Related

How i can add a list of JLabels in Java Swing

I'm trying to create a list of labels in java swing.
Main Code:
JLabel local = new JLabel();
local.setBackground(new Color(186, 79, 84));
local.setFont(new Font("SansSerif", Font.BOLD, 10));
local.setForeground(new Color(255, 255, 255));
local.setText("Local");
JTable list = new JTable(new JLabel[][]{{local}}, new String[]{"Local"});
But it's giving me a little problem.
What would be the best way, the goal would be to create a vertical list with one item on each line.

Generating java swing fields based on user input

Java beginner here.
I am trying to generate Labels based on user input(take input for the number of labels to generate between 0 to 50) in a JPanel inside a JScrollPane.
The labels are generating correctly but the problem is the panel cant be scrolled down to view all the Labels.
Is it because I am using absolute layout for the panel? If yes then what might be the solution? Please guide.
Note: I made the labels using an array of 50 JLabels in a for loop. Terrible programming practice maybe but works.
Here's the code snippet
frame = new JFrame();
frame.setSize(800, 800);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(103, 37, 439, 350);
frame.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(null);
JButton btnGenerateLabels = new JButton("Generate Labels");
btnGenerateLabels.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel[] lab = new JLabel[50];
int y = 50;
for(int i=0; i<50; i++)
{
lab[i] = new JLabel();
lab[i].setText("Label "+(i+1));
panel.add(lab[i]);
lab[i].setBounds(180, y, 97, 25);
y += 30;
}
}
});
btnGenerateLabels.setBounds(129, 23, 152, 25);
panel.add(btnGenerateLabels);
Is it because I am using absolute layout for the panel?
Yes. Don't use a null layout. Swing was designed to be used with layout managers.
The solution is to use a layout manager, probably the GridLayout as was suggested.
After all the components have been added to the panel you then need to invoke revalidate() and repaint() on the panel. This will invoke the layout manager and each component will be given a size/location.
Scrollbars will then appear as required.

JList of TextFields and JScrollPane doesn't show / Java Swing

I am trying to create a window that shows a dynamic list of textFields and
if the number of textfields is large then I want to add a scroller.
I am using GridLayout.
The problem is that the panel I added the Jlist and scroller doesn't show anything, neither the list nor the scroller. Below you will find a part of my code.
//Label
JLabel numberOfTxt = new JLabel("Please enter the number in every TextField");
int n = 11; //A random number of TextFields
firstPanel.add(numberOfTxt, BorderLayout.NORTH); //Add label to panel
JList textFieldList = new JList(); //Create a list of TextFields
for (int i = 0; i < n; i++) {
//Add TextFields to list
JTextField textField = new JTextField();
textField.setBounds(0, 0, 6, 0);
textFieldList.add(textField);
System.out.println("textFieldList" + textFieldList);
}
textFieldList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
textFieldList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
textFieldList.setVisibleRowCount(8);
//Create scroller
JScrollPane listScroller = new JScrollPane(textFieldList);
listScroller.setBounds(0, 20, 600, 600);
//Create layout for panel where the textfields will be added
if (n % 2 != 0) {
n = n + 1;
}
thirdPanel.setLayout(new GridLayout(n / 2, 2, 10, 6));
thirdPanel.add(textFieldList);
thirdPanel.setVisible(true);
//ContentPane has BoxLayout
contentPane.add(firstPanel);
contentPane.add(thirdPanel);
contentPane.repaint();
window.pack();
}
window.revalidate();
}
});
JList does not works this way. If you really need a JList of TextFields you should use ListCellRenderer (probably you don't, see p.3).
You adding textFieldList both to listScroller and thirdPanel. Probably, you should replace thirdPanel.add(textFieldList); by thirdPanel.add(listScroller);.
thirdPanel uses GridLayout, but only one control is ever added to it. You should either add TextField directly to thirdPanel (easier way), or let the JList manage them.

Individually Identifying JButtons in a GridLayout

I have been creating a system by which I am listing various seats on a train within a GUI. I had decided to use a simple grid layout with numbered JButtons representing the seats and the seatNo and empty JLabels to represent empty space (I realise this may be trivial but it was simple). I have used a Gridlayout and I have created the Buttons and Labels as shown below.
I have an List (compArray2) in a separate class that consists of 0s and 1s and a direction that represent where there should be a seat and where the shouldn't be a seat. the .getNum gets the value either 0 for empty space or 1 for a seat and the .getDir gets the direction the seat will be facing.
public JPanel rowPanelCreation(int type, int rowNo, int width){
theNoOfSeats=0;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,width));
List<seatLayout> layout = new ArrayList<>();
layout = ModelConstants.compArray2;
for (seatLayout isit : x2){
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
if (isit.getNum()==0){
if (isit.getDir()=='x'){
panel.add(buttonDis);
}
}
else if (isit.getNum()==1){
theNoOfSeats++;
if (isit.getDir()=='N'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultN.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='E'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultE.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
buttonEna.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"You have chosen : ");}});
panel.add(buttonEna);
}
else if (isit.getDir()=='S'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultS.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='W'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultW.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
}
}
return panel;
}
the main problem I am having is that when I press one of the seat buttons I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo. Is there a better way I could do this ? I'm assuming that as all the buttons are fundamentally the same, there is no way to differentiate between them ?
"I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo."
Here's your problem. It's a reference problem. In the end, all the buttons will have the same JButton and JLabel reference. So all the buttons and labels will get the last button and label reference created, hence "displays the very last seatNo."
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
You need to create a new JButton and new JLabel reference each iteration
JBUtton buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
JLabel buttonDis = new JLabel();
Another approach would be to have an array of JButton, loop to set the buttons, and add them to the Panel. Say you have a GridLayout(2, 2). You then would need a array of 4 JButtons
JButton[] buttons = new JButton[9];
...
for (int i = 0; i < 4; i++){
buttons[i] = new JButton();
buttons[i].setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
// set other properties for button
panel.add(buttons[i]);
}

Java Swing: JScrollPane not working

I have a JPanel which contains some fields. The height of the JPanel is limited so I have to put a JScrollPane around it so people can scroll down.
As you can see below, it displays perfectly. But you can't scroll down (or up).
DetailPanel detail = new DetailPanel();
JScrollPane jsp = new JScrollPane(detail);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setBounds(745, 10, 235, 225);
add(jsp);
Detail panel:
private void init(){
setLayout(null);
setSize(140, 400);
int x = 5, y = 0;
for(int i = 0; i < lbls.length; i++) {
JLabel lbl = new JLabel(lbls[i]);
lbl.setBounds(x, y, 200, 25);
add(lbl);
fields[i] = new JTextField();
fields[i].setBounds(x, y+26, 200, 25);
add(fields[i]);
y+=50;
}
}
Your DetailPanel has no layout manager associated with it, which means it doesn't expand when you add children to it, which means the JScrollPane doesn't have anywhere to scroll. Either call setLayout() on your DetailPanel or override getPreferredSize() to add up the heights of its children and return a meaningful value.
I could be wrong, but I think this might be happening because DetailPanel's layout is null. What happens if you use a BoxLayout in vertical orientation and call detail.setPreferredSize(new Dimension(140,400));?

Categories

Resources