jscrollpane to scrolling a panel - java

i have to writing an applet, in left side i must use an panel to contain a list of vehicles that can be a list of buttons,what is the problem, number of the vehicles are not given !!!
so, i need to scrolling panel when number of vehicles is too much,
i do this for jframe, but it didn't work correct with panel, please help me with an example
the code i use to scrolling panel is :
public class VehicleList extends JPanel {
private ArrayList<VehicleReport> vehicles;
private ArrayList<JButton> v_buttons = new ArrayList<JButton>();
public void showList(ArrayList<Vehicles> vehicles)
{
this.vehicles = vehicles;
//...
add(getScrollpane());
setSize(155,300);
}
public JScrollPane getScrollpane()
{
JPanel panel = new JPanel();
panel.setPreferredSize(new DimensionUIResource(150, 300));
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraint = new GridBagConstraints();
panel.setLayout(gridbag);
constraint.fill = GridBagConstraints.HORIZONTAL;
JLabel title = new JLabel("Vehiles list");
constraint.gridwidth = 2;
constraint.gridx = 0;
constraint.gridy = 0;
constraint.ipady = 230;
gridbag.setConstraints(title, constraint);
panel.add(title);
// end of set title
constraint.gridwidth = 1;
int i=1;
for(JButton jb : v_buttons )
{
constraint.gridx =0;
constraint.gridy = i;
gridbag.setConstraints(jb, constraint);
panel.add(jb);
JLabel vehicle_lable = new JLabel("car" + i);
constraint.gridx = 1;
constraint.gridy = i;
gridbag.setConstraints(vehicle_lable, constraint);
panel.add(vehicle_lable);
i++;
}
JScrollPane jsp = new JScrollPane(panel);
return jsp;
}
}
in jaframe after add jscrollpane to jframe i place this
pack();
setSize(250, 250);
setLocation(100, 300);
and it work clearly!!!!

You also don't show us the layout manager of the VehicleList JPanel. In case you aren't setting it, it defaults to FlowLayout, unlike JFrame (which you mentioned this does work in), whose content pane defaults to BorderLayout. So maybe you just need to change the relevant code from:
//...
add(getScrollpane());
to
//...
setLayout(new BorderLayout());
add(getScrollpane(), BorderLayout.CENTER);

You need to set the scrolling policy on the horizontal and vertical:
public void setHorizontalScrollBarPolicy(int policy)
public void setVerticalScrollBarPolicy(int policy)
Using:
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
And:
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
JScrollPane.VERTICAL_SCROLLBAR_NEVER
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
So for example:
jscrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

Related

Setting Size is not overriding on Java

