i want my progressbar at the center of the sreen. i already tried...
setLocationRelativeTo(null);
but when i run the program it didnt work. somehow it is not in the middle of the screen. Please help me. See image.
HERE ARE MY CODES
public class progressbar extends JFrame {
private JProgressBar jp;
private Timer t;
int i = 0;
public progressbar() {
setTitle("Loading...");
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
setLocationRelativeTo(null);
setUndecorated(true);
setVisible(true);
jp = new JProgressBar();
// Paint the percent complete on progress bar
jp.setStringPainted(true);
jp.setPreferredSize(new Dimension(500, 30));
jp.setMinimum(0);
jp.setMaximum(1000);
getContentPane().add(jp);
pack();
// Create a timer that executes for every 2 millisec
t = new Timer(2, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jp.setValue(i++);
if (i == 1000) {
t.stop();
setVisible(false);
loginInterface l = new loginInterface();
l.txtUser.requestFocus();
}
}
});
// Start the timer
t.start();
}
The GridBagConstraints
Anchor is Center, Grid Height 1, Grid Width 1, Grid X -1, Grid Y - 1
You need to create GridBagConstraints and define anchor (among others like x_weight) to center in GridBagLayout
Then add the component to the layout like this
GridBagLayout layout = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();
//set the constraints properties
layout.addLayoutComponent(JProgressBar, cons);
then
setLayout(layout)
Related
I can't figure out why this code doesn't make scrollbars appear. I'm a complete beginner at Swing so the scrollpanes are very confusing and I don't understand some of the solutions I have seen online. The annoying thing is this code briefly worked but I destroyed the successful part before backing it up when trying to add a component. Any help would be appreciated!
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
private JPanel leftPanel;
private JButton myButton;
private JPanel scrollPanel;
private JScrollPane scrollPane;
public static void main(String[] args)
{
System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new Test();
}
});
}
/**
* Constructor for objects of class Backup
*/
public Test()
{
this.setTitle("testy");
this.setSize(new Dimension(1280,622));
leftPanel = new JPanel();
leftPanel.setBackground(new Color(255,0,0));
leftPanel.setBounds(0, 100, 640, 558);
leftPanel.setEnabled(true);
this.add(leftPanel);
scrollPanel = new JPanel(null);
scrollPanel.setBackground(new Color(100,100,100));
scrollPanel.setPreferredSize(new Dimension(640, 550));
scrollPanel.setEnabled(true);
JScrollPane scrollPane = new JScrollPane(scrollPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(0, 0, 642, 550);
scrollPane.setEnabled(true);
leftPanel.add(scrollPane);
for (int i = 1; i < 30; i++)
{
scrollPanel.setLayout(new GridLayout(30, 1, 0, 1));
myButton = new JButton("AAAAAAAAAAAAAAAAAAAAA " + i);
myButton.setPreferredSize(new Dimension(630, 70));
scrollPanel.add(myButton);
}
this.setBackground(new Color(0,0,0));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
I think I've massively improved it since then thanks to camickr
Here is the current version:
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
private JPanel leftPanel;
private JButton myButton;
private JPanel scrollPanel;
private JScrollPane scrollPane;
public static void main(String[] args)
{
System.setProperty("swing.defaultlaf",
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new Test();
}
});
}
public Test()
{
this.setTitle("testy");
this.setSize(new Dimension(1280,622));
leftPanel = new JPanel();
leftPanel.setBackground(new Color(255,0,0));
leftPanel.setBounds(0, 100, 640, 558);
this.add(leftPanel);
scrollPanel = new JPanel();
scrollPanel.setLayout(new GridLayout(70, 1, 0, 1));
//scrollPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20,
20));
scrollPanel.setBackground(new Color(100,100,100));
//scrollPanel.setPreferredSize(new Dimension(640, 550));
//JScrollPane scrollPane = new JScrollPane(scrollPanel);
JScrollPane scrollPane = new JScrollPane(scrollPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//scrollPane.setLayout(new GridLayout(30, 1, 0, 1));
//scrollPane.setBounds(0, 0, 642, 550);
scrollPane.setEnabled(true);
//scrollPanel.add(scrollPane);
leftPanel.add(scrollPanel);
for (int i = 1; i < 71; i++)
{
myButton = new JButton("AAAAAAAAAAAAAAAAAAAAA " + i);
//myButton.setPreferredSize(new Dimension(640, 80));
scrollPanel.add(myButton);
}
this.setBackground(new Color(0,0,0));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}}
Don't use a null layout.
Don't use setBounds().
Don't use setPreferredSize().
Each Swing component is responsible for determining its own preferred size. The layout manager will then set the size/location of each components added to the panel and it will then (dynamically) calculated the preferred size of the panel. The scroll bars will appear when the preferred size of the panel is greater than the size of the scroll pane.
scrollPanel = new JPanel(null);
scrollPanel.setBackground(new Color(100,100,100));
// scrollPanel.setPreferredSize(new Dimension(640, 550)); // delete
//scrollPanel.setEnabled(true); // not needed
...
for (int i = 1; i < 30; i++)
{
//scrollPanel.setLayout(new GridLayout(30, 1, 0, 1)); // set layout when panel created.
//myButton.setPreferredSize(new Dimension(630, 70)); // not needed.
The layout manager should be set outside the loop, when you create the panel. It should NOT be null.
Don't hard code the preferred size. It will not dynamically adjust as components are added.
Swing components are enabled by default to setEnabled is not needed.
Don't use the "leftPanel". Just add the scroll pane directly to the frame. This will allow the scrollpane to resize dynamically as the frame is resized. Then the scroll bars will appear when requirement.
Don't set the preferreid size of the button. The size will be determined based on the text and the Font of the button.
The problem: I have no control on implementing more into the histogram package, so I create an array of buttons and overlay them on top of the histogram using JLayeredPane. However, I cannot get both the histogram plot and the buttons panels to scale when the JFrame is enlarged or contracted.
The JLayedPane is composed of 2 JPanels, see MWE.
To repeat the issue, just run program and extend JFrame.
I have read the following on SO posts; jlayeredpane-with-gridlayout, jlayeredpane-with-a-layoutmanager, jlayeredpane-not-resizing-with-jframe, resize-jframe-to-jpanels-inside-jlayeredpane, automatic-content-resizing-of-jlayeredpane,
as well as the Oracle page on JLayeredPane which has some examples
As useful as these links were, I still cannot get both JPanels to extend/contract with the JFrame.
Question: Is there a way to get both JPanels in the JLayeredPane to rescale without implementing a new layout? If new layout is needed, would someone please provide a MWE on how to do such?
public class FrameDemo extends JPanel {
private JLayeredPane layeredPane;
private final int width = 800;
private final int height = 800;
private String[] layerStrings = { "Yellow (0)", "Magenta (1)", "Cyan (2)", "Red (3)", "Green (4)", "Blue (5)" };
private Color[] layerColors = { Color.yellow, Color.magenta, Color.cyan, Color.red, Color.green, Color.blue };
public FrameDemo() {
setLayout(new BorderLayout());
init();
addPanels();
add(layeredPane, BorderLayout.CENTER);
}
private void init() {
this.layeredPane = new JLayeredPane();
this.layeredPane.setPreferredSize(new Dimension(width, height));
this.layeredPane.setBorder(BorderFactory.createTitledBorder("Histogram should go here"));
this.layeredPane.setLayout(new BorderLayout());
}
private void addPanels() {
this.layeredPane.add(createHistogramPanel(), BorderLayout.CENTER, new Integer(1));
this.layeredPane.add(createButtonPanel(), BorderLayout.CENTER, new Integer(0));
this.layeredPane.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
Dimension size = layeredPane.getSize(); // get size
createHistogramPanel().setSize(size); // push size through
createButtonPanel().setSize(size); // push size trhough
// otherChildOfLayers.setSize(size); // push size trhough
layeredPane.revalidate(); // revalidate to see updates
layeredPane.repaint(); // "Always invoke repaint after
// revalidate"
}
});
}
private JPanel createHistogramPanel() {
JPanel histpanel = new JPanel();
histpanel.setLayout(new GridLayout(2, 3));
for (int i = 0; i < layerStrings.length; i++) {
JLabel label = createColoredLabel(layerStrings[i], layerColors[i]);
histpanel.add(label);
}
histpanel.setOpaque(false);
histpanel.setBounds(10, 10, width, height);
return histpanel;
}
private JLabel createColoredLabel(String text, Color color) {
JLabel label = new JLabel("");
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color);
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.setPreferredSize(new Dimension(120, 120));
return label;
}
private JPanel createButtonPanel() {
ButtonGroup buttons = new ButtonGroup();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2, 3));
for (int i = 0; i < 6; i++) {
final int placer = i + 1;
JButton freshButton = new JButton();
freshButton.addActionListener(e -> {
System.out.println("Button " + placer + " clicked");
});
freshButton.setText("Button " + (i + 1));
freshButton.setOpaque(true);
freshButton.setContentAreaFilled(false);
freshButton.setBorderPainted(false);
freshButton.setBounds(new Rectangle(132, 75 + (i * 20), 40, 20));
buttonPanel.add(freshButton, null);
buttons.add(freshButton);
}
buttonPanel.setOpaque(false);
buttonPanel.setBounds(10, 10, width, height);
return buttonPanel;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new FrameDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Your code won't work because in componentResized you're creating new panels and applying the size to them. You need to resize the existing panels added to the layered pane. This could be done by assigning histogramPanel and buttonPanel as instance variables.
I'm trying to make a JFrame with a JProgressbar and a JButton inside, for the user to be see how far the process is and able to abort the process.
The only issue I seem to encounter, the progressbar and button components to always adjust to the JFrame size, and not the size I set them to. See picture one; Picture 1
The goal is to make it look like this example; Picture 2
Does anyone have some suggestions?
See my code below;
JFrame f = new JFrame("Retrieve Datalog");
JButton b = new JButton("Abort");
JProgressBar progressBar = new JProgressBar();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setIconImage(ICONBAR.getImage());
f.setResizable(false);
f.setSize(300, 100);
f.setLocationRelativeTo(getFrame());
b.setSize(50, 10);
progressBar.setSize(f.getWidth() - 100, f.getHeight() - 50);
progressBar.setValue(50);
progressBar.setStringPainted(true);
f.add(progressBar, BorderLayout.NORTH);
f.add(b, BorderLayout.CENTER);
f.setVisible(true);
PS:
I'm using NetBeans 8.1 IDE, JDK v8u91
I try some code. You can use Grid bag layout. There is the code and snapshot
Snapshot
import java.awt.*;
import javax.swing.*;
/**
* JFrame with a progress bar and button. With the size of their own.
*
* #author Tadesse
*/
public class Test extends JFrame {
JButton button = new JButton("Cancel");
JProgressBar progressBar = new JProgressBar();
public Test() {
GridBagConstraints g = new GridBagConstraints();
setLayout(new GridBagLayout());
set(g, 0, 0, GridBagConstraints.CENTER);
add(progressBar, g);
set(g, 0, 1, GridBagConstraints.CENTER);
add(button, g);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200, 100);
setVisible(true);
}
public void set(GridBagConstraints c, int x, int y, int anchor) {
c.gridx = x;
c.gridy = y;
c.anchor = anchor;
}
public static void main(String[] args) {
new Test();
}
}
I have a JPanel(named mainJP) which has a few buttons and labels (uses BorderLayout). Next it adds another JPanel (named JP1) and inside it a ScrollPane with a JTable. I want to be able to resize JP2 and in turn all its child components (ScrollPane and JTable). So that I can see few more rows of the JTable without having to scroll. Also inorder to resize JP1, other siblings of JP1 should adjust themselves. Not sure how to achieve that.
As the image shows I already have a few features implemented - to entirely delete JP1, to expand/collapse JP1 view, to delete and add rows in the JTable.
So basically I want to be able to drag the mouse at bottom border of JP1 to vertically increase the size of JP1 and its child components (ScrollPane and JTable).
As described in a few of the below solutions, I am still confused at which level should I incorporate a JSpiltPane - as it allows only adding 2 components. I think all the JP1 should be in the JSplitPane. However there can be more than one JP1 components and they are dynamically added.
To add extra components to the JSplitPane is easy. Put a JPanel in each pane you want to show your components, then add the components to this panel -- you can customize the layout as needed.
Something like this will put a JSplitPane in an already create JFrame, add a JPanel to each Pane, and then add some JLabels to the left side, a JTextField to the right. The splitpane will expand to the size of the JFrame it's in.
JSplitPane splitPane = new JSplitPane();
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JTextField textField = new JTextField();
GridBagConstraints gBC = new GridBagConstraints();
getContentPane().setLayout(new GridBagLayout());
leftPanel.setLayout(new GridBagLayout());
rightPanel.setLayout(new GridBagLayout());
// I'm not going to bother doing any layout of the label or textfield here
leftPanel.add(label1, new GridBagConstraints());
leftPanel.add(label2, new GridBagConstraints());
rightPanel.add(textField, new GridBagConstraints());
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
gBC.fill = GridBagConstraints.BOTH;
gBC.weightx = 1.0;
gBC.weighty = 1.0;
getContentPane().add(splitPane, gBC);
pack();
These are two different problems. Resizing a JPanel on a mouse drag -- the easiest way for you is going to be to use two nested JSplitPanes. You would use one so you can drag horizontally, and another to drag vertically.
Alternatively, if you don't want split panes, you can try something like this method and create a custom JPanel. The borders are there to make the effect more visible. I personally don't like it as it's overly complicated.
public class ResizablePanel extends JPanel {
private boolean drag = false;
private Point dragLocation = new Point();
public ResizablePanel() {
setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
setPreferredSize(new Dimension(500, 500));
final JFrame f = new JFrame("Test");
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
drag = true;
dragLocation = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
drag = false;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (drag) {
if (dragLocation.getX()> getWidth()-10 && dragLocation.getY() > getHeight()-10) {
System.err.println("in");
setSize((int)(getWidth()+(e.getPoint().getX()-dragLocation.getX())),
(int)(getHeight()+(e.getPoint().getY()-dragLocation.getY())));
dragLocation = e.getPoint();
}
}
}
});
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(this,BorderLayout.CENTER);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new ResizablePanel();
}
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
As for the children resizing with it's parent, that one is pretty easy with GridBagLayout.
The important parts to remember in the GridBagConstraints are the fill, weightx and weighty.
You can just do something like this in your frame -- it will put a scrollpane with a JTable in it that will resize with the frame:
JScrollPane jScrollPane1 = new JScrollPane();
JTable jTable1 = new JTable();
GridBagConstraints gBC = new GridBagConstraints();
getContentPane().setLayout(new GridBagLayout());
jScrollPane1.setViewPortView(jTable1);
gBC.fill = GridBagConstraints.BOTH;
gBC.weightx = 1.0;
gBC.weighty = 1.0;
getContentPane().add(jScrollPane1, gBC);
I have a JScrollPane that contains a vertical Box. I'm inserting new JPanel's at the top of Box. If I use the scrollbar to scroll down I'd like for the current view to remain where I scrolled down to. For example, if I have 50 panels in the box and use the scrollbar to view panel 20, I'd like the view to remain on box 20 even though other boxes are added on top. Additionally, if I use the scrollbar to scroll back up to the top I'd like the view to display new panels as they are added. Any idea how to do this?
BTW, it isn't necessary to use a JScrollPane or a Box. The example code is just to help explain what I am trying to do.
Example code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestScrollPane extends JFrame {
JScrollPane scrollPane;
Box box;
private static int panelCount = 0;
public TestScrollPane() {
setPreferredSize(new Dimension(200, 400));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(15);
box = Box.createVerticalBox();
scrollPane.getViewport().add(box);
this.add(scrollPane);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
Timer t = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
box.add(new TestPanel(), 0);
scrollPane.validate();
}
});
t.setRepeats(true);
t.start();
}
public class TestPanel extends JPanel {
int myId = panelCount++;
public TestPanel() {
this.setLayout(new GridBagLayout());
this.setBorder(BorderFactory.createBevelBorder(1));
JLabel label = new JLabel("" + myId);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
this.setMaximumSize(new Dimension(100, 100));
this.setPreferredSize(new Dimension(100, 100));
this.add(label);
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TestScrollPane testScrollPane = new TestScrollPane();
}
});
}
}
EDIT:
This is how I ended up changing the code. I feel somewhat foolish for not seeing the obvious. Anyways, thanx to those that helped.
public void actionPerformed(ActionEvent ae) {
Point view = scrollPane.getViewport().getViewPosition();
TestPanel panel = new TestPanel();
box.add(panel, 0);
scrollPane.validate();
if (view.y != 0) {
view.y += panel.getHeight();
scrollPane.getViewport().setViewPosition(view);
}
}
BTW, I had cross posted this question to http://www.coderanch.com/t/528829/GUI/java/JScrollPane-adding-JPanels-at-top#2398276 Just FYI for those that might care.
You could get the bounds of the component you want to make visible (using JComponent's getBounds method), and use that as an input to JViewPort's scrollRectToVisible method.
Something like:
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
TestPanel panel = new TestPanel();
box.add(panel, 0);
JViewport vp = scrollPane.getViewport();
Point p = vp.getViewPosition();
p.y += panel.getPreferredSize().height;
scrollPane.revalidate();
vp.setViewPosition(p);
}
});