JTable does not fill JScrollPane which is added to JPanel using GridBagLayout - java

I have a JPanel with GridBagLayout. The panel contains 2 rows, first row has a JLabel and second row has a JScrollPane with JTable inside. The table does not fill 100% of the scrollpane. Even I resize my frame, the scrollpane resizes but the table inside always has fixed width.
JTable table=new JTable(myModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scroll=new JScrollPane(table);
JPanel panel=new JPanel(new GridBagLayout());
// component add details skipped
And the following are the grid bag constraints applied to scroll pane while adding to panel.
GridBagConstraints gbc=new GridBagConstraints();
gbc.gridx=0; // first column
gbc.gridy=1; // second row
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.fill=GridBagConstraints.BOTH;
gbc.anchor=GridBagConstraints.NORTHEAST;
gbc.weightx=1.0;
gbc.weighty=1.0;
What went wrong? Problem is with scroll pane or table?

I think that only (notice rows never will be resized by using any of LayoutManager, only columns)
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 0;
GBC isn't proper LayoutManager for JComponents implements Scrollable, use BorderLayout(ev GridLayout) for these JComponents
for example
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JTableAndGBC {
private String[] columnNames = {"Source", "Hit", "Last", "Ur_Diff"};
private JTable table;
private Object[][] data = {{"Swing Timer", 2.99, 5, 1.01},
{"Swing Worker", 7.10, 5, 1.010}, {"TableModelListener", 25.05, 5, 1.01}};
private DefaultTableModel model = new DefaultTableModel(data, columnNames);
public JTableAndGBC() {
JPanel panel = new JPanel(new GridBagLayout());
table = new JTable(model);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(table, gbc);
JFrame frame = new JFrame();
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) throws Exception {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JTableAndGBC();
}
});
}
}
EDIT 1
JTable, JScollPane, JComboBox can't returns reasonable PreferredSize, see my code in the edit, then wokrs for all LayoutManagers,
notice carefully with table.setPreferredScrollableViewportSize(table.getPreferredSize());, I'd suggest to test if Dimension overload desired coordinates or screen resolution or not overload :-),
otherwise to shrink with new Dimension(int, int) instead of table.getPreferredSize()
.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JTableAndGBC {
private String[] columnNames = {"Source", "Hit", "Last", "Ur_Diff"};
private JTable table;
private Object[][] data = {{"Swing Timer", 2.99, 5, 1.01},
{"Swing Worker", 7.10, 5, 1.010}, {"TableModelListener", 25.05, 5, 1.01}};
private DefaultTableModel model = new DefaultTableModel(data, columnNames);
public JTableAndGBC() {
JPanel panel = new JPanel(new GridBagLayout());
table = new JTable(model);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
JScrollPane pane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
panel.add(pane, gbc);
JFrame frame = new JFrame();
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) throws Exception {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JTableAndGBC();
}
});
}
}
EDIT 2
I'm strongly to suggest to use BorderLayout, GridLayout
.
instead of GBC (JTable, JScollPane, JComboBox can't returns reasonable PreferredSize, required to override GBC, brrrr, not why bothering)
.
code for BorderLayout
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class JTableAndGBC {
private String[] columnNames = {"Source", "Hit", "Last", "Ur_Diff"};
private JTable table;
private Object[][] data = {{"Swing Timer", 2.99, 5, 1.01},
{"Swing Worker", 7.10, 5, 1.010}, {"TableModelListener", 25.05, 5, 1.01}};
private DefaultTableModel model = new DefaultTableModel(data, columnNames);
public JTableAndGBC() {
JPanel panel = new JPanel(new BorderLayout()/*(new GridBagLayout()*/);
table = new JTable(model);
//GridBagConstraints gbc = new GridBagConstraints();
//gbc.weightx = 1.0;
//gbc.fill = GridBagConstraints.HORIZONTAL;
JScrollPane pane = new JScrollPane(table,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
/*TableColumn firstColumn = table.getColumnModel().getColumn(0);
firstColumn.setMinWidth(150);
firstColumn.setMaxWidth(200);
TableColumn secondColumn = table.getColumnModel().getColumn(1);
secondColumn.setMinWidth(200);
secondColumn.setMaxWidth(250);
TableColumn thirdColumn = table.getColumnModel().getColumn(1);
thirdColumn.setMinWidth(50);
thirdColumn.setMaxWidth(100); */
table.setRowHeight(30);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
panel.add(pane/*, gbc*/);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) throws Exception {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JTableAndGBC();
}
});
}
}

Thanks for giving valuable suggestions. I found the exact solution for this problem. Size the table at its preferred size or view port size whichever is greater. Regardless of whatever layout manager you use it is working fine!
The solution is have table defined with getScrollableTracksViewportWidth() method, as example given below:
JTable table=new JTable(myModel){
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
};
JScrollPane scroll=new JScrollPane(table);