I am having issue where my JPanel is not setting up the size. I am not sure if is something to do with my JTab or JFrame. I am using GridBagLayout layout management. And for some reason are not able to set the size.
Here is a dummy code, following the same logic to my original source code:
FirstPanel.java
import javax.swing.*;
import java.awt.*;
public class FirstPanel extends JPanel {
private JLabel label1 = new JLabel("Label 1");
private JTextField textField1 = new JTextField();
private GridBagConstraints c = new GridBagConstraints();
public FirstPanel() {
//Size is not overriding
Dimension size = getPreferredSize();
size.width = 100;
setPreferredSize(size);
setBorder(BorderFactory.createTitleBorder("Border Title");
setLayout(new GridBagLayout());
addComponents();
}
private void addComponents() {
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(5, 0, 0, 0);
add(label1, c);
c.gridx = 1;
add(textField1, c);
c.weightx = 1;
c.weighty = 1;
add(new JLabel(""), c);
}
}
MainPanel.java
import javax.swing.*;
import java.awt.*;
public class MainPanel {
private JFrame frame = new JFrame("App");
private JPanel panel1 = new JPanel(new GridBagLayout());
private GridBagConstraints c = new GridBagConstraints();
private JTabbedPane tabPane = new JTabbedPane();
public MainPanel() {
addComponents();
frame.add(tabPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 350);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
private void addComponents() {
tabPane.addTab("Tab 1", new FirstPanel());
}
}
Main.java
public class Main {
public static void main(String[] args) {
new MainPanel();
}
}
Or at least have two JPanels,
Exactly.
Frist you create a main panel using a BorderLayout that you add to the tabbed pane.
Then you have a second panel for your labels and text fields (using whatever layout manager you want). Then you add this panel to the BorderLayout.LINE_START.
Then you add your scrollpane containing the JTable to the BorderLayout.CENTER of the main panel.
Read the tutorial on Layout Manager. Nest panels with different layout managers as required.
want to have JTable taking 50% of the other side.
Picking a random number like 50% is not the way to design a GUI. What happens if the frame is made smaller/larger. What happens to the space? Design the layout with flexibility in mind, just like your browser window is designed. There are always fixed areas where the size is determined by the components added and there is a flexible area that grows/shrinks as desired.

GridBagLayout Not Working when adding second element

I'm just learning about GridBagLayout. When I add a JTextField to my layout, everything seems to disappear
// final JTextField textField = new JTextField("textField");
// addComponentToGridbag(textField, 0,0,1,1);
JButton button = new JButton("Button");
addComponentToGridbag(button, 1,0,1,1);
If I leave those first two lines commented out, I get this, which is OK except that there is no text field (of course):
But I want a text field to appear directly above the button, so I uncomment those two lines. And then I get this (notice how not only did my button disappear, but so did my top and bottom panels):
What is going on? How can I get a text field to appear without losing the other stuff? Thanks!
Here is the entire class:
public class GUI {
private JFrame frame;
private JPanel topPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
private GridBagLayout layout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
private JPanel centerPanel = new JPanel();
public GUI() {
makeMainFrame();
makePanels();
bodyLayout();
JLabel title = new JLabel("Dashboard");
topPanel.add(title);
JButton btnExit = new JButton("Exit");
bottomPanel.add(btnExit);
}
private void bodyLayout() {
centerPanel.setLayout(layout);
final JTextField textField = new JTextField("textField");
addComponentToGridbag(textField, 0,0,1,1);
JButton btnFetchMetaData = new JButton("Button");
addComponentToGridbag(btnFetchMetaData, 1,0,1,1);
}
private void addComponentToGridbag(Component component, int row, int column, int width, int height) {
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
centerPanel.add(component);
}
private void makeMainFrame() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = (int) (screenSize.height * 0.75);
int width = (int) (screenSize.width * 0.75);
frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Learning Java Swing");
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
}
private void makePanels() {
frame.getContentPane().add(topPanel, BorderLayout.NORTH);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
centerPanel.setBackground(Color.RED);
centerPanel.setOpaque(true);
frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
}
Reusing the same GridBagConstraints object might be a problem. Try always creating new GridBagConstraints in addComponentToGridbag method

Java JPanels not visible in Frame

Can someone please explain why my frame only shows p2 and not p1?
This happens to me often and I know I'm missing something.
public class Exercise_16_4 extends JFrame {
private static final long serialVersionUID = 1L;
JLabel[] labels = new JLabel[3];
JTextField[] textFields = new JTextField[3];
JButton[] buttons = new JButton[4];
String[] buttonText = {"Add", "Subtract", "Multiply", "Divide"};
String[] labelText = {"Number 1", "Number 2", "Result"};
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
public Exercise_16_4() {
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel(labelText[i]);
textFields[i] = new JTextField();
p1.add(labels[i]);
p1.add(textFields[i]);
}
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(buttonText[i]);
p2.add(buttons[i]);
}
add(p1);
add(p2);
}
public static void main(String[] args) {
Exercise_16_4 frame = new Exercise_16_4();
frame.setTitle("Exercise 16.4");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//main
}//class
The default layout manager for the content pane of a JFrame is a BorderLayout.
By default when you add a component to the frame is will be added to the CENTER of the BorderLayout. The problem is only one component can be added so only the last one added is displayed.
You can try something like:
add(p1, BorderLayout.NORTH);
Or you can create a JPanel add the p1, p2 components to the panel and then add the panel to the frame.
Read the section from the Swing tutorial on Layout Managers for more information and examples of using layout managers as well as examples that show you how to create the GUI on the Event Dispatch Thread.

2 JPanels in the same location using Jigloo Swing

My problem is that I need to make a GUI that, on startup, displays a login screen, then, when the user succesfully logs in, displays a different screen. I've visited other questions on both this board and on others, and on all of them, the general consensus is that instead of using two different, JFrames, I should use 2 JPanels in the same JFrame. When a user logs in, the first JFrame, asking for log in details, will have its visibility set to false and the second JFrame's visibility will become True. The problem I'm having here is that I can't seem to place 2 JPanels on the same location. I'm using Jigloo to work on Swing. Whenever I place the second JPanel and set its visibility to false, it's size becomes 0,0. I tried putting components on the second panel, then setting my preferred size and then switching the visibility to false, but both panels disappeared during executionm despite the first frame's visibility still being true and being the proper size. Help please!
I've answered a similar question wherein you've multiple panels within single JFrame.. and based on user action performed panels are replaced
Can't seem to get .remove to work
To skin the program based on your query:
public class Main extends JFrame implements ActionListener
{
private JPanel componentPanel = null;
private JPanel loginPanel = null;
private JLabel loginLabel = null;
private JPanel optionPanel = null;
private JLabel optionLabel = null;
private JButton loginButton = null;
public JPanel getComponentPanel()
{
if(null == componentPanel)
{
componentPanel = new JPanel();
GridBagLayout gridBagLayout = new GridBagLayout();
componentPanel.setLayout(gridBagLayout);
GridBagConstraints constraint = new GridBagConstraints();
constraint.insets = new Insets(10, 10, 10, 10);
loginPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
loginPanel.setMinimumSize(new Dimension(100, 50));
loginPanel.setPreferredSize(new Dimension(100, 50));
loginPanel.setMaximumSize(new Dimension(100, 50));
loginPanel.setBorder(
BorderFactory.createLineBorder(Color.RED));
loginLabel = new JLabel("Login Panel");
loginPanel.add(loginLabel);
componentPanel.add(loginPanel, constraint);
optionPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
optionPanel.setMinimumSize(new Dimension(100, 50));
optionPanel.setPreferredSize(new Dimension(100, 50));
optionPanel.setMaximumSize(new Dimension(100, 50));
optionPanel.setBorder(
BorderFactory.createLineBorder(Color.BLUE));
optionLabel = new JLabel("Option Panel");
optionPanel.add(optionLabel);
componentPanel.add(optionPanel, constraint);
loginButton = new JButton("Login");
constraint.gridx = 0;
constraint.gridy = 1;
loginButton.addActionListener(this);
componentPanel.add(loginButton, constraint);
}
return componentPanel;
}
public void actionPerformed (ActionEvent evt)
{
loginPanel.setVisible(false);
loginButton.setEnabled(false);
optionPanel.setVisible(true);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
Main main = new Main();
frame.setTitle("Simple example");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setContentPane(main.getComponentPanel());
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

GridBagLayout within JScrollPane not resizing properly

I have a JPanel with a GridBagLayout inside of a JScrollPane. I also have an 'add' button within the JPanel which, when clicked, will be removed from the JPanel, adds a new instance of a separate component to the JPanel, then adds itself back to the JPanel. This sort of makes a growing list of components, followed by the 'add' button.
Adding new components works fine, the JPanel stretches to accommodate the new components, and the JScrollPane behaves as expected, allowing you to scroll through the entire length of the JPanel.
This is how the add works:
jPanel.remove(addButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
jPanel.add(new MyComponent(), c);
jPanel.add(addButton, c);
jPanel.validate();
jPanel.repaint();`
Removal works by clicking a button inside the added components themselves. They remove themselves from the JPanel just fine. However, the JPanel keeps it's stretched-out size, re-centering the list of components.
This is how removal works:
Container parent = myComponent.getParent();
parent.remove(myComponent);
parent.validate();
parent.repaint();`
The question is, why does my GridBagLayout JPanel resize when adding components, but not when removing components?
You have to revalidate and repaint the JScrollPane, here is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTest {
public static void main(String[] args) {
final JPanel panel = new JPanel(new GridBagLayout());
for (int i = 0; i < 25; i++) {
JTextField field = new JTextField("Field " + i, 20);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridy = i;
panel.add(field, constraints);
}
final JScrollPane scrollPane = new JScrollPane(panel);
JButton removeButton = new JButton("Remove Field");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (panel.getComponentCount() >= 1) {
panel.remove(panel.getComponentCount() - 1);
scrollPane.revalidate();
scrollPane.repaint();
}
}
});
JFrame frame = new JFrame("Swing Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(640, 480);
frame.setLocation(200, 200);
frame.getContentPane().add(scrollPane);
frame.getContentPane().add(removeButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
}

Categories

Resources