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.
Related
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);
I've bee teaching myself java and following along with the problems in the book. I'm trying to make a display for my calculator. In the example(I did not attach this) the buttons were a smaller size than what mine are and I can't figure out how to reformat them. I tried using the dimension class but it had no affect. Also, I can't get my text at the top of the calculator to align left.
Here is my code:
public class Calculator extends JFrame {
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(300, 300);
setLayout(new BorderLayout());
JPanel numberPanel = new JPanel();
add(numberPanel, BorderLayout.CENTER);
numberPanel.setLayout(new GridLayout(4, 3, 3, 3));
for(int i = 1; i < 10; i++) {
JButton button = new JButton(String.valueOf(i));
numberPanel.add(button);
}
JButton zero = new JButton("" + 0);
JButton dot = new JButton(".");
JButton clear = new JButton("C");
numberPanel.add(zero);
numberPanel.add(dot);
numberPanel.add(clear);
JPanel keyPanel = new JPanel();
add(keyPanel, BorderLayout.EAST);
keyPanel.setLayout(new GridLayout(4, 1, 3, 3));
JButton plus = new JButton("+");
JButton minus = new JButton("-");
JButton times = new JButton("*");
JButton divide = new JButton("/");
keyPanel.add(plus);
keyPanel.add(minus);
keyPanel.add(times);
keyPanel.add(divide);
JPanel equalsPanel = new JPanel();
add(equalsPanel, BorderLayout.SOUTH);
equalsPanel.setLayout(new GridLayout(1, 1));
JButton equals = new JButton("=");
equalsPanel.add(equals);
JPanel textPanel = new JPanel();
add(textPanel, BorderLayout.NORTH);
JTextField inputBox = new JTextField("0.0");
inputBox.setHorizontalAlignment(JTextField.LEFT);
inputBox.setEditable(false);
Font font = new Font("MonoSpaced", Font.BOLD, 20);
inputBox.setFont(font);
textPanel.add(inputBox);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
}
Imports were left off for brevity
GridLayout will laugh at you when you try and set a dimension. It does respect preferred sizes. You should select a layout manager that will respect preferred sizes. Or you can simply pack() (after you add all your components) your frame instead of setSize() and all the components preferred sizes will kick in. (Disclaimer - because of GridLayout though, if you try and resize the frame after that, you components will resize again)
See more at How to use Layout Managers. For a quick view of which layout managers respect preferred sizes and which ones don't, have a look at this post.
A common approach is to nest panels with different layout managers also, as seen here
UPDATE
As mentioned preciously, you should just call pack on the frame instead of set size. With your current code, this would cause the frame to be very small because of the preferred sizes of the components. If you want the buttons to have a bigger preferred size, you can set the font to a bigger font and/or use button.setMargins(new Insets(w,x,y,x)); to make the margins bigger. But it is preferred to pack the frame.
I would recommend using the Window Builder add-on if you’re using Eclipse. This tool will help you with many aspects of Swing. Learn by doing.
WindowBuilder Dowload Link
When i add another JPanel into frame previous will dissapper (or probably overlaps the previous one). How can i stop this overlapping?
public Attack() {
JFrame frame = new JFrame("Oracle Padding Attack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel1.setLayout(null);
JLabel label1 = new JLabel("Inicialization vector:");
createTextField(10, 40, arrayIV, panel1, "HH", true, false);
label1.setBounds(10, 0, 120, 50);
panel1.add(label1);
panel2.setLayout(null);
JLabel label2 = new JLabel("Encrypted text:");
createTextField(400, 40, encryptedTextArray, panel2, "00", true, false);
label2.setBounds(400, 0, 120, 50);
panel2.add(label2);
frame.add(panel1);
frame.add(panel2);
frame.setSize(900, 400);
frame.setVisible(true);
}
It depends on how you want your two panels placed inside your frame. You will need a layout for your frame.
If you want to be able to "jump" from one to the other, cardLayout is your answer.
Otherwise if you want both side to side for example, you will have to use a layout inside your frame. I like the MigLayout, but GridLayout will do the job just fine.
http://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html
All build in layout handlers can be found here: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Also it's not recommended to use null layout at all since it will break the look if the window is resized.
I'm trying to add a JLabel to a JPanel to a JFrame. I set the border for the JPanel, but all I see on the JFrame is a small black square in the center of my frame. Whatever I do I can't change the size or location of it. Please help.
Start main = new Start();
Random random = new Random();
JFrame mainFrame = new JFrame("MainFrame");
JPanel mainPanel = new JPanel();
JLabel welcomeLabel = new JLabel();
mainFrame.add(main);
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle(names[random.nextInt(names.length)]);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setSize(mainFrameX, mainFrameY);
mainFrame.setResizable(false);
mainFrame.setLocationRelativeTo(null);
mainFrame.add(mainPanel);
mainPanel.add(welcomeLabel);
mainPanel.setBorder(new LineBorder(Color.BLACK));
mainPanel.setSize(new Dimension(200, 200));
welcomeLabel.setFont(new Font("Verdana", 1, 20));
welcomeLabel.setLocation(100, 100);
main.start();
Suggestions:
You will want to read the tutorial, Laying out Components, as it will explain how to code with the Swing layout managers, and this information is essential to solve your current problem.
One caveat: I urge you to avoid the temptation to use the null layout as use of it will lead to creation of code that is very hard to maintain or upgrade.
Your JLabel, welcomeLabel, will of course need some text to be visible.
Don't set it's location via setLocation(...) but again use the layout managers to do the dirty work of placing and sizing your components.
You will also want to call pack() and setVisible(true) on your JFrame after adding all initial components.
Hovercraft is right (+1), make sure you understand how the layout managers are working.
The order in which you do things are important, especially when dealing with the top level containers...
Start main = new Start();
Random random = new Random();
JFrame mainFrame = new JFrame("MainFrame");
JPanel mainPanel = new JPanel();
JLabel welcomeLabel = new JLabel();
welcomeLabel.setFont(new Font("Verdana", 1, 20));
mainPanel.add(welcomeLabel);
mainPanel.setBorder(new LineBorder(Color.BLACK));
// Do this first
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle(names[random.nextInt(names.length)]);
// Add your components
mainFrame.add(main);
mainFrame.add(mainPanel);
// Prepare the window for showing, now you have some content.
mainFrame.setResizable(false);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setLocationRelativeTo(null);
main.start();
This will still only produce a small black square in the window, because the JLabel has no content and therefore it's preferred size is going to be (something like) 2x2 (because of the border).
Try adding some text to...
welcomeLabel.setText("Welcome");
And then see the difference
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));?