I want to have a JFrame, where on the left and the right there is a border that has the color black and a width of withfOfJFrame/10.
Now, my try at it looks like this:
JFrame f = new JFrame();
f.setSize(800, 600);
f.setLayout(new BorderLayout());
JPanel leftBorder = new JPanel();
JPanel rightBorder = new JPanel();
leftBorder.setBackground(Color.black);
rightBorder.setBackground(Color.black);
leftBorder.setSize(f.getWidth()/10, f.getHeight());
rightBorder.setSize(f.getWidth()/10, f.getHeight());
JPanel center = new JPanel();
center.setBackground(Color.red);
f.add(leftBorder, BorderLayout.WEST);
f.add(center, BorderLayout.CENTER);
f.add(rightBorder, BorderLayout.EAST);
f.setVisible(true);
This adds a black border on the left and the right, but that border has a fixed size and doesn't recalculate when resizing the window. The size isn't even 1/10 of 800 (the beginning width of the JFrame).
What am I doing wrong? Or is there even a better way to do this?
You may achieve the desired result with a GridBagLayout and appropriate weights:
public class Snippet {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel leftBorder = new JPanel();
JPanel rightBorder = new JPanel();
leftBorder.setBackground(Color.black);
rightBorder.setBackground(Color.black);
JPanel center = new JPanel();
center.setBackground(Color.red);
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1.0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.weightx = 0.1;
f.add(leftBorder, gbc);
gbc.gridx = 1;
gbc.weightx = 0.8;
f.add(center, gbc);
gbc.gridx = 2;
gbc.weightx = 0.1;
f.add(rightBorder, gbc);
f.pack();
f.setVisible(true);
}
});
}
}
A ComponentListener works well for this.
Addendum: The Flank panel needs to revalidate() itself explicitly in response to any size change.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/a/14588506/230513 */
public class Test {
private static final int W = 320;
private static final Center center = new Center();
private static class Center extends JPanel {
public Center() {
setBackground(Color.red);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, 3 * W / 4);
}
};
private static class Flank extends JPanel {
private Dimension d = new Dimension(W / 10, 0);
public Flank() {
setBackground(Color.black);
Test.center.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
d = new Dimension(e.getComponent().getWidth() / 10, 0);
revalidate();
}
});
}
#Override
public Dimension getPreferredSize() {
return d;
}
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Flank(), BorderLayout.WEST);
f.add(center, BorderLayout.CENTER);
f.add(new Flank(), BorderLayout.EAST);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
Related
I want to place some elements inside a JFrame by setLocation(x, y) but my frame is not the size I expect.
The size of my JFrame is 600 x 400 but when I run the app it looks like a JFrame of about 550 x 350.
I would like to understand why this happens, even if there are better ways to implement it.
Thanks in advance for any assistance.
My code:
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Example");
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(600, 400);
mainFrame.setLayout(null);
mainFrame.setResizable(false);
JPanel p1 = new JPanel();
p1.setSize(100, 100);
p1.setLocation(0,0);
p1.setBackground(Color.BLUE);
mainFrame.add(p1);
JPanel p2 = new JPanel();
p2.setSize(100, 100);
p2.setLocation(500,300);
p2.setBackground(Color.BLUE);
mainFrame.add(p2);
}
Output:
A frame's visible content size is the frame size minus the frame's decorations insets.
So your viewable area will be 600x400 - frameDecorationInsets, and this will be variable (even across the same platform).
Instead, you should be looking at the size of the parent container, for example
Note, I'm running on MacOS, which has a different frame decoration then Windows, but this concept will still work on both ... and you get resizability
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel p1 = new JPanel();
private JPanel p2 = new JPanel();
public TestPane() {
setLayout(null);
p1.setBackground(Color.BLUE);
add(p1);
p2.setBackground(Color.BLUE);
add(p2);
}
#Override
public void doLayout() {
super.doLayout();
p1.setSize(100, 100);
p1.setLocation(0, 0);
p2.setSize(100, 100);
p2.setLocation(getWidth() - p2.getWidth(), getHeight() - p2.getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
}
}
But...
Arguably, you shouldn't be using null layouts, you should be relying on things like JComponent#getPreferredSize and JFrame#pack to provide suitable hints about how best you want the window to be sized by default, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JPanel p1 = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
p1.setBackground(Color.BLUE);
JPanel p2 = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
p2.setBackground(Color.BLUE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(p1, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.SOUTHEAST;
add(p2, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
}
}
I have simple GUI that is supposed to show some informations. I created menu of multiple JTabbedPanes and the tabs are stacking on each other as intended. I am trying to remove borders on left, right and bottom sides of each tab so it doesn't look stacked. I haven't found anything that would solve my problem, is there actually a way to do it?
Thank you for answer in advance.
Here is screen shot:
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import javax.swing.*;
public class Convertor implements ItemListener {
public void addComponentToPane(Container pane) throws FileNotFoundException {
//main panel containing all below
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//Menu panel
JPanel menuPanel = new JPanel();
menuPanel.setMinimumSize(new Dimension(1200, 30));
menuPanel.setMaximumSize(new Dimension(1200, 30));
menuPanel.setPreferredSize(new Dimension(1200, 30));
menuPanel.setBackground(Color.BLUE);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
mainPanel.add(menuPanel, gbc);
//Menu panel buttons
JButton importButton = new JButton("Import");
importButton.setPreferredSize(new Dimension(75, 20));
menuPanel.add(importButton, BorderLayout.EAST);
JButton button2 = new JButton("XXX");
button2.setPreferredSize(new Dimension(75, 20));
menuPanel.add(button2, BorderLayout.EAST);
//PAYER PANEL CONTAINER - containing payer panel
JPanel payerPanelContainer = new JPanel(new BorderLayout());
//payerPanelContainer.setBackground(Color.RED);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0;
gbc.weighty = 1;
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx = 0;
gbc.gridy = 1;
mainPanel.add(payerPanelContainer, gbc);
//PAYER PANEL
JPanel payerPanel = new JPanel(new GridBagLayout());
payerPanel.setBackground(Color.YELLOW);
payerPanelContainer.add(payerPanel);
//PAYER PANEL TABBED PANE
JTabbedPane payerTabbedPane = new JTabbedPane();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
payerPanel.add(payerTabbedPane, gbc);
//Create payer tabs
JPanel payerTab1 = new JPanel(new BorderLayout());
payerTabbedPane.addTab("Payer 1", payerTab1);
JPanel payerTab2 = new JPanel(new BorderLayout());
payerTabbedPane.addTab("Payer 2", payerTab2);
//create MSISDN tabbed pane in each payer tab
JTabbedPane msisdnTabbedPane1 = new JTabbedPane();
payerTab1.add(msisdnTabbedPane1);
//create MSISDN tabs
JPanel generalTabPayer1 = new JPanel(new BorderLayout());
msisdnTabbedPane1.addTab("GENERAL", generalTabPayer1);
JPanel msisdnTab1 = new JPanel(new BorderLayout());
msisdnTabbedPane1.addTab("MSISDN 1", msisdnTab1);
JPanel msisdnTab2 = new JPanel(new BorderLayout());
msisdnTabbedPane1.addTab("MSISDN 2", msisdnTab2);
JPanel msisdnTab3 = new JPanel(new BorderLayout());
msisdnTabbedPane1.addTab("MSISDN 2", msisdnTab3);
//create MSISDN options tabbed pane
JTabbedPane msisdnOptionsTabbedPane1 = new JTabbedPane();
msisdnTab1.add(msisdnOptionsTabbedPane1);
//create MSISDN options tabs
JPanel msisdnOptionsTab1 = new JPanel(new BorderLayout());
msisdnOptionsTabbedPane1.addTab("Option 1", msisdnOptionsTab1);
JPanel msisdnOptionsTab2 = new JPanel(new BorderLayout());
msisdnOptionsTabbedPane1.addTab("Option 2", msisdnOptionsTab2);
//add main panel to window
pane.add(mainPanel);
}
private static void createAndShowGUI() throws FileNotFoundException {
//Create and set up the window.
JFrame frame = new JFrame("CSV Reader");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Convertor demo = new Convertor();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setSize(1206, 800);
frame.setMinimumSize(new Dimension(1206, 800));
frame.setMaximumSize(new Dimension(1206, 800));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub
}
}
It's possible, but it's hard. The only way to do it is to provide your own UI for the tabbed pane. Here is the example, which is not completly satisfied your requirements, but it can show the way, which you must go (sorry, but I cann't provide a complete solution, because it could be time expansive).
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.MetalTabbedPaneUI;
public class BorderlessTabsExample implements Runnable {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(MetalLookAndFeel.class.getName());
} catch (Exception e) {
// Nothing
}
SwingUtilities.invokeLater(new BorderlessTabsExample());
}
#Override
public void run() {
JTabbedPane tabber = new JTabbedPane();
tabber.addTab("First", new JLabel("First"));
tabber.addTab("Second", new JLabel("Second"));
tabber.addTab("Third", new JLabel("Third"));
// set the UI which will paint your tabs
tabber.setUI(new MetalBorderlessTabbedPaneUI());
JFrame frm = new JFrame("Tabber test");
frm.add(tabber);
frm.setSize(500, 400);
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
private static class MetalBorderlessTabbedPaneUI extends MetalTabbedPaneUI {
#Override
protected void installDefaults() {
super.installDefaults();
if (contentBorderInsets != null) {
contentBorderInsets = new Insets(contentBorderInsets.top, 0, 0, 0);
}
}
#Override
protected void paintContentBorderRightEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) {
// Do nothing
}
#Override
protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) {
// Do nothing
}
#Override
protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) {
// Do nothing
}
}
}
I am building a toolbar for a program using GridBagLayout, but even using weightx and fill, the components are not the sizes they should be and they are not filling the JPanel.
For instance, when the total size of jidest.x_size is 1920, the total size of the components is 1776
package jide.parts;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import jide.jidest;
#SuppressWarnings("serial")
public class BottomBar extends JPanel implements MouseListener{
JPanel charCountPanel = new JPanel();
JPanel lineCountPanel = new JPanel();
JPanel cursorPositionPanel = new JPanel();
JPanel spacer1 = new JPanel();
JPanel spacer2 = new JPanel();
JPanel spacer3 = new JPanel();
JPanel morespace = new JPanel();
JLabel charCount = new JLabel("charcount");
JLabel lineCount = new JLabel("linecount");
JLabel cursorPosition = new JLabel("TEST:TEST");
public BottomBar(){
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
charCountPanel.setToolTipText("Click here for more complete stats");
lineCountPanel.setToolTipText("Click here for more complete stats");
setPreferredSize(new Dimension((int) jidest.x_size,20));
setBackground(Color.red);
cursorPositionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
cursorPositionPanel.add(cursorPosition);
//cursorPositionPanel.setSize(50,20);
lineCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
lineCountPanel.add(lineCount);
//lineCountPanel.setSize(50,20);
charCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
charCountPanel.add(charCount);
//charCountPanel.setSize(50,20);
morespace.setSize((int) (jidest.x_size-156),20);
//add(cursorPositionPanel);
spacer1.setBackground(Color.BLACK);
//spacer1.setSize(1,20);
spacer2.setBackground(Color.BLACK);
//spacer2.setSize(1,20);
spacer3.setBackground(Color.BLACK);
//spacer3.setPreferredSize(new Dimension(1,20));
//size is 156, width is 7
gbc.fill=GridBagConstraints.BOTH;
gbc.weighty=1;
gbc.gridx = 1;
gbc.weightx=(1.0)/jidest.x_size;
add(spacer1,gbc);
gbc.gridx=2;
gbc.weightx=(50.0)/jidest.x_size;
add(cursorPositionPanel,gbc);
gbc.gridx=3;
gbc.weightx=(1.0)/jidest.x_size;
add(spacer2,gbc);
gbc.gridx=4;
gbc.weightx=(50.0)/jidest.x_size;
add(lineCountPanel,gbc);
gbc.gridx=5;
gbc.weightx=(1.0)/jidest.x_size;
add(spacer3,gbc);
gbc.gridx=6;
gbc.weightx=(50.0)/jidest.x_size;
add(charCountPanel,gbc);
gbc.gridy = 0;
gbc.gridx=0;
gbc.weightx=(jidest.x_size-153)/jidest.x_size;
add(morespace,gbc);
System.out.println((spacer1.getWidth()+cursorPositionPanel.getWidth()+spacer2.getWidth()+lineCountPanel.getWidth()+spacer3.getWidth()+morespace.getWidth())+" should be " + jidest.x_size);
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
In future, please post an MCVE. This works to spread the components across the width of the bar.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BottomBarGUI {
private JComponent ui = null;
BottomBarGUI() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(new BottomBar());
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BottomBarGUI o = new BottomBarGUI();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
class BottomBar extends JPanel {
JPanel charCountPanel = new JPanel();
JPanel lineCountPanel = new JPanel();
JPanel cursorPositionPanel = new JPanel();
JPanel spacer1 = new JPanel();
JPanel spacer2 = new JPanel();
JPanel spacer3 = new JPanel();
JPanel morespace = new JPanel();
JLabel charCount = new JLabel("charcount");
JLabel lineCount = new JLabel("linecount");
JLabel cursorPosition = new JLabel("TEST:TEST");
public BottomBar() {
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 0;
gbc.weightx = .5;
charCountPanel.setToolTipText("Click here for more complete stats");
lineCountPanel.setToolTipText("Click here for more complete stats");
setBackground(Color.red);
cursorPositionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
cursorPositionPanel.add(cursorPosition);
lineCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
lineCountPanel.add(lineCount);
charCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
charCountPanel.add(charCount);
spacer1.setBackground(Color.BLACK);
spacer2.setBackground(Color.BLACK);
spacer3.setBackground(Color.BLACK);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.gridx = 0;
add(spacer1, gbc);
gbc.gridx = 1;
add(cursorPositionPanel, gbc);
gbc.gridx = 2;
add(spacer2, gbc);
gbc.gridx = 3;
add(lineCountPanel, gbc);
gbc.gridx = 4;
add(spacer3, gbc);
gbc.gridx = 5;
add(charCountPanel, gbc);
gbc.gridx = 0;
}
}
For some reason my borders aren't showing for my panels and i am unsure why, is there something i'm missing?
I have a main class which runs the frame class as well as other classes separate to the GUI
This is the code from my frame class:
import javax.swing.*;
import java.awt.*;
public class Frame
{
public static int xsize;
public static int ysize;
public static void main()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new MainFrame("Warlock of Firetop Mountain");
//Implementing Toolkit to allow computer to get dimensions of screen and assign them to two int values
Toolkit tk = Toolkit.getDefaultToolkit();
Frame.xsize = (int) tk.getScreenSize().getWidth();
Frame.ysize = (int) tk.getScreenSize().getHeight();
frame.setTitle("Warlock of Firetop Mountain");
frame.setSize(new Dimension(xsize, ysize));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
The frame.java takes its panels from MainFrame.java:
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
private Panel1 storyPanel;
private Panel2 statsPanel;
private Panel3 commandsPanel;
public MainFrame(String title)
{
super(title);
// Setting Layout
setLayout(new BorderLayout());
storyPanel = new Panel1();
statsPanel = new Panel2();
commandsPanel = new Panel3();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(statsPanel, BorderLayout.EAST);
p.add(commandsPanel, BorderLayout.SOUTH);
}
}
This calls up my three panels which look like this:
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Dimension;
import java.awt.Color;
public class Panel1 extends JPanel
{
public Panel1()
{
//Set size of Panel1
int xsizeP1 = (Frame.xsize / 2);
int ysizeP1 = (Frame.ysize / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
}
}
when the code runs the window launches as full screen but no borders or possibly panels are visible.
Thanks for any help, sorry if my questions are tedious, i'm relatively new to programming.
This is roughly what i want my panels to look like, eventually ill add in components to the panel and use GridBagConstraints to control the formatting
// this creates the JPanels and sets their preferred sizes
JFrame frame = new MainFrame("Warlock of Firetop Mountain");
//this sets your size static contents -- after the above's been done!
Toolkit tk = Toolkit.getDefaultToolkit();
Frame.xsize = (int) tk.getScreenSize().getWidth();
Frame.ysize = (int) tk.getScreenSize().getHeight();
You're setting preferred sizes of all your JPanels to 0, 0, and so you're not seeing any borders. Your sizing is being created after you've created your JPanels, and this method of sizing looks dangerous to me.
OK, thanks for posting an image of the desired GUI. My recommendations are:
First and foremost, don't try setting sizes as you're doing.
Instead, let the components and their layout managers size themselves.
Nest JPanels, each using its own layout manager to allow you to simply create complex GUI's.
When displaying images / ImageIcons, let them set the sizes of things as well.
If your GUI starts up with no icons displaying, consider creating a blank ImageIcon with a blank image of the right size as a placeholder icon.
For example, something like this:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class TomGuiPanel extends JPanel {
// rows and cols for jtextarea
private static final int CURRENT_AREA_ROWS = 20;
private static final int CURRENT_AREA_COLS = 40;
// columns for command jtextfied
private static final int COMMANDS_FIELD_COLS = 50;
// size of GUI component gaps
private static final int EB_GAP = 3;
private static final int NUMBER_OF_OPTIONS = 5;
// number if ImageIcons displayed within the user image char JList
private static final int CHAR_IMG_VISIBLE_ROWS = 5;
// a guess of the width of the largest image icon in the JList
// You'd use a different number
private static final int USER_IMG_CHAR_IMG_WIDTH = 70;
private JTextArea currentTextArea = new JTextArea(CURRENT_AREA_ROWS, CURRENT_AREA_COLS);
private JTextField commandsField = new JTextField(COMMANDS_FIELD_COLS);
private EnterAction enterAction = new EnterAction("Enter");
private DefaultListModel<Icon> charImgListModel = new DefaultListModel<>();
private JList<Icon> charImgList = new JList<>(charImgListModel);
public TomGuiPanel() {
JPanel topBtnPanel = new JPanel(new GridLayout(1, 0, EB_GAP, EB_GAP));
String[] btnTexts = { "Inventory", "Options", "Save", "Load" };
for (String txt : btnTexts) {
topBtnPanel.add(new JButton(txt));
}
JPanel characteristicsPanel = new JPanel(new GridBagLayout());
addCharacteristics(characteristicsPanel, "HP", 20, 0);
addCharacteristics(characteristicsPanel, "Attack", 12, 1);
addCharacteristics(characteristicsPanel, "Defence", 8, 2);
addCharacteristics(characteristicsPanel, "Agility", 9, 3);
addCharacteristics(characteristicsPanel, "Luck", 2, 4);
JScrollPane imgListPane = new JScrollPane(charImgList);
imgListPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
charImgList.setVisibleRowCount(CHAR_IMG_VISIBLE_ROWS);
charImgList.setPrototypeCellValue(createProtoType());
JPanel rightPanel = new JPanel(new BorderLayout(EB_GAP, EB_GAP));
rightPanel.add(topBtnPanel, BorderLayout.PAGE_START);
rightPanel.add(imgListPane, BorderLayout.CENTER);
rightPanel.add(characteristicsPanel, BorderLayout.LINE_END);
JPanel optionsPanel = new JPanel(new GridLayout(1, 0));
for (int i = 0; i < NUMBER_OF_OPTIONS; i++) {
String text = "Option " + (i + 1);
optionsPanel.add(new JCheckBox(text));
}
currentTextArea.setWrapStyleWord(true);
currentTextArea.setLineWrap(true);
currentTextArea.setFocusable(false);
JScrollPane taScrollPane = new JScrollPane(currentTextArea);
taScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(taScrollPane, BorderLayout.CENTER);
centerPanel.add(rightPanel, BorderLayout.LINE_END);
centerPanel.add(optionsPanel, BorderLayout.PAGE_END);
JPanel commandsPanel = new JPanel();
commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.LINE_AXIS));
commandsPanel.add(commandsField);
commandsPanel.add(Box.createHorizontalStrut(EB_GAP));
commandsPanel.add(new JButton(enterAction));
commandsPanel.add(Box.createHorizontalStrut(EB_GAP));
commandsPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
commandsField.setAction(enterAction); // use same action for button and
// text field
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(new BorderLayout(EB_GAP, EB_GAP));
add(centerPanel, BorderLayout.CENTER);
add(commandsPanel, BorderLayout.PAGE_END);
}
private void addCharacteristics(JPanel cPanel, String text, int value, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = row;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
cPanel.add(new JLabel(text), gbc);
gbc.insets.left = 20;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = 1;
cPanel.add(new JLabel(String.valueOf(value)), gbc);
}
private Icon createProtoType() {
int w = USER_IMG_CHAR_IMG_WIDTH;
int h = w;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Icon icon = new ImageIcon(img);
return icon;
}
private class EnterAction extends AbstractAction {
public EnterAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String text = commandsField.getText();
currentTextArea.append(text + "\n");
commandsField.selectAll();
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component source = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(source);
win.dispose();
}
}
private static void createAndShowGUI() {
TomGuiPanel mainPanel = new TomGuiPanel();
JFrame frame = new JFrame("Tom's GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Would create this realizable GUI:
Note that the GUI is roughly made, has no functionality other than the enter and exit buttons.
I've found myself writing up quite a few programs recently which all need to display some collection of data. So far the best looking approach I've thought of is make small JPanels which contain data on each item in the collection and put them all in a big JPanel which I then put in a JScrollPane. It works and looks just as intended but there's one issue: I can't seem to get the smaller JPanels to start at the top of the bigger JPanel.
The problem is only apparent when I've got a small number of small JPanels (green) added into the bigger JPanel (red).
Described below is the method I used to produce the above and I'd like to know if there's a better way I could do it (where the list starts at the top like it should):
I created a class which extends JPanel and in it add all data I want to display. We'll call it "SmallPanel.java". I don't set the size of it (that comes later).
In my main window's class (which extends JFrame):
private JScrollPane scrollPane;
private JPanel panel;
...
scrollPane = new JScrollPane();
getContentPane().add(scrollPane);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
scrollPane.setViewportView(panel);
...
private void addPanel()
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = panel.getComponentCount(); //The new JPanel's place in the list
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START; //I thought this would do it
gbc.ipady = 130; //Set the panel's height, the width will get set to that of the container JPanel (which is what I want since I'd like my JFrames to be resizable)
gbc.insets = new Insets(2, 0, 2, 0); //Separation between JPanels in the list
gbc.weightx = 1.0;
SmallPanel smallPanel = new SmallPanel();
panel.add(smallPanel, gbc);
panel.revalidate();
panel.invalidate();
panel.repaint(); //Better safe than peeved
}
Call the addPanel() method every time I want to add a panel.
EDIT
Final solution (based on MadProgrammer's answer below):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.BevelBorder;
public class ListPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private JPanel fillerPanel;
private ArrayList<JPanel> panels;
public ListPanel(List<JPanel> panels, int height)
{
this(panels, height, new Insets(2, 0, 2, 0));
}
public ListPanel(List<JPanel> panels, int height, Insets insets)
{
this();
for (JPanel panel : panels)
addPanel(panel, height, insets);
}
public ListPanel()
{
super();
this.fillerPanel = new JPanel();
this.fillerPanel.setMinimumSize(new Dimension(0, 0));
this.panels = new ArrayList<JPanel>();
setLayout(new GridBagLayout());
}
public void addPanel(JPanel p, int height)
{
addPanel(p, height, new Insets(2, 0, 2, 0));
}
public void addPanel(JPanel p, int height, Insets insets)
{
super.remove(fillerPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = getComponentCount();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.ipady = height;
gbc.insets = insets;
gbc.weightx = 1.0;
panels.add(p);
add(p, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = getComponentCount();
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
add(fillerPanel, gbc);
revalidate();
invalidate();
repaint();
}
public void removePanel(JPanel p)
{
removePanel(panels.indexOf(p));
}
public void removePanel(int i)
{
super.remove(i);
panels.remove(i);
revalidate();
invalidate();
repaint();
}
public ArrayList<JPanel> getPanels()
{
return this.panels;
}
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setMinimumSize(new Dimension(500, 500));
f.setLocationRelativeTo(null);
f.getContentPane().setLayout(new BorderLayout());
final ListPanel listPanel = new ListPanel();
for (int i = 1; i <= 10; i++)
listPanel.addPanel(getRandomJPanel(), new Random().nextInt(50) + 50);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent paramActionEvent)
{
listPanel.addPanel(getRandomJPanel(), new Random().nextInt(50) + 50);
}
});
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent paramActionEvent)
{
listPanel.removePanel(0);
}
});
f.getContentPane().add(btnRemove, BorderLayout.NORTH);
f.getContentPane().add(btnAdd, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setViewportView(listPanel);
f.getContentPane().add(scrollPane, BorderLayout.CENTER);
f.setVisible(true);
}
public static JPanel getRandomJPanel()
{
JPanel panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.add(new JLabel("This is a randomly sized JPanel"));
panel.setBackground(new Color(new Random().nextFloat(), new Random().nextFloat(), new Random().nextFloat()));
return panel;
}
}
The best solution I've found is to use VerticalLayout from the SwingLabs SwingX (which can be downloaded from here) libraries.
You "could" use a GridBagLayout with an invisible component positioned at the end, whose weighty property is set to 1, but this is a lot more additional work to manage, as you need to keep updating the x/y positions of all the components to keep it in place...
Updated with GridBagLayout example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class VerticalLayoutExample {
public static void main(String[] args) {
new VerticalLayoutExample();
}
public VerticalLayoutExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final TestPane pane = new TestPane();
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pane.addAnotherPane();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(pane));
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel filler;
private int y = 0;
public TestPane() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
filler = new JPanel();
filler.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.gridy = 0;
add(filler, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
public void addAnotherPane() {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Hello"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = y++;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
add(panel, gbc);
GridBagLayout gbl = ((GridBagLayout)getLayout());
gbc = gbl.getConstraints(filler);
gbc.gridy = y++;
gbl.setConstraints(filler, gbc);
revalidate();
repaint();
}
}
}
This is just a concept. As camickr has pointed out, so long as you know the last component, you can adjust the GridBagConstraints of the component so that the last component which is in the list has the weighty of 1 instead...
As you can, you can override some of the things GridBagLayout does, for example, instead of using the preferred size of the panel, I've asked GridBagLayout to make it fill the HORIZONTAL width of the parent container...
You can use a vertical BoxLayout.
Just make sure the maximum size of the panel is equal to the preferred size so the panel doesn't grow.
Edit:
Since your class already has a custom panel all you need to do is override the getMaximumSize() method to return an appropriate value. Something like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class VerticalLayoutExample2 {
public static void main(String[] args) {
new VerticalLayoutExample2();
}
public VerticalLayoutExample2() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final TestPane pane = new TestPane();
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pane.addAnotherPane();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(pane));
frame.add(add, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel filler;
private int y = 0;
public TestPane() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder( new EmptyBorder(4, 4, 4, 4) );
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
public void addAnotherPane() {
SmallPanel panel = new SmallPanel();
panel.setLayout( new GridBagLayout() );
panel.add(new JLabel("Hello"));
add(panel);
add(Box.createVerticalStrut(4));
revalidate();
repaint();
}
}
static class SmallPanel extends JPanel
{
#Override
public Dimension getMaximumSize()
{
Dimension preferred = super.getPreferredSize();
Dimension maximum = super.getMaximumSize();
maximum.height = preferred.height;
return maximum;
}
}
}
I know you mentioned you don't want to use a lib, but you can also look at Relative Layout. It is only a single class. It can easily mimic a BoxLayout but is easier to use because you don't need to override the getMaximumSize() method or add a Box component to the panel to give the vertical spacing.
You would set it as the layout of your panel as follow:
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setFill( true ); // fills components horizontally
rl.setGap(4); // vertical gap between panels
yourPanel.setLayout(rl);
yourPanel.add( new SmallPanel(...) );
yourPanel.add( new SmallPanel(...) );