Remove the
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
line. It causes the fixed table size.

Related

Trying to add two tables into one JFrame, but only one appears

I'm trying to add two tables into my frame, but I only get one. I tried to use different positions in BorderLayouts, but still don't get the final result. My code is below:
private JFrame f = new JFrame("List of cars");
// [SIZE]
f.setSize(700, 600);
// [TABLE]
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("GROUP 1");
table.setPreferredScrollableViewportSize(new Dimension(30, 20));
JScrollPane jScrollPane1 = new JScrollPane(table);
JPanel listPahel = new JPanel();
listPahel.setLayout(new BorderLayout());
listPahel.add(jScrollPane1, BorderLayout.CENTER);
listPahel.setBorder(BorderFactory.createEmptyBorder(50, 10, 400, 500));
listPahel.validate();
//-----------------
DefaultTableModel model2 = new DefaultTableModel();
JTable table2 = new JTable(model2);
model2.addColumn("GROUP 2");
table2.setPreferredScrollableViewportSize(new Dimension(30, 20));
JScrollPane jScrollPane2 = new JScrollPane(table2);
JPanel listPahel2 = new JPanel();
listPahel2.setLayout(new BorderLayout());
listPahel2.add(jScrollPane2, BorderLayout.SOUTH);
listPahel2.setBorder(BorderFactory.createEmptyBorder(200, 20, 20, 20));
listPahel2.validate();
f.add(listPahel);
f.add(listPahel2);
f.setVisible(true);
I always get the second table, but I need to get both.
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
You didn't say how you wanted the JTables arranged on your page, so I put them side by side. Here's the example GUI I came up with.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
I separated the creation of the JFrame from the creation of the two JPanels that hold the JTables. The JFrame has a default BorderLayout. I defined each of the two JPanels to have a BorderLayout.
The two JPanels each have a JScrollPane placed in the CENTER of their BorderLayout.
The two JPanels are placed in the WEST and EAST of the JFrame BorderLayout.
Here's the complete runnable code.
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class TwoJTablesGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TwoJTablesGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Two JTables GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createJTable1Panel(), BorderLayout.WEST);
frame.add(createJTable2Panel(), BorderLayout.EAST);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createJTable1Panel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
DefaultTableModel model = new DefaultTableModel();
model.addColumn("GROUP 1");
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private JPanel createJTable2Panel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
DefaultTableModel model = new DefaultTableModel();
model.addColumn("GROUP 2");
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
}

JTable in JPanel Not Displaying

