Update JFrame contents - java

How can I update the contents of a JFrame at a button click. I am building a image viewer where a list of photopath will be passed in and the user will have to click on the next or previous button to go back and forth and see the images. How can change the images and update the Jframe Below is my current implementation. I tried to dispose of the current frame and make a new one but that is not what I am looking for...
package cs213.photoAlbum.simpleview;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import model.photoNode;
public class ImageViewer {
private JFrame frame = new JFrame("Image Viewer");
private Container pane = frame.getContentPane();
private JPanel imgViewPanel = new JPanel();
JSlider slider = new JSlider(0, 100, 100);
JLabel percent = new JLabel("100%");
String imageFile = "";
private class ImageView extends JScrollPane {
JPanel panel = new JPanel();
Dimension originalSize = new Dimension();
Image originalImage;
JLabel iconLabel;
public ImageView(ImageIcon icon) {
this.originalImage = icon.getImage();
panel.setLayout(new BorderLayout());
iconLabel = new JLabel(icon);
panel.add(iconLabel);
setViewportView(panel);
originalSize.width = icon.getIconWidth();
originalSize.height = icon.getIconHeight();
}
public void update() {
int min = slider.getMinimum();
int max = slider.getMaximum();
int span = max - min;
int value = slider.getValue();
double multiplier = (double) value / span;
multiplier = multiplier == 0.0 ? 0.01 : multiplier;
Image scaled = originalImage.getScaledInstance((int) (originalSize.width * multiplier), (int) (originalSize.height * multiplier), Image.SCALE_FAST);
iconLabel.setIcon(new ImageIcon(scaled));
}
}
ImageView imageView;
public ImageViewer(String imgFile, final ArrayList<photoNode> list) {
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
});
createAndShowGUI();
imageFile = imgFile;
ImageIcon icon = new ImageIcon(imageFile);
imageView = new ImageView(icon);
JPanel panel = new JPanel();
panel.add(new JLabel("Set Image Size: "));
panel.add(slider);
panel.add(percent);
pane.add(panel, BorderLayout.NORTH);
imgViewPanel.add(imageView);
pane.add(imgViewPanel, BorderLayout.CENTER);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (!slider.getValueIsAdjusting()) {
percent.setText(slider.getValue() + "%");
imageView.update();
}
}
});
JButton next = new JButton("Next");
JButton prev = new JButton("Prev");
pane.add(next, BorderLayout.EAST);
pane.add(prev, BorderLayout.WEST);
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
imgViewPanel.remove(imageView);
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).fileName.equalsIgnoreCase(imageFile)) {
if (i + 1 < list.size()) {
//frame.dispose();
ImageIcon icon = new ImageIcon(list.get(i + 1).fileName);
ImageView imageView = new ImageView(icon);
imgViewPanel.add(imageView);
pane.add(imgViewPanel, BorderLayout.CENTER);
imgViewPanel.revalidate();
break;
}
}
}
}
}
});
}
private void createAndShowGUI() { // Creating the GUI...
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setTitle("PhotoAlbum55");
frame.pack();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setVisible(true);
}
}

The easiest way to swap images is to display them as ImageIcons in a JLabel and simply call setIcon(...) on the JLabel passing in another ImageIcon. If the images are small enough, you could create a collection of icons, perhaps a List<Icon>, and then move backwards or forwards through the list on next or previous button press.

Related

How to wait until JDialog is fully created

