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
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;
}
}
So I'm trying to create a series of radio buttons and check boxes that are displayed as follows:
Radio Button
Check Box
Radio Button
Check Box
Radio Button
However, I'm still in the learning process for java and I was wondering if anyone could solve this problem. At the moment the buttons and boxes are being displayed in the correct location, however the first radio button ("Courier") is not being displayed for some reason. If you could perhaps describe the reason and a possible solution that'd be great.
Thanks
Updated Code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Question2 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Font Chooser");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
gbc.gridx = 0;
gbc.gridy = 1;
JCheckBox cb = new JCheckBox("Bold");
gbLayout.setConstraints(cb, gbc);
mainPanel.add(cb);
gbc.gridy = 3;
gbLayout.setConstraints(cb, gbc);
cb = new JCheckBox("Italic");
mainPanel.add(cb);
gbc.gridx = 1;
gbc.gridy = 0;
JRadioButton rb = new JRadioButton("Times");
gbLayout.setConstraints(rb, gbc);
mainPanel.add(rb, gbc);
gbc.gridy = 2;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 4;
mainPanel.add(rb, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
3 issues
Y Coordinate not re-assigned to different value causing last 2 radio buttons to exist at same location
GridBagConstraints not being used for left-hand side components
setConstraints erroneously being used to set constraints
Resultant code:
public class GoodGridBagApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Font Chooser");
frame.add(getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private JPanel getMainPanel() {
JPanel mainPanel = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
gbc.gridx = 1;
gbc.gridy = 2;
JCheckBox cb = new JCheckBox("Bold");
mainPanel.add(cb, gbc);
gbc.gridy = 4;
cb = new JCheckBox("Italic");
mainPanel.add(cb, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
JRadioButton rb = new JRadioButton("Times");
mainPanel.add(rb, gbc);
gbc.gridy = 3;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 5;
mainPanel.add(rb, gbc);
return mainPanel;
}
});
}
}
Read: How to Use GridBagLayout
Please have a look at the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestForm extends JFrame
{
private JLabel firstLabel, secondLabel;
private JTextField firstTxt, secondTxt;
private GridBagLayout mainLayout = new GridBagLayout();
private GridBagConstraints mainCons = new GridBagConstraints();
private JPanel centerPanel;
public TestForm()
{
this.setLayout(mainLayout);
//Declaring instance variables
firstLabel = new JLabel("First: ");
secondLabel = new JLabel("Second: ");
firstTxt = new JTextField(7);
secondTxt = new JTextField(7);
mainCons.anchor = GridBagConstraints.WEST;
mainCons.weightx = 1;
mainCons.gridy = 2;
mainCons.gridx = 1;
mainCons.insets = new Insets(15, 0, 0, 0);
this.add(createCenterPanel(), mainCons);
System.out.println("Center Panel Width: "+centerPanel.getWidth());
this.setTitle("The Test Form");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
centerPanel.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,10,0,0);
centerPanel.add(secondLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,-10,0,0);
centerPanel.add(secondTxt,gbc);
centerPanel.setBorder(BorderFactory.createTitledBorder("The Testing Form"));
centerPanel.setPreferredSize(centerPanel.getPreferredSize());
centerPanel.validate();
System.out.println("Width is: "+centerPanel.getWidth());
System.out.println("Width is: "+centerPanel.getHeight());
return centerPanel;
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TestForm();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I am trying to get the width of the centerPanel in 2 places. But in both cases, I get 0 as the answer! I must get the width and height somehow because the southPanel (not included here) will use those values, with some reduce to the height. Please help!
The width is 0 before pack() or setSize() is called. You can get the width and use it after pack() call
or
define your own LayoutManager which use the width for the height of another layout part (southPanel)
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.