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;
}
}
Related
I am currently trying to include a JTable to my JPanel. I was not having any problems with my code previously until I started to code the table. Sometimes when I run my program everything will appear, sometimes just the panels appear, and sometimes/majority of the time nothing will appear. I just don't understand why it is not consistent. There are no errors in the console. I have included below my ViewPage.java, Page.java, and Main.java.
`
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ViewPage extends Page implements ActionListener
{
JPanel panel1, panel2, panel3;
JLabel searchLabel, repairsLabel, dateLabel;
JButton goButton, recentButton, oldestButton, homeButton;
JComboBox dropDown;
JTextField textField;
JTable tabel;
JScrollPane scrollpane;
public ViewPage()
{
panel1 = new JPanel();
panel1.setBackground(Color.blue);
panel1.setBounds(0,0,1280,120);
panel2 = new JPanel();
panel2.setBackground(Color.green);
panel2.setBounds(0,120,1280,480);
panel3 = new JPanel();
panel3.setBackground(Color.red);
panel3.setBounds(0,600,1280,120);
//Panel 1 components
repairsLabel = new JLabel("Repairs");
repairsLabel.setFont(new Font("Serif", Font.BOLD, 50));
searchLabel = new JLabel("Search :");
searchLabel.setFont(new Font("Serif", Font.PLAIN, 25));
goButton = new JButton("GO");
goButton.setFocusable(false);
goButton.addActionListener(this);
textField = new JTextField();
String[] filters = {" ", "customerID", "First_Name", "Last_Name"};
dropDown = new JComboBox(filters);
dropDown.addActionListener(this);
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 0);
gbc.weightx = 5.5;
gbc.gridx = 0;
gbc.gridy = 0;
panel1.add(repairsLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.5;
gbc.gridx = 1;
gbc.gridy = 0;
panel1.add(searchLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.weightx = 3;
gbc.gridx = 2;
gbc.gridy = 0;
panel1.add(dropDown, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.ipadx = 100;
panel1.add(textField, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 100);
gbc.gridx = 4;
gbc.gridy = 0;
gbc.ipadx = 1;
panel1.add(goButton, gbc);
//Panel 2 components
panel2.setLayout(new GridBagLayout());
String[][] data = new String[50][8];
String[] headings = {"customer_ID", "Date", "First Name", "Last Name", "Phone #", "OS", "PC Type", "Problem"};
JTable table = new JTable(data, headings);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(1000,400));
table.setFillsViewportHeight(true);
scrollpane = new JScrollPane(table);
panel2.add(scrollpane);
//Panel 3 componets
panel3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
dateLabel = new JLabel("Date Filter: ");
dateLabel.setFont(new Font("Serif", Font.PLAIN, 25));
recentButton = new JButton("Most Recent");
oldestButton = new JButton("Oldest");
homeButton = new JButton("Home");
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(1, 10, 1, 0);
gbc2.weightx = 5.5;
gbc2.gridx = 0;
gbc2.gridy = 0;
panel3.add(dateLabel, gbc);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dropDown)
{
System.out.println(dropDown.getSelectedItem());
}
}
}
`
`
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public abstract class Page
{
private final static int pageWidth = 1280;
private final static int pageHeight = 720;
protected JFrame frame;
public Page()
{
frame = new JFrame();
frame.setTitle("Computer Repair Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(pageWidth, pageHeight);
frame.setLayout(null);
frame.setVisible(true);
}
public int getpageWidth()
{
return pageWidth;
}
public int getpageHeight()
{
return pageHeight;
}
}
`
`
public class Main {
public static void main(String[] args) {
ViewPage viewPage = new ViewPage();
}
}
`
Ouput:
enter image description here
This is what I am expecting to output which has only appeared 2-3 times out of the 50 times I have tried running the program.
enter image description here
I am new to GUI in java, and have been using this video to learn. When I run the program, the window is blank until I resize it.
public class GUIProgram extends JFrame
{
int screenWidth = 1000; //screenSize.width;
int screenHeight = 800; //screenSize.height;
public GUIProgram()
{
super("DATABASE");
setSize(screenWidth, screenHeight);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel(new GridBagLayout());
JButton b = new JButton("Button 1");
JButton c = new JButton("Button 2");
p.add(b);
p.add(c);
JCheckBox cb = new JCheckBox("Do you LOVE bacon?");
JCheckBox cb2 = new JCheckBox("Do you LOVE cheese?");
p2.add(cb);
p2.add(cb2);
JLabel label = new JLabel("This is a label");
JTextArea tb = new JTextArea("this is a test area");
JTextField textField = new JTextField("text field");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15,15,15,15);
gbc.gridx = 0;
gbc.gridy = 0;
p3.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
p3.add(tb, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
p3.add(textField, gbc);
add(p, BorderLayout.SOUTH);
add(p3, BorderLayout.CENTER);
add(p2, BorderLayout.NORTH);
}
}
Thanks in advance to anyone who can lend me some advice!
Please let me know if there is some ambiguity in what I'm asking or how I explained myself.
Call setVisible() last, immediately after pack().
Tip:
setSize(screenWidth, screenHeight); Don't set the size of top level containers. Instead layout the content & call pack().
I have a Swing Form that contains a JScrollPane(activityScrollPane) for a JPanel(activityPanel). The panel contains a JTextField and a JButton (that is used to add more fields to the Panel). Now the problem is that the elements start from the center of the panel as in the image below (with the borders marking the activityScrollPane boundary)
Following is the code I am currently using to make the scroll pane and associated components.
//part of the code for creating the ScrollPane
final JPanel activityPanel = new JPanel(new GridBagLayout());
gbc.gridx=0;
gbc.gridy=0;
JScrollPane activityScrollPane = new JScrollPane(activityPanel);
//adding activity fields
activityFields = new ArrayList<JTextField>();
fieldIndex = 0;
activityFields.add(new JTextField(30));
final GridBagConstraints activityGBC = new GridBagConstraints();
activityGBC.gridx=0;
activityGBC.gridy=0;
activityGBC.anchor = GridBagConstraints.FIRST_LINE_START;
activityPanel.add(activityFields.get(fieldIndex),activityGBC);
fieldIndex++;
JButton btn_more = (new JButton("more"));
activityGBC.gridx=1;
activityPanel.add(btn_more,activityGBC);
How can I make the JTextField and the JButton or for that matter any component to appear on the top left corner of the JScrollPane. I have already tried using
activityConstraints.anchor = GridBagConstraints.NORTHWEST;
as pointed in the SO post, but it does not at all seem to work.
You simply forgot to provide any weightx/weighty values, atleast one having a non-zero value will do. have a look at this code example :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Latest EDIT : No spacing along Y-Axis
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private JTextField tfield2;
private JButton button2;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
//gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
tfield2 = new JTextField(10);
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield2, gbc);
button2 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button2, gbc);
JScrollPane scroller = new JScrollPane(contentPane);
frame.add(scroller);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Sorry as my answer me be on the off-side of what you have asked, but why dont you use GroupLayout instead of GridBag Layout, thats much more easier to handle
try it with BorderLayout: controls.setLayout(new BorderLayout()); and then apply it for your JPanel controls.add(yourPanel, BorderLayout.PAGE_START);
I also have problems with GridBagLayout so i solved it with BorderLayout and it works so fine.
So i wrote for your little example:
private void initComponents() {
controls = new Container();
controls = getContentPane();
controls.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
field = new JTextField(20);
c.gridx = 0;
c.gridy = 0;
panel.add(field, c);
one = new JButton("Go!");
c.gridx = 1;
c.gridy = 0;
panel.add(one, c);
controls.add(panel, BorderLayout.PAGE_START);
}
Hope it helps!
I think this could be simple and possible, you can
put Nested JPanel to the JScrollPane
to this JPanel
put JPanels contains JComponent to the GridLayout (notice about scrolling, you have to change scrolling increment)
or use most complex JComponents as
put JPanels contains JComponent as Item to the JList
put JPanels contains JComponent as row to the JTable (with only one Column, with or without TableHeader)
Add one panel at the right and one at the bottom.
Right Panel:
Set Weight X to 1.0.
Set Fill to horizontal.
Bottom Panel:
Set Weight Y to 1.0.
Set Fill to vertical
There may be better ways to that, but this one worked for me.
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 :
Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
How can I make that each JPanel is 300px width and 400px in height?
for GridBaglayout you have to set
fill
anchor
weightx and weighty
gridx / gridy (depend of orientations)
then is possible for example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 20;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 60;
//gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 2;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
on most cases will be better use another LayoutManager
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
Box content = new Box(BoxLayout.X_AXIS);
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
content.add(P1panel);
content.add(P2panel);
tradeframe.setContentPane(content);
tradeframe.setVisible(true);
Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.
Here is the way to do that :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest
{
public GridBagLayoutTest()
{
JFrame frame = new JFrame("GridBag Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
container.add(leftPanel, gbc);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.fill = GridBagConstraints.BOTH;
container.add(rightPanel, gbc);
frame.setSize(600, 400);
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new GridBagLayoutTest();
}
};
SwingUtilities.invokeLater(runnable);
}
}
OUTPUT :
You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.
The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.