I need to calculate window decorations somehow. So I override JDialog's constructor. But when I call get_decoration_size() it sometimes returns wrong values. And my thought was: window creates later than get_decoration_size() executes(strange, because both in same thread and in same constructor). So I decided to sleep for a second, and it worked, and now decorations always valid.
My question is: is there a way to "join" to the creating process(wait until window is shown by setVisible(true))? If so, it must be something to replace unsafe_sleep(1000).
package swing.window;
import db.db;
import javax.swing.*;
import java.awt.*;
import static swing.util.*;
import static util.util.unsafe_sleep;
public class calc_decor extends JDialog {
{
//some initializations
setLayout(null);
setResizable(false);
JLabel label = new JLabel("Loading...");
add(label);
setxy(label, 3, 3);
fit(label);
setsize(this, label.getWidth() + 100, label.getHeight() + 100);
window_to_center(this);
setVisible(true);//trying to draw
unsafe_sleep(1000);//without that it looks like get_decoratoin_size()
//is called before setVisible(true)
db.sysdecor = get_decoration_size();//trying to get decorations
dispose();
}
private Dimension get_decoration_size() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
I had to assume a lot to create a runnable example.
Here's the result of your getDecorationSize method. The line didn't print until I closed the JDialog.
java.awt.Dimension[width=16,height=39]
And here's the code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTest());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
150, 100, 150, 100));
panel.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new CalculateDecor(frame, "Spash Screen");
}
}
public class CalculateDecor extends JDialog {
private static final long serialVersionUID = 1L;
public CalculateDecor(JFrame frame, String title) {
super(frame, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 200));
JLabel label = new JLabel("Loading...");
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label);
add(panel);
pack();
setLocationRelativeTo(frame);
setVisible(true);
System.out.println(getDecorationSize());
}
private Dimension getDecorationSize() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
}

The JButton does not fill the entire JPanel