I don't understand where is the problem. The JTable is embedded in a JScrollPanel which is embedded in a JPanel. The table is not displaying. Any help appreciated. I probably missed to add some elements. Checked thoroughly but cannot find anything. This is just the constructor:
public TableIssues() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 894, 597);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel patientsPanel = new JPanel();
patientsPanel.setBounds(6, 152, 882, 417);
patientsPanel.setLayout(null);
String[] patientsColumns = {
"one",
"two",
"three"};
String[][] tableInput={{"first","second","third"},{"first","second","third"}};
patientsTable = new JTable(tableInput,patientsColumns);
JScrollPane scroll = new JScrollPane();
scroll.setBounds(0, 0, 882, 363);
scroll.setLayout(null);
scroll.setViewportView(patientsTable);
patientsPanel.add(scroll);
JButton addPatietsButton = new JButton("Add");
addPatietsButton.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
addPatietsButton.setBounds(356, 375, 211, 36);
patientsPanel.add(addPatietsButton);
contentPane.add(patientsPanel);
}
NEVER do this:
scroll.setLayout(null);
You ruin the JScrollPane's layout, and so it completely loses its functionality, thereby shooting yourself in the foot. Remove that line.
While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example, this GUI
is created by this code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableIssues2 extends JPanel {
private static final int GAP = 5;
private static final String[] COL_NAMES = {"One", "Two", "Three"};
private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
private JTable patientsTable = new JTable(model);
public TableIssues2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
buttonPanel.add(new JButton("Add"));
buttonPanel.add(new JButton("Remove"));
buttonPanel.add(new JButton("Exit"));
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
for (int i = 0; i < 5; i++) {
model.addRow(new String[]{"First", "Second", "Third"});
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(new JScrollPane(patientsTable), BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
TableIssues2 mainPanel = new TableIssues2();
JFrame frame = new JFrame("TableIssues2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

positionnig myJTextField beside JComboBox

I want to creat a palet with many JComboBox. like that :
for(int x=0; x<MAX; x++){
box[x] = new JComboBox(new String[]{"op1", "op2", "op3");
}
at the right of each JComboBox i want to create many JTextField. So, in my palet i will have some think like that:
myJComboBox1 myJTextField
anotherJTextField
anotherJTextField
myJComboBox2 myJTextField
anotherJTextField
anotherJTextField
...
How can i do that please ? I tried by setBounds and other layout like FlowLayout and GridLayout but without success.
GridBagLayout is the best solution. However, if you are new to Swing, it might be a bit over complicated. In that case:
Use GridLayout(0, 2) for the main panel.
Wrap the combobox in a Panel with a border layout and add it to north. Add it to the main panel.
Use another panel with GridLayout(0,1) add your text fields to it and add it to the main panel.
and loop...
Adding sample code:
package snippet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BorderLayoutTest extends JFrame {
static private int MAX = 10 ;
public BorderLayoutTest() {
super(BorderLayoutTest.class.getName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for(int i = 0; i < MAX; i++) {
add(createComboPanel());
add(createPanelWithTextFields());
}
pack();
}
public Component createComboPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JComboBox<>(new String[] { "First Option", "Second Option", "Third Option" }), BorderLayout.NORTH);
return panel;
}
private Component createPanelWithTextFields() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JTextField(30));
panel.add(new JTextField(30));
panel.add(new JTextField(30));
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new BorderLayoutTest().setVisible(true);
}
});
}
}
Take a look at GridBagLayout. You can use your window like a table.
myPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
JLabel lbl = new JLabel("bla");
myPanel.add(lbl, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 3;
JTextField tf = new JTextField();
myPanel.add(tf, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 3;
JTextField othertf = new JTextField();
myPanel.add(othertf, gbc);
You can even set weights and so on for the GridBagConstraints. It is completly adjusted as table. That will result in something like that:
label textfield
textfield
Just re-read the question. Just replace the JLabels with JComboBoxes and it answers your question a little bit better ;)

JFrame GridBagLayout component positioning

So, I was using null layout but was told it was a terrible idea and so decided to use GridBagLayout, as it's supposedly the easiest to customise. I'm having trouble with positioning my components, I am really confused as to how I can get a label to the top middle of the screen, my table in the middle, and my login button to the bottom right. Does anyone know how to do this?
Here's my code:
import javafx.geometry.HorizontalDirection;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
public class Main
{
JFrame window = new JFrame("PE Fixture"); //JFrame variables
JPanel container = new JPanel();
JPanel guestFixturesPanel = new JPanel();
JPanel loginPanel = new JPanel();
JPanel adminFixturesPanel = new JPanel();
JPanel createPanel = new JPanel();
String[] columns = {"Sport", "Location", "Date", "Result"};
String[][] data = {{"Football", "AQA Highschool", "12.11.13", "5 - 0"},
{"Tennis", "Wembley", "26.11.14.", "TBC"}};
CardLayout cardLayout = new CardLayout();
GridBagConstraints c = new GridBagConstraints();
public Main()
{
container.setLayout(cardLayout);
guestFixturesPanel.setLayout(new GridBagLayout()); //GUEST FIXTURES PANEL COMPONENTS
JButton loginButton = new JButton("Login");
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0, 0, 10, 0);
guestFixturesPanel.add(loginButton, c);
JTable fixturesTable = new JTable(data, columns)
{
public boolean isCellEditable(int data, int columns)
{
return false;
}
};
fixturesTable.setPreferredScrollableViewportSize(new Dimension(500, 300));
fixturesTable.setFillsViewportHeight(true);
JScrollPane scrollTable = new JScrollPane(fixturesTable);
c.gridx = 0;
c.gridy = 0;
c.ipady = 700;
c.ipadx = 400;
guestFixturesPanel.add(scrollTable, c);
JLabel fixturesLabel = new JLabel("FIXTURES");
fixturesLabel.setFont(new Font("TimesRoman", Font.PLAIN, 50));
fixturesLabel.setForeground(Color.WHITE);
c.gridx = 0;
c.gridy = 0;
guestFixturesPanel.add(fixturesLabel, c);
container.add(guestFixturesPanel, "2"); //LABELS EACH COMPONENT WITH A NUMBER
container.add(loginPanel, "3");
container.add(adminFixturesPanel, "4");
container.add(createPanel, "5");
guestFixturesPanel.setBackground(Color.DARK_GRAY); //Colours each panel
loginPanel.setBackground(Color.DARK_GRAY);
adminFixturesPanel.setBackground(Color.DARK_GRAY);
createPanel.setBackground(Color.DARK_GRAY);
cardLayout.show(container, "1");
window.add(container); //Creates the frame of the program.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(500, 860);
window.setResizable(false);
window.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
}
});
}
}
EDIT:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
public class Main
{
String[] columns = {"Sport", "Location", "Date", "Result"};
String[][] data = {{"Football", "AQA Highschool", "12.11.13", "5 - 0"},
{"Tennis", "Wembley", "26.11.14.", "TBC"}};
private void createAndShowGUI()
{
CardLayout layout = new CardLayout();
JPanel guestCard = new JPanel(layout);
JPanel guestTitle = new JPanel(new FlowLayout(FlowLayout.CENTER)); //GUEST TOP PANEL
JLabel fixturesLabel = new JLabel("FIXTURES");
fixturesLabel.setFont(new Font("TimesRoman", Font.PLAIN, 50));
fixturesLabel.setForeground(Color.WHITE);
guestTitle.add(fixturesLabel);
JTable fixturesTable = new JTable(data, columns) //GUEST MID PANEL
{
public boolean isCellEditable(int data, int columns)
{
return false;
}
};
fixturesTable.setPreferredScrollableViewportSize(new Dimension(350, 450));
fixturesTable.setFillsViewportHeight(true);
JScrollPane scrollTable = new JScrollPane(fixturesTable);
JPanel guestBot = new JPanel(new FlowLayout(FlowLayout.RIGHT)); //GUEST BOT PANEL
JButton loginButtonGuest = new JButton("Login");
guestBot.add(loginButtonGuest);
JPanel loginCard = new JPanel(layout); //LOGIN TOP PANEL
JPanel loginTitle = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel loginLabel = new JLabel("LOGIN");
loginLabel.setFont(new Font("TimesRoman", Font.PLAIN, 50));
loginLabel.setForeground(Color.WHITE);
loginTitle.add(loginLabel);
JPanel container = new JPanel(new BorderLayout(8,8)); //ADDS CARDS TO CONTAINER
container.add(guestCard, "2");
container.add(loginCard, "3");
guestCard.add(guestTitle, BorderLayout.NORTH); //ADDS COMPONENTS TO CARDS
guestCard.add(scrollTable, BorderLayout.CENTER);
guestCard.add(guestBot, BorderLayout.SOUTH);
loginCard.add(loginTitle, BorderLayout.NORTH);
container.setBackground(Color.DARK_GRAY); //COLOURS CARDS
guestTitle.setBackground(Color.DARK_GRAY);
scrollTable.setBackground(Color.DARK_GRAY);
guestBot.setBackground(Color.DARK_GRAY);
layout.show(container, "1");
JFrame window = new JFrame("PE Fixtures"); //CREATES WINDOW
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(container);
window.setSize(400, 700);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().createAndShowGUI();
}
});
}
}
ERROR:
"C:\Program Files\Java\jdk1.7.0_51\bin\java" -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 13.0.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.7.0_51\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\jfxrt.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.7.0_51\jre\lib\ext\zipfs.jar;C:\Users\Harry\Desktop\Computer Science Projects\PE Fixtures v2.0\out\production\PE Fixtures v2.0;C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 13.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain Main
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: cannot add to layout: unknown constraint: 2
at java.awt.BorderLayout.addLayoutComponent(BorderLayout.java:463)
at java.awt.BorderLayout.addLayoutComponent(BorderLayout.java:424)
at java.awt.Container.addImpl(Container.java:1120)
at java.awt.Container.add(Container.java:966)
at Main.createAndShowGUI(Main.java:48)
at Main.access$000(Main.java:8)
at Main$2.run(Main.java:77)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
I am really confused as to how I can get a label to the top middle of
the screen, my table in the middle, and my login button to the bottom
right.
As you can see GridBagLayout is not the simplest layout manager (too much troubles and not really too much power). To lay out this little amount of components I'd suggest you use a Nested Layout approach:
Use BorderLayout to lay out the "main" panel components (label, table and button).
Use FlowLayout to center the label inside a top panel and place the button at the right in a bottom panel.
Example
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Demo {
private void createAndShowGUI() {
JLabel label = new JLabel("Title");
label.setFont(label.getFont().deriveFont(Font.BOLD | Font.ITALIC, 18));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
topPanel.add(label);
DefaultTableModel model = new DefaultTableModel(new Object[]{"Column # 1", "Column # 2"}, 0);
model.addRow(new Object[]{"Property # 1", "Value # 1"});
model.addRow(new Object[]{"Property # 2", "Value # 2"});
model.addRow(new Object[]{"Property # 3", "Value # 3"});
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JButton button = new JButton("Log In");
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(button);
JPanel content = new JPanel(new BorderLayout(8, 8));
content.add(topPanel, BorderLayout.NORTH);
content.add(scrollPane, BorderLayout.CENTER);
content.add(bottomPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}
Screenshot
In addition
For more complex GUI designs you may want to try one of these third-party layout managers suggested in this answer:
MigLayout
DesignGridLayout
FormLayout

Why does GridBagLayout provide strange result?

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 :

Categories