I have to create 5 Jlists in succession to make their backgrounds look in different colors. My existing code creates these 5 lists without the colors (the default JList). I understand that I can only customize the inside/border of a jlist and not the margin/padding around it? Or Am I wrong and is there a way to it?
Btw, The space above the list is a Jlabel (not shown in the pic above) and the layout managers in use are GroupLayout and GridBagLayout.
UPDATE
AT, as per your suggestion, here is a comparison to how the lists look like when surrounded by a jpanel. The lists in the back are the ones with the Jpanel surrounded with a minimal empty border of size 1.
The issue with creating a JPanel with preferredsize overridden is that the jlists are in horizontal jpanel and above them is another jpanel with labels. So, wrapping jlist in a jpanel is not going to do it.
Please do have a look at this code example. Is it closer to what you wanted, else you define the changes that needs to be done. I be on them as soon as I get the reply from your side :-)
Here is the outcome :
import java.awt.*;
import javax.swing.*;
public class JListExample
{
private JList<String> list1;
private JList<String> list2;
private JList<String> list3;
private JList<String> list4;
private JList<String> list5;
private CustomPanel panel1;
private CustomPanel panel2;
private CustomPanel panel3;
private CustomPanel panel4;
private CustomPanel panel5;
private String[] data = {"one", "two", "three", "four"};
private int width = 110;
private int height = 300;
private void displayGUI()
{
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5, 2, 2));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
panel1 = new CustomPanel(width, height, Color.GRAY, "List 1");
list1 = new JList<String>(data);
panel1.add(list1, gbc);
panel2 = new CustomPanel(width, height,
Color.GREEN.brighter().brighter(), "List 2");
list2 = new JList<String>(data);
panel2.add(list2, gbc);
panel3 = new CustomPanel(width, height,
Color.ORANGE.brighter(), "List 3");
list3 = new JList<String>(data);
panel3.add(list3, gbc);
panel4 = new CustomPanel(width, height,
Color.BLUE.brighter(), "List 4");
list4 = new JList<String>(data);
panel4.add(list4, gbc);
panel5 = new CustomPanel(width, height, Color.RED, "List 5");
list5 = new JList<String>(data);
panel5.add(list5, gbc);
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
contentPane.add(panel4);
contentPane.add(panel5);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JListExample().displayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
private final int GAP = 5;
private int width;
private int height;
private Color backgroundColour;
private JLabel titleLabel;
public CustomPanel(int w, int h, Color c, String title)
{
width = w;
height = h;
backgroundColour = c;
titleLabel = new JLabel(title, JLabel.CENTER);
setBackground(backgroundColour);
setBorder(
BorderFactory.createEmptyBorder(
GAP, GAP, GAP, GAP));
setLayout(new GridBagLayout());
titleLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
add(titleLabel, gbc);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(width, height));
}
}
**LATEST EDIT : **
As rightly pointed by #kleopatra (not something that is new for me :-)), too good judgement call. Done the edit related to that below :
import java.awt.*;
import javax.swing.*;
public class JListExample
{
private final int GAP = 5;
private JList<String> list1;
private JList<String> list2;
private JList<String> list3;
private JList<String> list4;
private JList<String> list5;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JPanel panel4;
private JPanel panel5;
private String[] data = {"one", "two", "three", "four"};
private int width = 110;
private int height = 300;
private GridBagConstraints gbc = new GridBagConstraints();
private void displayGUI()
{
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5, 2, 2));
panel1 = getPanel(Color.GRAY, "List 1");
list1 = new JList<String>(data);
panel2 = getPanel(Color.GREEN.brighter().brighter(), "List 2");
list2 = new JList<String>(data);
panel3 = getPanel(Color.ORANGE.brighter(), "List 3");
list3 = new JList<String>(data);
panel4 = getPanel(Color.BLUE.brighter(), "List 4");
list4 = new JList<String>(data);
panel5 = getPanel(Color.RED, "List 5");
list5 = new JList<String>(data);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
panel1.add(list1, gbc);
panel2.add(list2, gbc);
panel3.add(list3, gbc);
panel4.add(list4, gbc);
panel5.add(list5, gbc);
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
contentPane.add(panel4);
contentPane.add(panel5);
frame.setContentPane(contentPane);
frame.setSize(610, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getPanel(Color c, String title)
{
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBorder(
BorderFactory.createEmptyBorder(
GAP, GAP, GAP, GAP));
panel.setBackground(c);
panel.setLayout(new GridBagLayout());
JLabel label = new JLabel(title, JLabel.CENTER);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
panel.add(label, gbc);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JListExample().displayGUI();
}
});
}
}
Related
I am trying to create a GUI that runs a guessing game, but have gotten stuck using GridBagLayout. The problem is with the sizing of the JPanel within my JFrame.
I have already written a similar program that works just fine, and do not understand why one works and the other does not.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.*;
public class GuessGame {
private static JTextField inputBox;
GuessGame(){}
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("GuessingGame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(JFrame frame) {
JPanel panel = new JPanel();
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GuessGame guessingGame = new GuessGame();
GridBagConstraints gbc = new GridBagConstraints();
inputBox = new JTextField(10);
inputBox.setEditable(false);
JLabel title = new JLabel("FUN FUN Guessing Game");
JLabel entryBoxLabel = new JLabel("Entry Box: ");
JLabel statsOptions = new JLabel("Statistics Options");
JLabel message = new JLabel("HAVE FUN!!!");
JButton startGame = new JButton("START");
JButton clearDisplay = new JButton("CLEAR");
JButton displayStats = new JButton("STATS");
JCheckBox bestTime = new JCheckBox("Best Time");
JCheckBox bestPlays = new JCheckBox("Best # of Plays");
JCheckBox bestPlayer = new JCheckBox("Best Player");
JTextArea displayArea = new JTextArea(300, 300);
JScrollPane scrollWrap = new JScrollPane(displayArea);
gbc.anchor = GridBagConstraints.ABOVE_BASELINE;
gbc.gridx = 0; gbc.gridy = 0; panel.add(title, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 1; panel.add(startGame, gbc);
gbc.fill = GridBagConstraints.WEST;
gbc.gridx = 1; gbc.gridy = 1; panel.add(entryBoxLabel, gbc);
gbc.fill = GridBagConstraints.LINE_END;
gbc.gridx = 1; gbc.gridy = 1; panel.add(inputBox, gbc);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0; gbc.gridy = 2; panel.add(displayArea, gbc);
gbc.gridx = 1; gbc.gridy = 2; panel.add(scrollWrap, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 3; panel.add(clearDisplay, gbc);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridx = 1; gbc.gridy = 3; panel.add(statsOptions, gbc);
gbc.anchor = GridBagConstraints.SOUTHWEST;
gbc.gridx = 1; gbc.gridy = 3; panel.add(bestTime, gbc);
gbc.anchor = GridBagConstraints.SOUTH;
gbc.gridx = 1; gbc.gridy = 3; panel.add(bestPlays, gbc);
gbc.anchor = GridBagConstraints.SOUTHEAST;
gbc.gridx = 1; gbc.gridy = 3; panel.add(bestPlayer, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 4; panel.add(displayStats, gbc);
gbc.gridx = 1; gbc.gridy = 4; panel.add(message, gbc);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
I was expecting something that looks like this:
!https://imgur.com/20HVSxR
But what I got was this:
!https://imgur.com/AnMJtt7
HALP
Instad of using GridBad, I prefer using BoxLayout. Here is my approach to your problem. This is the closest you can get to the image you posted using Swing.
import java.awt.*;
import javax.swing.*;
public class Test {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
JPanel north = createNorthPanel();
JPanel center = createCenterPanel();
JPanel south = createSouthPanel();
frame.add(north, BorderLayout.NORTH);
frame.add(center, BorderLayout.CENTER);
frame.add(south, BorderLayout.SOUTH);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
private static JPanel createNorthPanel() {
JPanel northPanel = new JPanel();
BoxLayout northPanelLayout = new BoxLayout(northPanel, BoxLayout.Y_AXIS);
northPanel.setLayout(northPanelLayout);
JPanel upperPanel = new JPanel();
JLabel funFunGuessingGameLabel = new JLabel("FUN FUN Guessing Game");
funFunGuessingGameLabel.setFont(funFunGuessingGameLabel.getFont().deriveFont(Font.ITALIC));
upperPanel.add(funFunGuessingGameLabel);
upperPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
JPanel lowerPanel = new JPanel();
BoxLayout lowerPanelLayout = new BoxLayout(lowerPanel, BoxLayout.X_AXIS);
lowerPanel.setLayout(lowerPanelLayout);
JButton startButton = new JButton("START");
startButton.setPreferredSize(new Dimension(175,(int)startButton.getPreferredSize().getHeight()));
JLabel entryBoxLabel = new JLabel("Entry Box: ");
JTextField entryBoxTextField = new JTextField();
lowerPanel.add(startButton);
lowerPanel.add(Box.createHorizontalStrut(10));
lowerPanel.add(entryBoxLabel);
lowerPanel.add(entryBoxTextField);
lowerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
northPanel.add(upperPanel);
northPanel.add(lowerPanel);
return northPanel;
}
private static JPanel createCenterPanel() {
JPanel centerPanel = new JPanel();
BoxLayout centerPanelLayout = new BoxLayout(centerPanel, BoxLayout.Y_AXIS);
centerPanel.setLayout(centerPanelLayout);
JLabel l1 = new JLabel("Guesses and statistics are shown in this display as a scrollable list, e.g.: ");
JLabel l2 = new JLabel("(1,3,5)é(0,0)");
JLabel l3 = new JLabel("(2,4,6)é(0,0)");
JLabel l4 = new JLabel("(7,8,9)é(0,0)");
Box space = Box.createVerticalBox();
centerPanel.add(Box.createHorizontalStrut(10));
centerPanel.add(l1);
centerPanel.add(Box.createVerticalStrut(10));
centerPanel.add(l2);
centerPanel.add(Box.createVerticalStrut(5));
centerPanel.add(l3);
centerPanel.add(Box.createVerticalStrut(5));
centerPanel.add(l4);
centerPanel.add(Box.createVerticalStrut(40));
centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
return centerPanel;
}
private static JPanel createSouthPanel() {
JPanel southPanel = new JPanel();
BoxLayout southPanelLayout = new BoxLayout(southPanel, BoxLayout.Y_AXIS);
southPanel.setLayout(southPanelLayout);
JPanel upperPanel = new JPanel();
BoxLayout upperPanelLayout = new BoxLayout(upperPanel, BoxLayout.X_AXIS);
upperPanel.setLayout(upperPanelLayout);
JPanel clearButtonPanel = new JPanel(new BorderLayout(0, 0));
JButton clearButton = new JButton("CLEAR");
clearButton.setPreferredSize(new Dimension(175, (int) clearButton.getPreferredSize().getHeight()));
clearButtonPanel.add(clearButton);
JPanel innerPanel = new JPanel();
BoxLayout innerPanelLayout = new BoxLayout(innerPanel, BoxLayout.Y_AXIS);
innerPanel.setLayout(innerPanelLayout);
JPanel statisticsOptionsLabelPanel = new JPanel();
JLabel statisticsOptionsLabel = new JLabel("Statistics Options");
statisticsOptionsLabelPanel.add(statisticsOptionsLabel);
JPanel checkBoxPanel = new JPanel();
BoxLayout checkBoxPanelLayout = new BoxLayout(checkBoxPanel, BoxLayout.X_AXIS);
checkBoxPanel.setLayout(checkBoxPanelLayout);
JCheckBox bestTimeCheckBox = new JCheckBox("Best Time");
JCheckBox bestNumOfPlaysCheckBox = new JCheckBox("Best # of plays");
JCheckBox topPlayerCheckBox = new JCheckBox("Top Player");
checkBoxPanel.add(bestTimeCheckBox);
checkBoxPanel.add(bestNumOfPlaysCheckBox);
checkBoxPanel.add(topPlayerCheckBox);
innerPanel.add(statisticsOptionsLabelPanel);
upperPanel.add(Box.createVerticalGlue());
innerPanel.add(checkBoxPanel);
upperPanel.add(clearButtonPanel);
upperPanel.add(Box.createHorizontalStrut(14));
upperPanel.add(innerPanel);
upperPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
JPanel lowerPanel = new JPanel();
BoxLayout lowerPanelLayout = new BoxLayout(lowerPanel, BoxLayout.X_AXIS);
lowerPanel.setLayout(lowerPanelLayout);
JButton statsButton = new JButton("STATS");
statsButton.setPreferredSize(new Dimension(175,(int)statsButton.getPreferredSize().getHeight()));
JLabel haveFunLabel = new JLabel("Have Fun!!!");
lowerPanel.add(statsButton);
lowerPanel.add(Box.createHorizontalGlue());
lowerPanel.add(haveFunLabel);
lowerPanel.add(Box.createHorizontalGlue());
lowerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
southPanel.add(upperPanel);
southPanel.add(lowerPanel);
return southPanel;
}
}
I have two panels. The first one looks like this.
public class BoardPanel extends JPanel
{
public BoardPanel()
{
setLayout(null);
this.setOpaque(false);
Button button = new JButton("..");
button.setLocation(...);
button.setSize(...);
add(button);
}
public void paintComponent( Graphics g )
{
/*
* Painting some stuff here.
*/
}
}
The other panel is something like this:
public class OtherPanel extends JPanel
{
public OtherPanel()
{
super();
this.setLayout(null);
this.setOpaque(false);
JPanel panel1 = new JPanel();
panel1.setLocation(...);
panel1.setSize(...);
panel1.setOpaque( .. );
JPanel panel2 = new JPanel();
panel2.setLocation(...);
panel2.setSize(...);
panel2.setOpaque( .. );
add(panel1):
add(panel2);
}
}
After that , I put both my panels in a frame. But I want my BoardPanel to occupy more screen than OtherPanel. So I used GridBagLayout for the frame
public class MainFrame extends JFrame
{
private GridBagLayout aGridLayout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public MainFrame()
{
super("Quoridor");
setLayout(gridLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366, 768);
setVisible(true);
setResizable(false);
this.getContentPane().setBackground(Color.decode("#b2a6a6"));
BoardPanel boardPanel = new BoardPanel();
OtherPanel otherPanel = new OtherPanel();
this.addComponent(boardPanel, 1, 1, 2, 1);
this.addComponent(otherPanel, 1, 3, 1, 1);
}
public void addComponent(Component component , int row , int column , int width
, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
aGridLayout.setConstraints(component, constraints);
add(component);
}
}
The problem is , that the frame gives equal space to both panels , and dont give more space to the boardPanel.
Why is this happening ? Doest it have to do with the bounds of the panels ?
Here is a good tutorial on GridBagLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html . Also see the code below and screenshot. The anchor field positions the component at the first line. The weightx field gives more space to the columns for boardPanel. The ipady field specifies how much to add to the height of the component. Here, boardPanel gets most of the width and all of the height. The otherPanel panel gets half of the height.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridExample {
private JFrame mainFrame;
private JPanel boardPanel, otherPanel;
public GridExample(){
mainFrame = new JFrame();
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
boardPanel = new JPanel();
boardPanel.add(new JLabel("board panel"));
boardPanel.setBackground(Color.yellow);
otherPanel = new JPanel();
otherPanel.add(new JLabel("other panel"));
otherPanel.setBackground(Color.green);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.75;
c.ipady = 400;
c.gridx = 0;
c.gridy = 0;
mainFrame.add(boardPanel, c);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.25;
c.ipady = 200;
c.gridx = 1;
c.gridy = 0;
mainFrame.add(otherPanel, c);
mainFrame.setVisible(true);
}
public static void main(String[] args){
GridExample swingContainerDemo = new GridExample();
}
}
I want the various components to spread out and fill the entire window.
Have you tried anything else? Yes, I tried GridLayout but then the buttons look huge. I also tried pack() which made the window small instead. The window should be 750x750 :)
What I was trying is this:
These 4 buttons on the top as a thin strip
The scroll pane with JPanels inside which will contain all the video conversion tasks. This takes up the maximum space
A JPanel at the bottom containing a JProgressBar as a thin strip.
But something seems to have messed up somewhere. Please help me solve this
SSCCE
import java.awt.*;
import javax.swing.*;
import com.explodingpixels.macwidgets.*;
public class HudTest {
public static void main(String[] args) {
HudWindow hud = new HudWindow("Window");
hud.getJDialog().setSize(750, 750);
hud.getJDialog().setLocationRelativeTo(null);
hud.getJDialog().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addVideo = HudWidgetFactory.createHudButton("Add New Video");
JButton removeVideo = HudWidgetFactory.createHudButton("Remove Video");
JButton startAll = HudWidgetFactory.createHudButton("Start All Tasks");
JButton stopAll = HudWidgetFactory.createHudButton("Stop All Tasks");
buttonPanel.add(addVideo);
buttonPanel.add(startAll);
buttonPanel.add(removeVideo);
buttonPanel.add(stopAll);
JPanel taskPanel = new JPanel(new GridLayout(0,1));
JScrollPane taskScrollPane = new JScrollPane(taskPanel);
IAppWidgetFactory.makeIAppScrollPane(taskScrollPane);
for(int i=0;i<10;i++){
ColorPanel c = new ColorPanel();
c.setPreferredSize(new Dimension(750,100));
taskPanel.add(c);
}
JPanel progressBarPanel = new JPanel();
JComponent component = (JComponent) hud.getContentPane();
component.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Insets in = new Insets(2,2,2,2);
gbc.insets = in;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
component.add(buttonPanel,gbc);
gbc.gridy += 1;
gbc.gridheight = 17;
component.add(taskScrollPane,gbc);
gbc.gridy += 17;
gbc.gridheight = 2;
component.add(progressBarPanel,gbc);
hud.getJDialog().setVisible(true);
}
}
Use this
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridbagConstraints.BOTH
Why not simply place three JPanels on top of one JPanel with BorderLayout as Layout Manager, where the middle JPanel with all custom panels with their respective sizes can be accommodated inside a JScrollPane, as shown in the below example :
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 5/17/13
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerBase
{
private JPanel contentPane;
private JPanel buttonPanel;
private JPanel centerPanel;
private CustomPanel[] colourPanel;
private JPanel progressPanel;
private JButton addVideoButton;
private JButton removeVideoButton;
private JButton startAllButton;
private JButton stopAllButton;
private JProgressBar progressBar;
private Random random;
public PlayerBase()
{
colourPanel = new CustomPanel[10];
random = new Random();
}
private void displayGUI()
{
JFrame playerWindow = new JFrame("Player Window");
playerWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
addVideoButton = new JButton("Add New Video");
removeVideoButton = new JButton("Remove Video");
startAllButton = new JButton("Start all tasks");
stopAllButton = new JButton("Stop all tasks");
buttonPanel.add(addVideoButton);
buttonPanel.add(removeVideoButton);
buttonPanel.add(startAllButton);
buttonPanel.add(stopAllButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scroller = new JScrollPane();
centerPanel = new JPanel(new GridLayout(0, 1, 2, 2));
for (int i = 0; i < colourPanel.length; i++)
{
colourPanel[i] = new CustomPanel(new Color(
random.nextInt(255), random.nextInt(255)
, random.nextInt(255)));
centerPanel.add(colourPanel[i]);
}
scroller.setViewportView(centerPanel);
contentPane.add(scroller, BorderLayout.CENTER);
progressPanel = new JPanel(new BorderLayout(5, 5));
progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
progressPanel.add(progressBar);
contentPane.add(progressPanel, BorderLayout.PAGE_END);
playerWindow.setContentPane(contentPane);
playerWindow.pack();
//playerWindow.setSize(750, 750);
playerWindow.setLocationByPlatform(true);
playerWindow.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new PlayerBase().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
public CustomPanel(Color backGroundColour)
{
setOpaque(true);
setBackground(backGroundColour);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(750, 100));
}
}
OUTPUT :
I've attached a screenshot for which the following Border legend applies:
Yellow = JPanel with BorderLayout
Blue = JPanel with GridBagLayout
Fuchsia = JPanel with FlowLayout
There are two panels not blocked out in colors that warrant mentioning:
1) The title panel where the word "Primary" is displayed; this panel is at BorderLayout.NORTH in "Yellow" panel.
2) The image panel where the image of the device is located; this panel is a sibling to "Fuchsia"
"Blue" is at BorderLayout.CENTER in "Yellow" while "Fuchsia" and the image panel are given the following constraints:
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(0, 10, 0, 0);
c.fill = GridBagConstraints.BOTH;
//"Blue".add(imagePanel, c);
c.weighty = 0.80;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
//"Blue".add("Fuchsia", c);
As you can probably tell from the image, I'm trying to get rid of the "wasted" space in "Blue" right below "Fuchsia". I don't seem to be able to do it with GridBagConstraints, so am I just using the wrong LayoutManager? It looks to me like "Blue", who is at CENTER in the BorderLayout is just giving each child JPanel half of the available space and reserving the remainder space instead of contracting upward. What am I missing here? Is this simply a matter of setting a preferred or maximum size on "Fuchsia"? it doesn't seem like that will get me where I want to be, since the border around "Fuchsia" (which is covered by my color coding) is where I want the end of the component to be.
Have a look at this output, from this code example :
import java.awt.*;
import javax.swing.*;
public class LayoutTest
{
private void displayGUI()
{
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.YELLOW);
contentPane.setLayout(new BorderLayout(2, 2));
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel headingLabel = new JLabel("Primary");
topPanel.add(headingLabel);
contentPane.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.BLUE);
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
JPanel imagePanel = new JPanel();
JLabel imageLabel = null;
try
{
imageLabel = new JLabel(
new ImageIcon(
new java.net.URL(
"http://pscode.org/"
+ "tame/screenshot/"
+ "landscape/slider1.gif")));
}
catch(Exception e)
{
e.printStackTrace();
}
imagePanel.add(imageLabel);
centerPanel.add(imagePanel, gbc);
JPanel detailsPanel = new JPanel();
detailsPanel.setOpaque(true);
detailsPanel.setBackground(Color.WHITE);
detailsPanel.setBorder(
BorderFactory.createEmptyBorder(
5, 5, 5, 5));
detailsPanel.setLayout(new GridLayout(0, 1, 5, 5));
JLabel statusLabel = new JLabel("Chassis Status : ");
JLabel usageLabel = new JLabel("Bandwidth Usage : ");
JLabel fanLabel = new JLabel("Fan Status : ");
detailsPanel.add(statusLabel);
detailsPanel.add(usageLabel);
detailsPanel.add(fanLabel);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.8;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 3;
centerPanel.add(detailsPanel, gbc);
contentPane.add(centerPanel, BorderLayout.CENTER);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new LayoutTest().displayGUI();
}
});
}
}
Without using GridBagLayout could be
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NestedLayout {
private JFrame frame = new JFrame();
private JPanel yellowNorthPanel = new JPanel();
private JPanel yellowPanel = new JPanel();
private JPanel bluePanel = new JPanel();
private JPanel fuchsiaTopPanel = new JPanel();
private JPanel fuchsiaBottonPanel = new JPanel();
public NestedLayout() {
yellowNorthPanel.setBorder(new LineBorder(Color.yellow, 5));
yellowPanel.setLayout(new BorderLayout());
yellowPanel.setBorder(new LineBorder(Color.yellow, 5));
bluePanel.setLayout(new BorderLayout(5, 5));
bluePanel.setBorder(new LineBorder(Color.blue, 5));
fuchsiaTopPanel.setBorder(new LineBorder(Color.cyan, 5));
fuchsiaBottonPanel.setBorder(new LineBorder(Color.cyan, 5));
bluePanel.add(fuchsiaTopPanel, BorderLayout.NORTH);
bluePanel.add(fuchsiaBottonPanel);
yellowPanel.add(bluePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(yellowNorthPanel, BorderLayout.NORTH);
frame.add(yellowPanel);
//frame.pack();
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new NestedLayout();
}
});
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to hand-code a Java GUI using Swing and AWT. I'm using various layouts to try and achieve or something similar to the GUI posted below (it's a mock layout made with Pencil):
What I got so far is this, but can't seem to make it more "polite", appealing and user-friendly as possible.
This is the code I have done so far:
import java.awt.*;
import javax.swing.*;
import javax.swing.JTable;
public class GUI extends JFrame {
public void buildGui() {
JFrame frame = new JFrame("Hotel TV Scheduler");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(0,0));
JPanel chPanel = new JPanel();
chPanel.setLayout(new GridLayout(3,2));
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridLayout(3,2));
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new GridLayout(0,2));
JPanel addPanel = new JPanel();
addPanel.setLayout(new GridLayout(0,3));
mainPanel.add(chPanel, BorderLayout.LINE_START);
mainPanel.add(listPanel, BorderLayout.CENTER);
mainPanel.add(infoPanel, BorderLayout.LINE_END);
JTable chOneTable = new JTable();
JTable chTwoTable = new JTable();
JTable listTable = new JTable();
JLabel ch1Label = new JLabel("Channel 1");
JLabel ch2Label = new JLabel("Channel 2");
JLabel listLabel = new JLabel("List");
JButton rmvChOneButton = new JButton("Remove Channel");
JButton rmvChTwoButton = new JButton("Remove Channel");
chPanel.add(ch1Label);
chPanel.add(ch2Label);
chPanel.add(chOneTable);
chPanel.add(chTwoTable);
chPanel.add(rmvChOneButton);
chPanel.add(rmvChTwoButton);
listPanel.add(listLabel);
listPanel.add(listTable);
JLabel titleLabel = new JLabel("Title");
JLabel genreLabel = new JLabel("Genre");
JLabel durationLabel = new JLabel("Duration");
JLabel actorLabel = new JLabel("Actor");
JLabel directorLabel = new JLabel("Director");
JLabel rentableLabel = new JLabel("Rentable");
JLabel synLabel = new JLabel("Synopsis");
JTextField txtTitle = new JTextField();
JTextField txtGenre = new JTextField();
JTextField txtDuration = new JTextField();
JTextField txtActor = new JTextField();
JTextField txtDirector = new JTextField();
JTextField txtSynopsis = new JTextField();
JCheckBox rentCB = new JCheckBox();
JButton btnAddProg = new JButton("Add Program");
JList channelList = new JList();
JList timeList = new JList();
infoPanel.add(titleLabel);
infoPanel.add(txtTitle);
infoPanel.add(genreLabel);
infoPanel.add(txtGenre);
infoPanel.add(durationLabel);
infoPanel.add(txtDuration);
infoPanel.add(actorLabel);
infoPanel.add(txtActor);
infoPanel.add(directorLabel);
infoPanel.add(txtDirector);
infoPanel.add(rentableLabel);
infoPanel.add(rentCB);
infoPanel.add(synLabel);
infoPanel.add(txtSynopsis);
infoPanel.add(btnAddProg);
infoPanel.add(channelList);
infoPanel.add(timeList);
frame.add(mainPanel);
frame.setVisible(true);
}
}
It doesn't have to be exactly as the mock layout shown above but as much as possible similar or at least more user-friendly.
I want to use anything but GridBagLayout and SwingLayout.
Any ideas on how to improve the code and make it look more similar?
Any help is appreciated.
Brian
Have a look at the MigLayout. It's licensing is very inclusive:
MigLayout is free to use for commercial and non-commercial projects and the source code is provided. It is licensed under the very free BSD or GPL license, whichever you prefer
The JNLP demo application should show up great examples and corresponding source.
Also, try to avoid nesting logically unrelated components. Getting alignment, borders and padding becomes quite painful as you increase the degree of nesting.
What that GUI mostly needs is:
White space between components. Two common ways to provide that are:
Layout padding provided in the constructor of the layout.
Adding an EmptyBorder to components or containers. In the case of many components that already have borders, it is best to wrap them in a JPanel and add the border to the panel.
Constraining panels. E.G. If it is desired to have a group of components in the WEST of a BorderLayout to be 'shoved to the top', add them inside another panel with a BorderLayout.NORTH layout/constraint 1st. Here is an example of what I mean.
Use Eclipse and WindowBuilder. You can go back and "hand code" specific parts later and still return to WindowBuilder if you like.
Have a look at this sample program, will this do to satisfy your needs :-)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class TVSchedule
{
private static final int GAP = 5;
private static TVSchedule tvSchedule;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("HOTEL TV SCHEDULE");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
JPanel centerPanel = new JPanel();
//centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
centerPanel.setLayout(new GridLayout(0, 4, 5, 5));
centerPanel.add(createChannelOnePanel());
centerPanel.add(createChannelTwoPanel());
centerPanel.add(createListPanel());
centerPanel.add(createInformationPanel());
JPanel bottomPanel = new JPanel();
bottomPanel.setOpaque(true);
bottomPanel.setBackground(Color.RED.darker());
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JButton exitButton = new JButton("EXIT");
bottomPanel.add(exitButton);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(bottomPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
private JPanel createChannelOnePanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setOpaque(true);
panel.setBackground(Color.DARK_GRAY);
panel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
GridBagConstraints gbc = new GridBagConstraints();
String[] columnNames = {
"Time",
"Title"
};
Object[][] data = {
{"01:00","Cowboy and Alchemist."}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(new Dimension(200, 200));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.BLACK, 1)
, "Channel 1"
, TitledBorder.CENTER
, TitledBorder.DEFAULT_POSITION));
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
panel.add(scrollPane, gbc);
JButton removeButton = new JButton("Remove Selected");
gbc.weightx = 1.0;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
panel.add(removeButton, gbc);
return panel;
}
private JPanel createChannelTwoPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
GridBagConstraints gbc = new GridBagConstraints();
String[] columnNames = {
"Time",
"Title"
};
Object[][] data = {
{"02:00","Grey's Anatomy"}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(new Dimension(200, 200));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.BLACK, 1)
, "Channel 2"
, TitledBorder.CENTER
, TitledBorder.DEFAULT_POSITION));
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
panel.add(scrollPane, gbc);
JButton removeButton = new JButton("Remove Selected");
gbc.weightx = 1.0;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
panel.add(removeButton, gbc);
return panel;
}
private JPanel createListPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setOpaque(true);
panel.setBackground(Color.DARK_GRAY);
panel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
GridBagConstraints gbc = new GridBagConstraints();
String[] columnNames = {
"Genre",
"Title",
"Duration (Hours)"
};
Object[][] data = {
{"Comedy","C & A", "1.5"}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(new Dimension(200, 200));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.BLACK, 1)
, "List"
, TitledBorder.CENTER
, TitledBorder.DEFAULT_POSITION));
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
panel.add(scrollPane, gbc);
gbc.weightx = 1.0;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
panel.add(Box.createRigidArea(new Dimension(100, 30)), gbc);
return panel;
}
private JPanel createInformationPanel()
{
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(0, 1, 2, 2));
bottomPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.BLACK, 1)
, "Information"
, TitledBorder.LEFT
, TitledBorder.DEFAULT_POSITION));
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
GridBagConstraints gbc = new GridBagConstraints();
JLabel titleLabel = new JLabel("TITLE : ");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(titleLabel, gbc);
JTextField titleField = new JTextField(10);
gbc.gridx = 1;
panel.add(titleField, gbc);
JLabel genreLabel = new JLabel("GENRE : ");
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(genreLabel, gbc);
JTextField genreField = new JTextField(10);
gbc.gridx = 1;
panel.add(genreField, gbc);
JLabel durationLabel = new JLabel("DURATION : ");
gbc.gridx = 0;
gbc.gridy = 2;
panel.add(durationLabel, gbc);
JTextField durationField = new JTextField(10);
gbc.gridx = 1;
panel.add(durationField, gbc);
JLabel actorLabel = new JLabel("ACTOR : ");
gbc.gridx = 0;
gbc.gridy = 3;
panel.add(actorLabel, gbc);
JTextField actorField = new JTextField(10);
gbc.gridx = 1;
panel.add(actorField, gbc);
JLabel directorLabel = new JLabel("DIRECTOR : ");
gbc.gridx = 0;
gbc.gridy = 4;
panel.add(directorLabel, gbc);
JTextField directorField = new JTextField(10);
gbc.gridx = 1;
panel.add(directorField, gbc);
JLabel rentLabel = new JLabel("RENTABLE : ");
gbc.gridx = 0;
gbc.gridy = 5;
panel.add(rentLabel, gbc);
JCheckBox rentCBox = new JCheckBox(" ", false);
rentCBox.setOpaque(true);
rentCBox.setBackground(Color.WHITE);
rentCBox.setHorizontalTextPosition(SwingConstants.LEFT);
gbc.gridx = 1;
panel.add(rentCBox, gbc);
JLabel synopsisLabel = new JLabel("SYNOPSIS : ");
gbc.gridx = 0;
gbc.gridy = 6;
panel.add(synopsisLabel, gbc);
JTextArea synopsisArea = new JTextArea(10, 5);
synopsisArea.setBackground(Color.BLUE.darker());
synopsisArea.setForeground(Color.WHITE);
synopsisArea.setCaretColor(Color.WHITE);
gbc.gridx = 1;
gbc.gridwidth = 2;
gbc.gridheight = 2;
panel.add(synopsisArea, gbc);
JButton addProgramButton = new JButton("Add Program");
gbc.gridx = 0;
gbc.gridy = 8;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.PAGE_END;
gbc.gridwidth = 1;
gbc.gridheight = 1;
panel.add(addProgramButton, gbc);
JSpinner spinner = new JSpinner(new SpinnerNumberModel(00.15, 00.15, 60.00, 00.15));
gbc.gridx = 2;
gbc.gridy = 8;
panel.add(spinner, gbc);
bottomPanel.add(panel);
return bottomPanel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
tvSchedule = new TVSchedule();
tvSchedule.createAndDisplayGUI();
}
});
}
}
I really don't know what you using between JButton and 'JSpinner', that's why never added anything there, hope you can do that yourself.
Here is the output for the same :