I am trying to make minesweeper. When I click on the JButton I want the button to hide. I have accomplished this but the button does not cover the entire JPanel. It always leaves some of the panel on the top visible.
I have tried setting the preferred size, vertical and horizontal alignment.
Why is it doing this? How can I fix it?
class canvas extends JFrame {
public static JPanel[] panels;
public static Tile[] tiles;
canvas(int size){
JFrame theGUI = new JFrame();
panels = new JPanel[size*size]; //creates panels and tiles, the tiles contain color, if it is
a bomb ect.
tiles = new Tile[size*size];
Container con = theGUI.getContentPane();
Graphics g;
for(int i = 0; i < panels.length; i++) {
JPanel temp = new JPanel();
temp.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));//adds borders
temp.setBorder(BorderFactory.createLineBorder(Color.black,1));
JButton button = new JButton();
button.setBackground(Color.GRAY);
button.setAlignmentY(0.0f);//tried to see if vertical align would fix it, it didnt
button.setPreferredSize(new Dimension(70,70));
button.addActionListener(new Action() {
public void actionPerformed(ActionEvent event) {
button.setVisible(false);
}
});
temp.add(button);
Tile tempTile = new Tile();
panels[i] = temp;
tiles[i] = tempTile;
tiles[i].color = Color.green;
panels[i].setBackground(tiles[i].color);
con.add(panels[i]);
}
con.setLayout(new GridLayout(size,size));
theGUI.setTitle("mine sweeper");
theGUI.setSize(size*40, size*40);
theGUI.setVisible(true);
}
}
The problem I am trying to fix:
I think you can achieve your goal with simpler code. You just need to add the JButtons directly to a JPanel that uses GridLayout as its layout manager. Consider the following code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class MineSweeper implements ActionListener, Runnable {
private JFrame frame;
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
if (obj instanceof JButton) {
JButton button = (JButton) obj;
button.setVisible(false);
}
}
public void run() {
showGui();
}
private JButton createButton() {
JButton button = new JButton();
button.setPreferredSize(new Dimension(40, 40));
button.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
button.addActionListener(this);
return button;
}
private JPanel createMineField() {
JPanel mineField = new JPanel(new GridLayout(10, 10));
mineField.setBackground(Color.GREEN);
for (int i = 0; i < 100; i++) {
mineField.add(createButton());
}
return mineField;
}
private void showGui() {
frame = new JFrame("Mine Sweeper");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createMineField(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
/**
* Start here.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new MineSweeper());
}
}

How do I swap icons on buttons arranged in GridLayout using Drag and Drop?

I'm trying to create a jigsaw puzzle of sorts, where I have loaded an image onto a 5x5 grid, cropped the image and assigned each cropped part as an icon to 25 buttons arranged in the same pattern. I want to be able to drag my mouse pointer from a button to another and swap the icons on those 2 buttons.
I've tried using multiple MouseListener methods and MouseMotionListener methods, but nothing has worked so far.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.Component;
import javax.swing.*;
//import java.awt.image.*;
public class ImageMove {
JFrame jf;
JButton[][] grid;
JLabel test;
public static void main(String[] args) {
ImageMove ob = new ImageMove();
ob.start();
}
public void start() {
jf = new JFrame();
JPanel gridPanel = new JPanel();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("download.jpg");
Image temp1= img.getImage();
img=new ImageIcon(temp1.getScaledInstance(500, 500, Image.SCALE_SMOOTH));
Image img1 = img.getImage();
gridPanel.setLayout(new GridLayout (5,5));
grid = new JButton[5][5];
for(int y=0;y<5;y++) {
for(int x=0; x<5; x++) {
Image image = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(img1.getSource(), new CropImageFilter(x * 500 / 5, y * 500 / 5, 100, 100)));
ImageIcon icon = new ImageIcon(image);
JButton temp = new JButton(icon);
temp.setTransferHandler(new TransferHandler("icon"));
temp.addMouseMotionListener(new DragMouseAdapter());
grid[x][y]=temp;
gridPanel.add(grid[x][y]);
}
}
test= new JLabel();
jf.getContentPane().add(BorderLayout.NORTH, test);
jf.add(gridPanel);
jf.pack();
jf.setSize(500, 500);
jf.setVisible(true);
}
class DragMouseAdapter extends MouseAdapter{
private int x, y;
public void mouseDragged(MouseEvent e) {
final int x0=MouseInfo.getPointerInfo().getLocation().x;
final int y0=MouseInfo.getPointerInfo().getLocation().y;
x=x0;
y=y0;
JButton c = (JButton) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
public void mouseReleased(MouseEvent e) {
JButton c = (JButton) e.getSource();
Icon icon = c.getIcon();
grid[((int)(x/100))][((int)(y/100))].setIcon(icon);
}
}
}
Currently, the program copies the icon from the first button to the second button, i.e. it replaces the second button's icon with the first, but the first button remains the same. I expect to swap those two icons entirely. The MouseDragged method towards the end is performing the described behavior, but the MouseReleased doesn't seem to do anything at all.
Any help is much appreciated.
It's very easy. You simply need to save somewhere the drag source button, and on drop replace its icon with the old icon of drop target button.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
//import java.awt.image.*;
public class ImageMove {
JFrame jf;
JButton[][] grid;
JLabel test;
JButton dragSource; // here we save drag source component
public static void main(String[] args) {
ImageMove ob = new ImageMove();
ob.start();
}
public void start() {
jf = new JFrame();
JPanel gridPanel = new JPanel();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("download.jpg");
Image temp1 = img.getImage();
img = new ImageIcon(temp1.getScaledInstance(500, 500, Image.SCALE_SMOOTH));
Image img1 = img.getImage();
gridPanel.setLayout(new GridLayout(5, 5));
grid = new JButton[5][5];
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 5; x++) {
Image image = Toolkit.getDefaultToolkit()
.createImage(new FilteredImageSource(img1.getSource(), new CropImageFilter(x * 500 / 5, y * 500 / 5, 100, 100)));
ImageIcon icon = new ImageIcon(image);
JButton temp = new JButton(icon);
// use own extension of TransferHandler
temp.setTransferHandler(new MyTransferHandler("icon"));
// start drag on mouse pressed event.
temp.addMouseListener(new DragMouseAdapter());
grid[x][y] = temp;
gridPanel.add(grid[x][y]);
}
}
test = new JLabel();
jf.getContentPane().add(BorderLayout.NORTH, test);
jf.add(gridPanel);
jf.pack();
jf.setSize(500, 500);
jf.setVisible(true);
}
class DragMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JButton c = (JButton) e.getSource();
dragSource = c;
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
}
private class MyTransferHandler extends TransferHandler {
public MyTransferHandler(String property) {
super(property);
}
#Override
public boolean importData(JComponent comp, Transferable t) {
Icon targetIcon = ((JButton) comp).getIcon();
boolean result = super.importData(comp, t);
if (dragSource != null) {
dragSource.setIcon(targetIcon);
dragSource = null;
}
return result;
}
}
}

Placing the JPanel in JScrollPane [duplicate]

I've got a probelm with my swing ui lately. Everything works fine,untill i trigger a tooltip from a JButton.After that moving the mouse over the rest of the ui is causing weird artifacts and glitching.
Bugged:
I can't show the whole code because its too much but here im initialising the button :
GridBagConstraints bottompane_gbc = new GridBagConstraints();
toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
toggleTorConnectionButton.setIcon(new ImageIcon(ResourceHandler.Menueicon3_1));
toggleTorConnectionButton.setMinimumSize(new Dimension(removeFinishedDownloads.getMinimumSize().width, toggleTorConnectionButton.getIcon().getIconHeight()+5));
toggleTorConnectionButton.addActionListener(); // unimportant
bottompane_gbc.gridy = 1;
bottompane_gbc.fill = GridBagConstraints.BOTH;
bottompane_gbc.insets = new Insets(0,15,10,5);
bottompane.add(ToggleTorConnectionButton,bottompane_gbc);
this.add(bottompane,BorderLayout.PAGE_END);
If anybody needs more information to help me pls feel free to ask.Im kind of desperated. XD
EDIT:
After some tinkering im guessing that the problem is related to swing and my use of it.Currently im using alot of Eventlisteners (is this bad?), that might slow down the awt thread ?
Here is a brief extract from HPROF:
http://www.pastebucket.com/96444
EDIT 2:
I was able to recreate the error in a handy and simple example. When you move over the button,wait for the tooltip and then over the ui.You will see ghosting :(.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
new Main_frame();
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setFocusable(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
frame.setLocationRelativeTo(null);
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel();
Dimension dim = new Dimension(370, 60);
pane.setPreferredSize(dim);
pane.setMaximumSize(dim);
pane.setBackground(Color.blue);
pane.setMinimumSize(dim);
download_window.jobpanel.add(pane);
}
download_window.jobpanel.repaint();
download_window.jobpanel.revalidate();
frame.add(tabbedPane);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
JPanel bottompane = new JPanel();
bottompane.setPreferredSize(new Dimension(385, 40));
JButton toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setPreferredSize(new Dimension(100, 50));
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Edit 3: Concerning trashgods ideas, I used the EventDispatchThread, I modified the setter to override the getter for size and i crossed out incompatibility by using trashgods code and it was working fine.... So where is the actual difference?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Main_frame();
}
});
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
frame.add(tabbedPane);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMinimumSize() {
return new Dimension(370, 60);
}
};
pane.setBackground(Color.blue);
jobpanel.add(pane);
}
JPanel bottompane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(385, 40);
}
};
JButton toggleTorConnectionButton = new JButton("Button"){
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 30);
}
};
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Could anyone please verify that strange behavior himself? You just need to copy&paste the code from above in Edit3.
Your code exhibits none of the glitches shown above when run on my platform.
Verify that you have no painting problems e.g. neglecting super.paintComponent() as discussed here.
Verify that you have no driver incompatibilities, as discussed here.
Construct and modify all GUI objects on the event dispatch thread.
Don't use set[Preferred|Maximum|Minimum]Size() when you really mean to override get[Preferred|Maximum|Minimum]Size(), as discussed here. The example below overrides getPreferredSize() on the scroll pane, but you can implement Scrollable, as discussed here.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
/** #see https://stackoverflow.com/a/34319260/230513 */
public class MainFrame {
private static final int H = 64;
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MainFrame());
}
public MainFrame() {
JFrame frame = new JFrame("LOL");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
for (int i = 0; i < 8; i++) {
panel.add(new DownloadPanel());
}
JScrollPane jsp = new JScrollPane(panel) {
#Override
public Dimension getPreferredSize() {
return new Dimension(6 * H, 4 * H);
}
};
tabbedPane.addTab("Download", null, jsp, "Main Download Window.");
tabbedPane.addTab("Options", null, null, "Options");
frame.add(tabbedPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class DownloadPanel extends JPanel {
JPanel jobPanel = new JPanel();
public DownloadPanel() {
this.setLayout(new BorderLayout());
this.setBackground(Color.lightGray);
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(true);
this.add(jpb);
JPanel buttonPane = new JPanel();
JButton toggleTorConnectionButton = new JButton("Button");
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
buttonPane.add(toggleTorConnectionButton);
this.add(buttonPane, BorderLayout.WEST);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(4 * H, H);
}
}
}

GridBagLayout Java

Hi again i've put in my original code just to let you see what i was talking about for the GridBagConstrainsts thats i was trying to put each image to be stuck to the south of the panel immediately next to each other
package prototype;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
//Declare the class which extends JFrame and
//implements ActionListener to enable bottons to respond whenever clicked or selected
public class Master extends JFrame implements ActionListener {
//create the bottons visible by the user
JButton check = new JButton("");
JButton playList = new JButton("");
JButton update = new JButton("");
JButton quit = new JButton("");
JCheckBox tick = new JCheckBox("Tick");
JPanel top = new JPanel();
public static void main(String[] args) {
//declare object of the class
Master jf = new Master();
}
public Master() {
setLayout(new BorderLayout());
setSize(1050, 400);
setTitle("Master");
// close application only by clicking the quit button
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//show the frame in the middle of the screen when run
setLocationRelativeTo(null);
top.add(new JLabel("Select an option by clicking one of the buttons below"));
add("North", top); // add the text above to the upper part of the frame (North)
JPanel bottom = new JPanel();
bottom.setLayout(new GridBagLayout());
bottom.add(check);
check.addActionListener(this);
bottom.add(playList);
playList.addActionListener(this);
bottom.add(update);
update.addActionListener(this);
bottom.add(quit);
quit.addActionListener(this);
add("South", bottom);
//make the frame non resizable but visible
setResizable(true);
setVisible(true);
try{
Image img = ImageIO.read(getClass().getResource("gui/Exit.png"));
Image resize = img.getScaledInstance(290, 180, 18);
quit.setIcon(new ImageIcon(resize));
img = (bottom, new JLabel("NAME"), 0,0,1,1, GridBagConstraints.SOUTH);
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/Untitled.png"));
Image resize = img.getScaledInstance(290, 180, 18);
check.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/CPL.png"));
Image resize = img.getScaledInstance(290, 180, 18);
playList.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
try{
Image img = ImageIO.read(getClass().getResource("gui/UpdateLib.png"));
Image resize = img.getScaledInstance(290, 180, 18);
update.setIcon(new ImageIcon(resize));
}catch(Exception e){
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == check) {
new CheckLibrary();
} else if (e.getSource() == update) {
new UpdateLibrary();
} else if (e.getSource() == quit) {
System.exit(0);
} else if (e.getSource() == playList) {
new CreatePlaylist();
}
}
}
For that purposes you need to use anchor and weighty properties of GridBagConstraints.
In next example I set JTextField to the south:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Example extends JFrame {
public Example (){
JTextField f = new JTextField(20);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.SOUTHEAST;
c.weighty = 1;
add(f,c);
}
public static void main(String...strings ){
Example e = new Example();
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.pack();
e.setLocationRelativeTo(null);
e.setVisible(true);
}
}
If you need to fill all horizontal space by component add next :
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
For Image you can use JLabel instead of JTextField in my example :
JLabel l = new JLabel(new ImageIcon(getClass().getResource(PATH_TO_IMAGE)));
You cannot add an image directly to a JPanel. What you can do instead is to set the image to be the image icon of a JPanel or JLabel and add that to whatever you're trying to make.

Categories