putting a JPanel in a JFrame: setContentPane() and add() both seem to work. Is there any technical difference?
One example from web has the following. Changing frame.setContentPane(panel) to frame.add(panel) seems to produce the same behavior.
//file: Calculator.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
GridBagConstraints gbc = new GridBagConstraints();
JTextField theDisplay = new JTextField();
public Calculator() {
gbc.weightx = 1.0; gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
ContainerListener listener = new ContainerAdapter() {
public void componentAdded(ContainerEvent e) {
Component comp = e.getChild();
if (comp instanceof JButton)
((JButton)comp).addActionListener(Calculator.this);
}
};
addContainerListener(listener);
gbc.gridwidth = 4;
addGB(this, theDisplay, 0, 0);
// make the top row
JPanel topRow = new JPanel();
topRow.addContainerListener(listener);
gbc.gridwidth = 1;
gbc.weightx = 1.0;
addGB(topRow, new JButton("C"), 0, 0);
gbc.weightx = 0.33;
addGB(topRow, new JButton("%"), 1, 0);
gbc.weightx = 1.0;
addGB(topRow, new JButton("+"), 2, 0 );
gbc.gridwidth = 4;
addGB(this, topRow, 0, 1);
gbc.weightx = 1.0; gbc.gridwidth = 1;
// make the digits
for(int j=0; j<3; j++)
for(int i=0; i<3; i++)
addGB(this, new JButton("" + ((2-j)*3+i+1) ), i, j+2);
// -, x, and divide
addGB(this, new JButton("-"), 3, 2);
addGB(this, new JButton("x"), 3, 3);
addGB(this, new JButton("\u00F7"), 3, 4);
// make the bottom row
JPanel bottomRow = new JPanel();
bottomRow.addContainerListener(listener);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("0"), 0, 0);
gbc.weightx = 0.33;
addGB(bottomRow, new JButton("."), 1, 0);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("="), 2, 0);
gbc.gridwidth = 4;
addGB(this, bottomRow, 0, 5);
}
void addGB(Container cont, Component comp, int x, int y) {
if ((cont.getLayout() instanceof GridBagLayout) == false)
cont.setLayout(new GridBagLayout());
gbc.gridx = x; gbc.gridy = y;
cont.add(comp, gbc);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("C"))
theDisplay.setText("");
else
theDisplay.setText(theDisplay.getText()
+ e.getActionCommand());
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 250);
frame.setLocation(200, 200);
frame.setContentPane(new Calculator());
frame.setVisible(true);
}
}
Another has the following. Changing frame.add(panel) to frame.setContentPane(panel) seems to produce the same behavior.
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class recMod {
public enum RecFieldNames {
FIRST_NAME("First Name:"),
LAST_NAME("Last Name:"),
VENDOR("Vendor:"),
VENDOR_LOC_CODE("Vendor Location Code:"),
USER_EMAIL("User Email Address:"),
USER_NAME("Username:"),
PASSWORD("Password:"),
USER_CODE("User Code:");
private String name;
private RecFieldNames(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static final int FIELD_COLS = 7;
private Map<RecFieldNames, JTextField> recFieldMap =
new HashMap<RecFieldNames, JTextField>();
//JButton[] recButtons = new JButton[3];
public recMod() {
JFrame frame = new JFrame("Record Modify");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
addLabelField(panel, RecFieldNames.FIRST_NAME, 0, 0, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.LAST_NAME, 2, 0, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.EAST);
addLabelField(panel, RecFieldNames.VENDOR, 0, 1, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.VENDOR_LOC_CODE, 2, 1, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_EMAIL, 0, 2, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_NAME, 0, 3, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.PASSWORD, 2, 3, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_CODE, 0, 4, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
//frame.getContentPane().setPreferredSize(new Dimension(500, 400));
((JComponent) frame.getContentPane()).
setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public String getFieldText(RecFieldNames rfn) {
return recFieldMap.get(rfn).getText();
}
private void addLabelField(JPanel p, RecFieldNames recFieldNames, int x,
int y, int width, int height, int labelAlign, int fieldAlign) {
GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel(recFieldNames.getName());
JTextField textField = new JTextField(FIELD_COLS);
recFieldMap.put(recFieldNames, textField);
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
int midInset = (x == 2) ? 40 : 5;
gbc.insets = new Insets(5, midInset, 5, 5);
gbc.anchor = labelAlign;
gbc.fill = GridBagConstraints.HORIZONTAL;
p.add(label, gbc);
gbc.gridx = x + 1;
gbc.anchor = fieldAlign;
gbc.insets = new Insets(5, 5, 5, 5);
p.add(textField, gbc);
}
public static void main(String args[]) {
new recMod();
}
}
The content pane of the frame is a JPanel.
So if you use frame.add( another panel ), then you have a structure like:
- JFrame
- content pane
- another panel
If you use frame setContentPane( another panel ) you have:
- JFrame
- another panel
See the section from the Swing tutorial on Adding Components to the Content Pane.
Related
For a school project I want to create a GUI which displays a few statistics of a server. I want to use a GridBagLayout to designate boxes to different statistics. The following picture is what I want the GUI layout to be
But when I run my code it looks like this:
The text should fill their area with the background colour and be in their designated area depicted in the first picture.
This is the code I am using:
package Monitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MonitoringGui extends JFrame implements ActionListener {
private Configuratie config;
private MonitoringPanel mp;
public MonitoringGui(Configuratie config) {
this.config = config;
setTitle("MonitoringGui");
setSize(850, 600);
setLayout(new GridBagLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// onderdelen toevoegen en verwijderen
JPanel selectorPanel = new JPanel();
selectorPanel.setLayout(new GridBagLayout());
selectorPanel.setBorder(BorderFactory.createLineBorder(Color.black));
addElement(selectorPanel, 0, 0, 4, 2, 0.2, 1, new int[]{20, 20, 20, 20});
// output en input area
JPanel drawArea = new JPanel();
selectorPanel.setLayout(new GridBagLayout());
drawArea.setBackground(Color.lightGray);
addElement(drawArea, 5, 0, 10, 1, 1, 1, new int[]{20, 0, 0, 20});
// buttons, etc
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
addElement(buttonPanel, 5, 1, 10, 1, 1, 0.2, new int[]{0, 0, 20, 20});
//grafiek area
JPanel grafiekArea = new JPanel();
grafiekArea.setLayout(new GridBagLayout());
grafiekArea.setBackground(Color.CYAN);
grafiekArea.add(new JLabel("GrafiekArea"));
addElement(grafiekArea, 0, 0, 3, 1, 1, 0, new int[]{20, 20, 20, 20}, drawArea);
//beschikbaar area
JPanel beschArea = new JPanel();
beschArea.setLayout(new GridBagLayout());
beschArea.setBackground(Color.ORANGE);
beschArea.add(new JLabel("BeschArea"));
addElement(beschArea, 0, 1, 1, 1, 0, 0, new int[]{20, 20, 20, 20}, drawArea);
//uptime area
JPanel uptimeArea = new JPanel();
uptimeArea.setLayout(new GridBagLayout());
uptimeArea.setBackground(Color.RED);
uptimeArea.add(new JLabel("UptimeArea"));
addElement(uptimeArea, 2, 1, 1, 1, 0, 0, new int[]{20, 20, 20, 20}, drawArea);
//schijfruimte area
JPanel schijfruimteArea = new JPanel();
schijfruimteArea.setLayout(new GridBagLayout());
schijfruimteArea.setBackground(Color.GREEN);
schijfruimteArea.add(new JLabel("Schijfruimte"));
addElement(schijfruimteArea, 3, 1, 1, 1, 0.2, 0.2, new int[]{20, 20, 20, 20}, drawArea);
setVisible(true);
}
public void addElement(Component comp, int x, int y, int width, int height, double weightx, double weighty, int[] insets) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.gridheight = height;
c.gridwidth = width;
c.weightx = weightx;
c.weighty = weighty;
c.insets = new Insets(insets[0], insets[1], insets[2], insets[3]);
add(comp, c);
}
public void addElement(Component comp, int x, int y, int width, int height, double weightx, double weighty, int[] insets, JPanel panel) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.gridheight = height;
c.gridwidth = width;
c.weightx = weightx;
c.weighty = weighty;
c.insets = new Insets(insets[0], insets[1], insets[2], insets[3]);
panel.add(comp, c);
}
}
I figured out the answer. To make this layout work for my application I have to specify the size of the different panels inside each panel. These are the lines of code I had to add:
selectorPanel.setPreferredSize(new Dimension(120,600));
drawArea.setPreferredSize(new Dimension(660, 600));
grafiekArea.setPreferredSize(new Dimension(670,400));
beschArea.setPreferredSize(new Dimension(220,200));
uptimeArea.setPreferredSize(new Dimension(220,200));
schijfruimteArea.setPreferredSize(new Dimension(220,200));
I have been chasing this bug for awhile and can't seem to figure it out. I have a small GUI with a list of labels and text fields. In between the rows that have a label + text field, there is an empty row that contains a JLabel to populate with an error message as necessary. The issue is, when this error message populates, the text fields above them are compressed for some reason and after a few hours of trying different things, I can't seem to pinpoint why. It also seems like all the labels/text areas compress compared to each other slightly as well. Can anyone point out the issue?
I have tried giving each element more space as well in the panel gridbaglayout. That doesn't seem to change the end result.
If looking at the code, the elements are on the 'continuousTransferPanel" Also the "singleTransferPanel" has the same issue with only 2 rows.
public void modifyJobWindow()
{
setTitle("Job Editor");
this.setMinimumSize(new Dimension(350, 400));
this.setSize(350, 300);
this.setResizable(false);
JPanel basePanel = new JPanel();
getContentPane().add(basePanel, BorderLayout.CENTER);
basePanel.setLayout(new BorderLayout(0, 0));
JPanel mainPanel = new JPanel();
basePanel.add(mainPanel, BorderLayout.CENTER);
mainPanel.setBackground(new Color(49, 49, 47));
mainPanel.setLayout(new BorderLayout(0, 0));
JPanel optionPanel = new JPanel();
optionPanel.setBackground(new Color(49, 49, 47));
mainPanel.add(optionPanel, BorderLayout.NORTH);
JLabel transferLabel = new JLabel("Transfer Type: ");
transferLabel.setHorizontalAlignment(SwingConstants.LEFT);
transferLabel.setFont(new Font("Arial", Font.BOLD, 16));
transferLabel.setForeground(Color.WHITE);
optionPanel.add(transferLabel);
comboBox = new JComboBox();
comboBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (comboBox.getSelectedItem().equals("Single File Transfer"))
{
acceptButton.setEnabled(true);
continuousTransferPanel.setVisible(false);
deleteSourceCheckBox.setSelected(false);
deleteSourceCheckBox.setEnabled(true);
deleteSourceCheckBox.setForeground(Color.WHITE);
autostartCheckBox.setSelected(false);
autostartCheckBox.setEnabled(false);
autostartCheckBox.setForeground(Color.GRAY);
singleTransferPanel.setVisible(true);
clearErrors();
}
else if (comboBox.getSelectedItem().equals("Continuous File Transfer"))
{
acceptButton.setEnabled(true);
deleteSourceCheckBox.setSelected(false);
deleteSourceCheckBox.setEnabled(true);
deleteSourceCheckBox.setForeground(Color.WHITE);
singleTransferPanel.setVisible(false);
autostartCheckBox.setEnabled(true);
autostartCheckBox.setForeground(Color.WHITE);
continuousTransferPanel.setVisible(true);
clearErrors();
}
else
{
acceptButton.setEnabled(false);
deleteSourceCheckBox.setSelected(false);
deleteSourceCheckBox.setEnabled(false);
deleteSourceCheckBox.setForeground(Color.GRAY);
autostartCheckBox.setSelected(false);
autostartCheckBox.setEnabled(false);
autostartCheckBox.setForeground(Color.GRAY);
singleTransferPanel.setVisible(false);
continuousTransferPanel.setVisible(false);
clearErrors();
}
}
});
comboBox.setModel(new DefaultComboBoxModel(new String[] {"", "Single File Transfer", "Continuous File Transfer"}));
comboBox.setMaximumRowCount(3);
optionPanel.add(comboBox);
JPanel subMainPanel = new JPanel();
subMainPanel.setBackground(new Color(49, 49, 47));
mainPanel.add(subMainPanel, BorderLayout.CENTER);
GridBagLayout gbl_subMainpanel = new GridBagLayout();
gbl_subMainpanel.columnWidths = new int[] {400};
gbl_subMainpanel.rowHeights = new int[] {175};
gbl_subMainpanel.columnWeights = new double[] {1.0};
gbl_subMainpanel.rowWeights = new double[] {0.0, Double.MIN_VALUE};
subMainPanel.setLayout(gbl_subMainpanel);
continuousTransferPanel = new JPanel();
GridBagConstraints gbc_continuousTransferPanel = new GridBagConstraints();
gbc_continuousTransferPanel.anchor = GridBagConstraints.NORTH;
gbc_continuousTransferPanel.fill = GridBagConstraints.HORIZONTAL;
gbc_continuousTransferPanel.gridx = 0;
gbc_continuousTransferPanel.gridy = 0;
subMainPanel.add(continuousTransferPanel, gbc_continuousTransferPanel);
continuousTransferPanel.setBackground(new Color(49, 49, 47));
GridBagLayout gbl_continuousTransferPanel = new GridBagLayout();
gbl_continuousTransferPanel.columnWidths = new int[] {100, 300};
gbl_continuousTransferPanel.rowHeights = new int[] {25, 15, 25, 15, 25, 15, 25, 15};
gbl_continuousTransferPanel.columnWeights = new double[] {0.0, 1.0};
gbl_continuousTransferPanel.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
continuousTransferPanel.setLayout(gbl_continuousTransferPanel);
continuousTransferPanel.setVisible(false);
JLabel jobCNameLabel = new JLabel("Job Name:");
jobCNameLabel.setFont(new Font("Arial", Font.BOLD, 12));
jobCNameLabel.setForeground(Color.WHITE);
GridBagConstraints gbc_jobCNameLabel = new GridBagConstraints();
gbc_jobCNameLabel.anchor = GridBagConstraints.WEST;
gbc_jobCNameLabel.insets = new Insets(5, 5, 0, 5);
gbc_jobCNameLabel.gridx = 0;
gbc_jobCNameLabel.gridy = 0;
continuousTransferPanel.add(jobCNameLabel, gbc_jobCNameLabel);
JLabel sourceCLabel = new JLabel("Source Folder:");
sourceCLabel.setFont(new Font("Arial", Font.BOLD, 12));
sourceCLabel.setForeground(Color.WHITE);
GridBagConstraints gbc_sourceCLabel = new GridBagConstraints();
gbc_sourceCLabel.anchor = GridBagConstraints.WEST;
gbc_sourceCLabel.insets = new Insets(5, 5, 0, 5);
gbc_sourceCLabel.gridx = 0;
gbc_sourceCLabel.gridy = 2;
continuousTransferPanel.add(sourceCLabel, gbc_sourceCLabel);
JLabel destCLabel = new JLabel("Destination:");
destCLabel.setForeground(Color.WHITE);
destCLabel.setFont(new Font("Arial", Font.BOLD, 12));
GridBagConstraints gbc_destCLabel = new GridBagConstraints();
gbc_destCLabel.insets = new Insets(5, 5, 0, 5);
gbc_destCLabel.anchor = GridBagConstraints.WEST;
gbc_destCLabel.gridx = 0;
gbc_destCLabel.gridy = 4;
continuousTransferPanel.add(destCLabel, gbc_destCLabel);
JLabel fileFilterLabel = new JLabel("File Regex:");
fileFilterLabel.setForeground(Color.WHITE);
fileFilterLabel.setFont(new Font("Arial", Font.BOLD, 12));
GridBagConstraints gbc_fileFilterLabel = new GridBagConstraints();
gbc_fileFilterLabel.insets = new Insets(5, 5, 0, 5);
gbc_fileFilterLabel.anchor = GridBagConstraints.WEST;
gbc_fileFilterLabel.gridx = 0;
gbc_fileFilterLabel.gridy = 6;
continuousTransferPanel.add(fileFilterLabel, gbc_fileFilterLabel);
jobCNameField = new JTextField();
jobCNameField.setBorder(defaultBorder);
GridBagConstraints gbc_jobCNameField = new GridBagConstraints();
gbc_jobCNameField.insets = new Insets(5, 0, 0, 5);
gbc_jobCNameField.fill = GridBagConstraints.HORIZONTAL;
gbc_jobCNameField.gridx = 1;
gbc_jobCNameField.gridy = 0;
continuousTransferPanel.add(jobCNameField, gbc_jobCNameField);
errorFieldCJobName = new JLabel("");
errorFieldCJobName.setFont(new Font("Arial", Font.BOLD, 8));
errorFieldCJobName.setForeground(Color.RED);
GridBagConstraints gbc_errorFieldCJobName = new GridBagConstraints();
gbc_errorFieldCJobName.anchor = GridBagConstraints.WEST;
gbc_errorFieldCJobName.insets = new Insets(0, 5, 0, 5);
gbc_errorFieldCJobName.gridx = 1;
gbc_errorFieldCJobName.gridy = 1;
continuousTransferPanel.add(errorFieldCJobName, gbc_errorFieldCJobName);
sourceCField = new JTextField();
sourceCField.setBorder(defaultBorder);
GridBagConstraints gbc_sourceCField = new GridBagConstraints();
gbc_sourceCField.insets = new Insets(5, 0, 0, 5);
gbc_sourceCField.fill = GridBagConstraints.HORIZONTAL;
gbc_sourceCField.gridx = 1;
gbc_sourceCField.gridy = 2;
continuousTransferPanel.add(sourceCField, gbc_sourceCField);
errorFieldCSourceField = new JLabel("");
errorFieldCSourceField.setFont(new Font("Arial", Font.BOLD, 8));
errorFieldCSourceField.setForeground(Color.RED);
GridBagConstraints gbc_errorFieldCSourceField = new GridBagConstraints();
gbc_errorFieldCSourceField.anchor = GridBagConstraints.WEST;
gbc_errorFieldCSourceField.insets = new Insets(0, 5, 0, 5);
gbc_errorFieldCSourceField.gridx = 1;
gbc_errorFieldCSourceField.gridy = 3;
continuousTransferPanel.add(errorFieldCSourceField, gbc_errorFieldCSourceField);
destCField = new JTextField();
destCField.setBorder(defaultBorder);
GridBagConstraints gbc_destCField = new GridBagConstraints();
gbc_destCField.insets = new Insets(5, 0, 0, 5);
gbc_destCField.fill = GridBagConstraints.HORIZONTAL;
gbc_destCField.gridx = 1;
gbc_destCField.gridy = 4;
continuousTransferPanel.add(destCField, gbc_destCField);
errorFieldCDest = new JLabel("");
errorFieldCDest.setFont(new Font("Arial", Font.BOLD, 8));
errorFieldCDest.setForeground(Color.RED);
GridBagConstraints gbc_errorFieldCDest = new GridBagConstraints();
gbc_errorFieldCDest.anchor = GridBagConstraints.WEST;
gbc_errorFieldCDest.insets = new Insets(0, 5, 0, 5);
gbc_errorFieldCDest.gridx = 1;
gbc_errorFieldCDest.gridy = 5;
continuousTransferPanel.add(errorFieldCDest, gbc_errorFieldCDest);
fileFilterField = new JTextField();
fileFilterField.setBorder(defaultBorder);
GridBagConstraints gbc_fileFilterField = new GridBagConstraints();
gbc_fileFilterField.insets = new Insets(5, 0, 0, 5);
gbc_fileFilterField.fill = GridBagConstraints.HORIZONTAL;
gbc_fileFilterField.gridx = 1;
gbc_fileFilterField.gridy = 6;
continuousTransferPanel.add(fileFilterField, gbc_fileFilterField);
errorFieldFileRegex = new JLabel("");
errorFieldFileRegex.setFont(new Font("Arial", Font.BOLD, 8));
errorFieldFileRegex.setForeground(Color.RED);
GridBagConstraints gbc_errorFieldFileRegex = new GridBagConstraints();
gbc_errorFieldFileRegex.anchor = GridBagConstraints.WEST;
gbc_errorFieldFileRegex.insets = new Insets(0, 5, 0, 5);
gbc_errorFieldFileRegex.gridx = 1;
gbc_errorFieldFileRegex.gridy = 7;
continuousTransferPanel.add(errorFieldFileRegex, gbc_errorFieldFileRegex);
singleTransferPanel = new JPanel();
GridBagConstraints gbc_singleTransferPanel = new GridBagConstraints();
gbc_singleTransferPanel.anchor = GridBagConstraints.NORTH;
gbc_singleTransferPanel.fill = GridBagConstraints.HORIZONTAL;
gbc_singleTransferPanel.gridx = 0;
gbc_singleTransferPanel.gridy = 0;
subMainPanel.add(singleTransferPanel, gbc_singleTransferPanel);
singleTransferPanel.setBackground(new Color(49, 49, 47));
GridBagLayout gbl_singleTransferPanel = new GridBagLayout();
gbl_singleTransferPanel.columnWidths = new int[] {100, 200};
gbl_singleTransferPanel.rowHeights = new int[] {30, 15, 30, 15};
gbl_singleTransferPanel.columnWeights = new double[] {0.0, 1.0};
gbl_singleTransferPanel.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
singleTransferPanel.setLayout(gbl_singleTransferPanel);
singleTransferPanel.setVisible(false);
JLabel sourceLabel = new JLabel("Source File:");
sourceLabel.setFont(new Font("Arial", Font.BOLD, 12));
sourceLabel.setForeground(Color.WHITE);
GridBagConstraints gbc_sourceLabel = new GridBagConstraints();
gbc_sourceLabel.anchor = GridBagConstraints.WEST;
gbc_sourceLabel.insets = new Insets(5, 5, 0, 5);
gbc_sourceLabel.gridx = 0;
gbc_sourceLabel.gridy = 0;
singleTransferPanel.add(sourceLabel, gbc_sourceLabel);
JLabel destLabel = new JLabel("Destination:");
destLabel.setForeground(Color.WHITE);
destLabel.setFont(new Font("Arial", Font.BOLD, 12));
GridBagConstraints gbc_destLabel = new GridBagConstraints();
gbc_destLabel.insets = new Insets(5, 5, 0, 5);
gbc_destLabel.anchor = GridBagConstraints.WEST;
gbc_destLabel.gridx = 0;
gbc_destLabel.gridy = 2;
singleTransferPanel.add(destLabel, gbc_destLabel);
sourceField = new JTextField();
sourceField.setBorder(defaultBorder);
GridBagConstraints gbc_sourceField = new GridBagConstraints();
gbc_sourceField.insets = new Insets(5, 0, 0, 5);
gbc_sourceField.fill = GridBagConstraints.HORIZONTAL;
gbc_sourceField.gridx = 1;
gbc_sourceField.gridy = 0;
singleTransferPanel.add(sourceField, gbc_sourceField);
errorFieldSourceField = new JLabel("");
errorFieldSourceField.setFont(new Font("Arial", Font.BOLD, 8));
errorFieldSourceField.setForeground(Color.RED);
GridBagConstraints gbc_errorFieldSourceField = new GridBagConstraints();
gbc_errorFieldSourceField.anchor = GridBagConstraints.WEST;
gbc_errorFieldSourceField.insets = new Insets(0, 5, 0, 5);
gbc_errorFieldSourceField.gridx = 1;
gbc_errorFieldSourceField.gridy = 1;
singleTransferPanel.add(errorFieldSourceField, gbc_errorFieldSourceField);
destField = new JTextField();
destField.setBorder(defaultBorder);
GridBagConstraints gbc_destField = new GridBagConstraints();
gbc_destField.insets = new Insets(5, 0, 0, 5);
gbc_destField.fill = GridBagConstraints.HORIZONTAL;
gbc_destField.gridx = 1;
gbc_destField.gridy = 2;
singleTransferPanel.add(destField, gbc_destField);
errorFieldDest = new JLabel("");
errorFieldDest.setFont(new Font("Arial", Font.BOLD, 8));
errorFieldDest.setForeground(Color.RED);
GridBagConstraints gbc_errorFieldDest = new GridBagConstraints();
gbc_errorFieldDest.anchor = GridBagConstraints.WEST;
gbc_errorFieldDest.insets = new Insets(0, 5, 0, 5);
gbc_errorFieldDest.gridx = 1;
gbc_errorFieldDest.gridy = 3;
singleTransferPanel.add(errorFieldDest, gbc_errorFieldDest);
JPanel titlePanel = new JPanel();
basePanel.add(titlePanel, BorderLayout.NORTH);
titlePanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
titlePanel.setBackground(new Color(49, 49, 47));
titlePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel titleLabel = new JLabel("File Transfer Job Editor");
titleLabel.setForeground(new Color(243, 112, 33));
titleLabel.setFont(new Font("Arial", Font.BOLD, 28));
titlePanel.add(titleLabel);
JPanel buttonPanel = new JPanel();
basePanel.add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
GridBagLayout gbl_buttonPanel = new GridBagLayout();
gbl_buttonPanel.columnWidths = new int[] {175, 175, 0};
gbl_buttonPanel.rowHeights = new int[] {30, 30, 0};
gbl_buttonPanel.columnWeights = new double[] {1.0, 1.0, Double.MIN_VALUE};
gbl_buttonPanel.rowWeights = new double[] {0.0, 0.0, Double.MIN_VALUE};
buttonPanel.setBackground(new Color(49, 49, 47));
buttonPanel.setLayout(gbl_buttonPanel);
autostartCheckBox = new JCheckBox("Auto Start");
autostartCheckBox.setForeground(Color.gray);
autostartCheckBox.setEnabled(false);
autostartCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
autostartCheckBox.setFont(new Font("Calibri", Font.BOLD, 16));
autostartCheckBox.setBackground(new Color(49, 49, 47));
GridBagConstraints gbc_autostartCheckBox = new GridBagConstraints();
gbc_autostartCheckBox.gridwidth = 1;
gbc_autostartCheckBox.fill = GridBagConstraints.VERTICAL;
gbc_autostartCheckBox.insets = new Insets(0, 0, 5, 5);
gbc_autostartCheckBox.gridx = 0;
gbc_autostartCheckBox.gridy = 0;
buttonPanel.add(autostartCheckBox, gbc_autostartCheckBox);
deleteSourceCheckBox = new JCheckBox("Delete Source File");
deleteSourceCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
deleteSourceCheckBox.setForeground(Color.WHITE);
deleteSourceCheckBox.setEnabled(false);
deleteSourceCheckBox.setForeground(Color.gray);
deleteSourceCheckBox.setFont(new Font("Calibri", Font.BOLD, 16));
deleteSourceCheckBox.setBackground(new Color(49, 49, 47));
GridBagConstraints gbc_deleteSourceCheckBox = new GridBagConstraints();
gbc_deleteSourceCheckBox.gridwidth = 1;
gbc_deleteSourceCheckBox.fill = GridBagConstraints.VERTICAL;
gbc_deleteSourceCheckBox.insets = new Insets(0, 0, 5, 5);
gbc_deleteSourceCheckBox.gridx = 1;
gbc_deleteSourceCheckBox.gridy = 0;
buttonPanel.add(deleteSourceCheckBox, gbc_deleteSourceCheckBox);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
close();
}
});
cancelButton.setFont(new Font("Calibri", Font.BOLD, 14));
cancelButton.setPreferredSize(new Dimension(100, 30));
GridBagConstraints gbc_generateButton = new GridBagConstraints();
gbc_generateButton.insets = new Insets(0, 0, 10, 0);
gbc_generateButton.gridx = 0;
gbc_generateButton.gridy = 1;
buttonPanel.add(cancelButton, gbc_generateButton);
acceptButton = new JButton("Accept");
acceptButton.setEnabled(false);
acceptButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
success = true;
if (comboBox.getSelectedItem().equals("Single File Transfer"))
{
if (sourceField.getText().length() > 0)
{
File sourceCheck = new File(sourceField.getText());
if (sourceCheck.exists() && sourceCheck.isFile())
{
// Success
sourceField.setBorder(defaultBorder);
errorFieldSourceField.setText("");
}
else
{
sourceField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldSourceField.setText("File does not exist.");
success = false;
}
}
else
{
sourceField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldSourceField.setText("Cannot be empty.");
success = false;
}
if (destField.getText().length() > 0)
{
destField.setBorder(defaultBorder);
errorFieldDest.setText("");
}
else
{
destField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldDest.setText("Cannot be empty.");
success = false;
}
if (success == true)
{
Job newJob = new Job("SingleJob", sourceField.getText(), destField.getText(), null, deleteSourceCheckBox.isSelected(), true);
// TODO: Start Job
}
}
else if (comboBox.getSelectedItem().equals("Continuous File Transfer"))
{
success = true;
if (jobCNameField.getText().length() > 0)
{
File jobNameCheck = new File("jobs/" + jobCNameField.getText() + ".job");
if (jobNameCheck.exists() && modify == false)
{
jobCNameField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldCJobName.setText("Job name already exists.");
success = false;
}
else
{
// Success
jobCNameField.setBorder(defaultBorder);
errorFieldCJobName.setText("");
}
}
else
{
jobCNameField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldCJobName.setText("Cannot be empty.");
success = false;
}
if (sourceCField.getText().length() > 0)
{
File sourceCheck = new File(sourceCField.getText());
if (sourceCheck.exists() && sourceCheck.isDirectory())
{
// Success
sourceCField.setBorder(defaultBorder);
errorFieldCSourceField.setText("");
}
else
{
sourceCField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldCSourceField.setText("Directory does not exist.");
success = false;
}
}
else
{
sourceCField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldCSourceField.setText("Cannot be empty.");
success = false;
}
if (destCField.getText().length() > 0)
{
destCField.setBorder(defaultBorder);
errorFieldCDest.setText("");
}
else
{
destCField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldCDest.setText("Cannot be empty.");
success = false;
}
try
{
Pattern.compile(fileFilterField.getText());
errorFieldFileRegex.setText("");
fileFilterField.setBorder(defaultBorder);
}
catch (PatternSyntaxException exception)
{
fileFilterField.setBorder(BorderFactory.createLineBorder(Color.red));
errorFieldFileRegex.setText("Invalid syntax.");
success = false;
}
if (success == true)
{
if (modify)
{
FileTransferUtility.jobList.remove(originalJob);
FileTransferGUI.clearJobFromTable(originalJob);
// TODO: Stop if running
}
if (comboBox.getSelectedItem().equals("Continuous File Transfer"))
{
Job newJob = new Job(jobCNameField.getText(), sourceCField.getText(), destCField.getText(), fileFilterField.getText(), deleteSourceCheckBox.isSelected(),
autostartCheckBox.isSelected());
JobHandler newJobHandler = new JobHandler(newJob);
FileTransferUtility.jobList.add(newJobHandler);
newJob.writeToFile("/jobs");
FileTransferGUI.addJobToTable(newJobHandler);
if (autostartCheckBox.isSelected())
{
// TODO: Start Job
}
}
close();
}
}
}
});
acceptButton.setPreferredSize(new Dimension(100, 30));
acceptButton.setFont(new Font("Calibri", Font.BOLD, 14));
GridBagConstraints gbc_closeButton = new GridBagConstraints();
gbc_closeButton.insets = new Insets(0, 0, 10, 0);
gbc_closeButton.gridx = 1;
gbc_closeButton.gridy = 1;
buttonPanel.add(acceptButton, gbc_closeButton);
JPanel entryPanel = new JPanel();
entryPanel.setBorder(null);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
Not really an answer, but I cannot reproduce your problem with my attempt at an MCVE. Note the use of arrays and collections (here maps) to simplify the code:
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyPanel extends JPanel {
public static final String[] LABELS = {"Job Name:", "Source Folder:", "Destination:", "File Regex:"};
private static final int TF_COLS = 20;
private static final Font LABEL_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 12);
private static final Font ERROR_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 8);
private static final String ERROR_MESSAGE = "Cannot Be Empty";
private static final Color BACKGROUND = new Color(49, 49, 47);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
private Map<String, JLabel> errorLabelMap = new HashMap<>();
public MyPanel() {
setLayout(new BorderLayout());
setBackground(BACKGROUND);
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
labelFieldPanel.setOpaque(false);
for (int i = 0; i < LABELS.length; i++) {
String text = LABELS[i];
JLabel label = new JLabel(text);
JTextField textField = new JTextField(TF_COLS);
JLabel errorLabel = new JLabel(" ");
label.setFont(LABEL_FONT);
label.setForeground(Color.WHITE);
errorLabel.setFont(ERROR_FONT);
errorLabel.setForeground(Color.RED);
labelFieldMap.put(text, textField);
errorLabelMap.put(text, errorLabel);
GridBagConstraints gbc = createLabelConstraint(i);
labelFieldPanel.add(label, gbc);
gbc = createTextFieldConstraints(i);
labelFieldPanel.add(textField, gbc);
gbc = createErrorLabelConstraints(i);
labelFieldPanel.add(errorLabel, gbc);
// add blank JLabel at the 0 position
gbc.gridx = 0;
labelFieldPanel.add(new JLabel(), gbc);
}
JButton acceptButton = new JButton("Accept");
acceptButton.setMnemonic(KeyEvent.VK_A);
acceptButton.addActionListener(e -> {
for (int i = 0; i < LABELS.length - 1; i++) {
String text = LABELS[i];
JTextField textField = labelFieldMap.get(text);
JLabel errorLabel = errorLabelMap.get(text);
if (textField.getText().trim().isEmpty()) {
errorLabel.setText(ERROR_MESSAGE);
} else {
errorLabel.setText(" ");
System.out.println(text + " " + textField.getText());
}
}
System.out.println();
});
JPanel btnPanel = new JPanel();
btnPanel.setOpaque(false);
btnPanel.add(acceptButton);
add(labelFieldPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
private GridBagConstraints createErrorLabelConstraints(int i) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2 * i + 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 5, 0, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
return gbc;
}
private GridBagConstraints createTextFieldConstraints(int i) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2 * i;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(5, 0, 0, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
return gbc;
}
private GridBagConstraints createLabelConstraint(int i) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2 * i;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 0, 5);
gbc.weightx = 0.0;
gbc.weighty = 0.0;
return gbc;
}
private static void createAndShowGui() {
MyPanel mainPanel = new MyPanel();
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Resulting GUI:
Since the problem is with your JTextField's Border, and since you can't reset the default border outright without running into problems, one solution is to create a CompoundBorder for your JTextField, the outer border a LineBorder that uses the same color as the JPanel's background color and the inner border being JTextField's default border. Then in your action listener, simply create a new compound border, one that uses a Color.RED outer border.
So when creating my JTextFields in the example below, I also create a CompoundBorder, giving it an outerBorder and innerBorder like so:
// create JTextField with TF_COLS int column count value
JTextField textField = new JTextField(TF_COLS);
// get the JTextField's default border and make it our inner border
Border innerBorder = textField.getBorder();
// create an outer LineBorder that uses the JPanel's background color
Border outerBorder = BorderFactory.createLineBorder(BACKGROUND);
// create the compound border with these two borders
CompoundBorder myBorder = BorderFactory.createCompoundBorder(outerBorder, innerBorder);
// and set the JTextField's border with it
textField.setBorder(myBorder);
Then in the JButton's ActionListener, get the JTextField's current border, our compound border, and change the outer border's line color. Simple:
// loop through all the JLabel texts
for (int i = 0; i < LABELS.length; i++) {
String text = LABELS[i]; // get the array item
// use it to get the JTextField associated with this String
JTextField textField = labelFieldMap.get(text);
// same for the error JLabel
JLabel errorLabel = errorLabelMap.get(text);
// get our current JTextField's border which is a compound border
CompoundBorder myBorder = (CompoundBorder) textField.getBorder();
// the insideBorder, the original JTextField's border, will be unchanged
Border insideBorder = myBorder.getInsideBorder();
// if the text field is empty (and not the last jtext field)
if (i < LABELS.length - 1 && textField.getText().trim().isEmpty()) {
errorLabel.setText(ERROR_MESSAGE); // set the error JLabel
// set txt field's color if we want
textField.setBackground(ERROR_BG_COLOR);
// okToTransfer = false;
// create a compound border, the outer border now a line border, RED
Border outsideBorder = BorderFactory.createLineBorder(Color.RED);
CompoundBorder newBorder = BorderFactory.createCompoundBorder(outsideBorder, insideBorder);
// set the JTextField's border to this one
textField.setBorder(newBorder);
} else {
// else all OK
errorLabel.setText(" ");
textField.setBackground(Color.WHITE);
// set the JTextField's border back to our original compound border
Border outsideBorder = BorderFactory.createLineBorder(BACKGROUND);
CompoundBorder newBorder = BorderFactory.createCompoundBorder(outsideBorder,
insideBorder);
textField.setBorder(newBorder);
}
System.out.println(text + " " + textField.getText());
}
For example:
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
#SuppressWarnings("serial")
public class MyPanel extends JPanel {
public static final String[] LABELS = { "Job Name:", "Source Folder:", "Destination:",
"File Regex:" };
private static final int TF_COLS = 30;
private static final Font LABEL_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 12);
private static final Font ERROR_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 8);
private static final String ERROR_MESSAGE = "Cannot Be Empty";
private static final Color BACKGROUND = new Color(49, 49, 47);
private static final String TITLE = "File Transfer Job Editor";
private static final Color TITLE_COLOR = new Color(243, 112, 33);
private static final Font TITLE_FONT = new Font("Arial", Font.BOLD, 28);
private static final Color ERROR_BG_COLOR = new Color(255, 220, 220);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
private Map<String, JLabel> errorLabelMap = new HashMap<>();
public MyPanel() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setForeground(TITLE_COLOR);
titleLabel.setFont(TITLE_FONT);
JPanel titlePanel = new JPanel();
titlePanel.setOpaque(false);
titlePanel.add(titleLabel);
titlePanel.setBorder(BorderFactory.createEtchedBorder());
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
labelFieldPanel.setOpaque(false);
int bGap = 3;
labelFieldPanel.setBorder(BorderFactory.createEmptyBorder(bGap, bGap, bGap, bGap));
for (int i = 0; i < LABELS.length; i++) {
String text = LABELS[i];
JLabel label = new JLabel(text);
JTextField textField = new JTextField(TF_COLS);
JLabel errorLabel = new JLabel(" ");
Border innerBorder = textField.getBorder();
Border outerBorder = BorderFactory.createLineBorder(BACKGROUND);
CompoundBorder myBorder = BorderFactory.createCompoundBorder(outerBorder, innerBorder);
textField.setBorder(myBorder);
label.setFont(LABEL_FONT);
label.setForeground(Color.WHITE);
errorLabel.setFont(ERROR_FONT);
errorLabel.setForeground(Color.RED);
labelFieldMap.put(text, textField);
errorLabelMap.put(text, errorLabel);
GridBagConstraints gbc = createLabelConstraint(i);
labelFieldPanel.add(label, gbc);
gbc = createTextFieldConstraints(i);
labelFieldPanel.add(textField, gbc);
gbc = createErrorLabelConstraints(i);
labelFieldPanel.add(errorLabel, gbc);
// add blank JLabel at the 0 position
gbc.gridx = 0;
labelFieldPanel.add(new JLabel(), gbc);
}
JButton acceptButton = new JButton("Accept");
acceptButton.setMnemonic(KeyEvent.VK_A);
acceptButton.addActionListener(e -> {
boolean okToTransfer = true;
for (int i = 0; i < LABELS.length; i++) {
String text = LABELS[i];
JTextField textField = labelFieldMap.get(text);
JLabel errorLabel = errorLabelMap.get(text);
CompoundBorder myBorder = (CompoundBorder) textField.getBorder();
Border insideBorder = myBorder.getInsideBorder();
if (i < LABELS.length - 1 && textField.getText().trim().isEmpty()) {
errorLabel.setText(ERROR_MESSAGE);
textField.setBackground(ERROR_BG_COLOR);
okToTransfer = false;
Border outsideBorder = BorderFactory.createLineBorder(Color.RED);
CompoundBorder newBorder = BorderFactory.createCompoundBorder(outsideBorder, insideBorder);
textField.setBorder(newBorder);
} else {
errorLabel.setText(" ");
textField.setBackground(Color.WHITE);
Border outsideBorder = BorderFactory.createLineBorder(BACKGROUND);
CompoundBorder newBorder = BorderFactory.createCompoundBorder(outsideBorder, insideBorder);
textField.setBorder(newBorder);
}
System.out.println(text + " " + textField.getText());
}
System.out.println();
if (okToTransfer) {
// TODO: transfer code here
// Window win = SwingUtilities.getWindowAncestor(MyPanel.this);
// win.dispose();
}
});
JButton cancelBtn = new JButton("Cancel");
cancelBtn.setMnemonic(KeyEvent.VK_C);
cancelBtn.addActionListener(e -> {
Window win = SwingUtilities.getWindowAncestor(MyPanel.this);
win.dispose();
});
int btnPanelGap = 15;
JPanel btnPanel = new JPanel(new GridLayout(1, 0, btnPanelGap, 0));
btnPanel.setBorder(BorderFactory.createEmptyBorder(4, btnPanelGap, 4, btnPanelGap));
btnPanel.setOpaque(false);
btnPanel.add(acceptButton);
btnPanel.add(cancelBtn);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
setBackground(BACKGROUND);
add(titlePanel);
add(labelFieldPanel);
add(btnPanel);
}
private GridBagConstraints createErrorLabelConstraints(int i) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2 * i + 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 5, 0, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
return gbc;
}
private GridBagConstraints createTextFieldConstraints(int i) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2 * i;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(5, 0, 0, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
return gbc;
}
private GridBagConstraints createLabelConstraint(int i) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2 * i;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 0, 5);
gbc.weightx = 0.0;
gbc.weighty = 0.0;
return gbc;
}
private static void createAndShowGui() {
MyPanel mainPanel = new MyPanel();
JDialog dialog = new JDialog((JFrame) null, "Job Editor", ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(mainPanel);
dialog.setResizable(false);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
System.exit(0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Suppose you have a panel initialized like so
JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setBounds(249, 165, 71, 227);
panel_playerBuffs.setOpaque(false);
panel_playerBuffs.setLayout(new GridBagLayout());
getContentPane().add(panel_playerBuffs);
And its layout is GridBayLayout with the following constraints
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
panel_playerBuffs.add(new JLabel("located at 1, 3"), gbc);
As you can see, this adds a JLabel at (1, 1) and another one at (1, 3). Now I'm trying to add a conditional somewhere else in the program to check whether or not there's a label at a given position. For instance, I would like to find out if the position (1, 2) has a label (in this case it doesn't). What method should I use for this?
How about using the GridBagLayout#getLayoutDimensions()
If the width or height of the given position is 0, there is empty.
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
public class GridBayLayoutSlotTest {
private JComponent makeUI() {
GridBagLayout layout = new GridBagLayout();
JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 3;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 3, 1"), gbc);
EventQueue.invokeLater(() -> {
int[][] a = layout.getLayoutDimensions();
System.out.println(Arrays.deepToString(a));
System.out.format("isEmpty(%d, %d): %s%n", 2, 1, isEmpty(a, 2, 1));
System.out.format("isEmpty(%d, %d): %s%n", 3, 1, isEmpty(a, 3, 1));
});
return panel_playerBuffs;
}
private static boolean isEmpty(int[][] a, int x, int y) {
int[] w = a[0];
int[] h = a[1];
return w[x] == 0 || h[y] == 0;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new GridBayLayoutSlotTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
i have GridBagLayout where I add a JLabel, a JTextfield. But it come out with unpredictable range
Source
public void siswa(){
panel_siswa = new JPanel(); //The Panel
panel_siswa.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.anchor = GridBagConstraints.CENTER;
label = new JLabel("CEK NILAI");
label.setFont(new Font("Arial", Font.BOLD, 18));
label_id = new JLabel("ID :");
label_name = new JLabel("Name :");
label_id2 = new JLabel("");
label_name2 = new JLabel("");
label_semester = new JLabel("Semester :");
label_semester2 = new JLabel("");
label_jurusan = new JLabel("Jurusan :");
label_jurusan2 = new JLabel("");
label_nilai1 = new JLabel(MP1);
label_nilai2 = new JLabel(MP2);
label_nilai3 = new JLabel(MP3);
label_nilai4 = new JLabel(MP4);
label_nilai5 = new JLabel(MP5);
tf_nilai1 = new JTextField();
tf_nilai2 = new JTextField();
tf_nilai3 = new JTextField();
tf_nilai4 = new JTextField();
tf_nilai5 = new JTextField();
send = new JButton("Send to my email");
gbc.weightx = 0.0;
gbc.gridwidth = 4;
gbc.gridx = 1;
gbc.gridy = 0;
panel_siswa.add(label,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
panel_siswa.add(label_id,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
panel_siswa.add(label_id2,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 1;
panel_siswa.add(label_jurusan,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = 1;
panel_siswa.add(label_jurusan2,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 2;
panel_siswa.add(label_name, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 2;
panel_siswa.add(label_name2, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 2;
panel_siswa.add(label_semester,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = 2;
panel_siswa.add(label_semester2,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 4;
panel_siswa.add(label_nilai1, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 4;
panel_siswa.add(tf_nilai1, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 5;
panel_siswa.add(label_nilai2, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 5;
panel_siswa.add(tf_nilai2, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 6;
panel_siswa.add(label_nilai3, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 6;
panel_siswa.add(tf_nilai3, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 7;
panel_siswa.add(label_nilai4, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 7;
panel_siswa.add(tf_nilai4, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 8;
panel_siswa.add(label_nilai5, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 8;
panel_siswa.add(tf_nilai5, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridy++;
panel_siswa.add(send);
}
}
Output
Problem Statement
I was expecting it will come out like picture below but its not. i think i have a problem on the source.
Question
is my source about gridbaglayout already great ? how to design it properly ?
You create a GUI like this with nested JPanels. Each JPanel can use the layout manager that's best suited for the particular JPanel.
Here's the GUI:
I created a main JPanel to hold all of the subordinate JPanels. The main JPanel uses a BoxLayout, page orientation.
The JPanel that holds the title uses a FlowLayout.
The JPanel that holds the student information uses a GridBagLayout.
The JPanel that holds the MP information uses a different GridBagLayout.
The JPanel that holds the submit button uses a FlowLayout.
Here's the code. This is what is meant by a short, self-contained, runnable example of the solution.
package com.ggl.testing;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class StudentDataEditor implements Runnable {
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
private static final Insets topInsets = new Insets(30, 10, 0, 10);
private Student student;
public static void main(String[] args) {
SwingUtilities.invokeLater(new StudentDataEditor());
}
public StudentDataEditor() {
this.student = new Student("00000017108", "Sutandi",
"Information Systems", 2);
}
#Override
public void run() {
JFrame frame = new JFrame("Student Data Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(createTitlePanel());
panel.add(createStudentPanel());
panel.add(createMPPanel());
panel.add(Box.createVerticalStrut(30));
panel.add(createEmailPanel());
panel.add(Box.createVerticalStrut(10));
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel();
JLabel titleLabel = new JLabel("CEK NILAI");
titleLabel.setFont(titleLabel.getFont().deriveFont(24F));
panel.add(titleLabel);
return panel;
}
private JPanel createStudentPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel idLabel = new JLabel("ID:");
addComponent(panel, idLabel, 0, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField idTextField = new JTextField(15);
idTextField.setEditable(false);
idTextField.setText(student.getId());
addComponent(panel, idTextField, 1, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel jurusanLabel = new JLabel("Jurusan:");
addComponent(panel, jurusanLabel, 2, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField jurusanTextField = new JTextField(15);
jurusanTextField.setEditable(false);
jurusanTextField.setText(student.getJurusan());
addComponent(panel, jurusanTextField, 3, gridy++, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel nameLabel = new JLabel("Name:");
addComponent(panel, nameLabel, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField nameTextField = new JTextField(15);
nameTextField.setEditable(false);
nameTextField.setText(student.getName());
addComponent(panel, nameTextField, 1, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel semesterLabel = new JLabel("Semester:");
addComponent(panel, semesterLabel, 2, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField semesterTextField = new JTextField(15);
semesterTextField.setEditable(false);
semesterTextField.setText(Integer.toString(student.getSemester()));
addComponent(panel, semesterTextField, 3, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return panel;
}
private JPanel createMPPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel mp1Label = new JLabel("MP1");
addComponent(panel, mp1Label, 0, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp1TextField = new JTextField(25);
addComponent(panel, mp1TextField, 1, gridy++, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp2Label = new JLabel("MP2");
addComponent(panel, mp2Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp2TextField = new JTextField(25);
addComponent(panel, mp2TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp3Label = new JLabel("MP3");
addComponent(panel, mp3Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp3TextField = new JTextField(25);
addComponent(panel, mp3TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp4Label = new JLabel("MP4");
addComponent(panel, mp4Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp4TextField = new JTextField(25);
addComponent(panel, mp4TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp5Label = new JLabel("MP5");
addComponent(panel, mp5Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp5TextField = new JTextField(25);
addComponent(panel, mp5TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return panel;
}
private JPanel createEmailPanel() {
JPanel panel = new JPanel();
JButton submitButton = new JButton("Send to my email");
panel.add(submitButton);
return panel;
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 0.0D, 0.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
public class Student {
private final int semester;
private final String id;
private final String name;
private final String jurusan;
public Student(String id, String name, String jurusan, int semester) {
this.id = id;
this.name = name;
this.jurusan = jurusan;
this.semester = semester;
}
public int getSemester() {
return semester;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getJurusan() {
return jurusan;
}
}
}
I am trying to make multiple lines of a JTextArea visible.I am using GridBagLayout to add the components. Here is a code snippet:
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class SSCE {
SSCE(){
JFrame f1=new JFrame();
GridBagLayout gbl=new GridBagLayout();
JButton btnAddAcc=new JButton("Add Acount");
JButton insertId=new JButton("Insert");
JButton insertTweet=new JButton("Insert2");
JButton tweetButton=new JButton("TweetButton");
JLabel accountStatusHeader=new JLabel("account status Header");
JLabel accountDisplayNameHeader=new JLabel("account displayname Header");
JLabel enterInterval=new JLabel("enter Interval!!");
final JTextArea accountDispName = new JTextArea(50, 50);
final JTextArea statusDisplay = new JTextArea(50, 50);
final JTextArea jTextAreaId = new JTextArea(20, 50);
final JTextArea jTextAreaTweets = new JTextArea(20, 50);
jTextAreaId.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.PINK, Color.GREEN));
final JTextArea tweetLog = new JTextArea(100, 100);
tweetLog.setPreferredSize(new Dimension(1000, 5000));
JScrollPane tweetLogPaneScroll = new JScrollPane(tweetLog);
JScrollPane idScrollPane = new JScrollPane(jTextAreaId);
JScrollPane tweetScrollPane = new JScrollPane(jTextAreaTweets);
final JTextField timeIntervalInput = new JTextField(20);
final JTextField tagIdInsertTextBox = new JTextField(50);
final JTextField tweetInsertTextBox = new JTextField(50);
f1.setLayout(gbl);
f1.add(btnAddAcc,makeGbc(0,0,1,2));
f1.add(accountDisplayNameHeader,makeGbc(1,0));
f1.add(accountStatusHeader,makeGbc(1,1));
f1.add(accountDispName,makeGbc(2,0));
f1.add(statusDisplay,makeGbc(2,1));
f1.add(enterInterval,makeGbc(3,0));
f1.add(timeIntervalInput,makeGbc(3,1));
f1.add(new JLabel("Twitter Ids"),makeGbc(4,0));
f1.add(new JLabel("Tweets"),makeGbc(4,1));
f1.add(idScrollPane,makeGbc(5,0,5));
f1.add(tweetScrollPane,makeGbc(5,1,5));
f1.add(tagIdInsertTextBox,makeGbc(10,0));
f1.add(tweetInsertTextBox,makeGbc(10,1));
f1.add(insertId,makeGbc(11,0));
f1.add(insertTweet,makeGbc(11,1));
f1.add(tweetButton,makeGbc(12,0,1,2));
f1.add(tweetLogPaneScroll,makeGbc(13,0,6,2));
f1.setSize(800,400);
f1.setVisible(true);
f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
accountDispName.setVisible(false);
statusDisplay.setVisible(false);
}
private GridBagConstraints makeGbc(int y, int x) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
// gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x,int gridheight) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x,int gridheight,int gridwidth) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
public static void main(String args[]){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SSCE a1;
a1 = new SSCE();
}
});
}
}
Please note the following lines:
f1.add(idScrollPane,makeGbc(5,0,5));
f1.add(tweetScrollPane,makeGbc(5,1,5));
In above, I am passing the third paramenter(the gridheight) as 5 but still I see only one row. I want to set the row span to 5.
And Also the following:
f1.add(tweetLogPaneScroll,makeGbc(13,0,6,2));
Here again, I am passing the third param(gridheight) as 6.But yet I see only one Row of textarea. So what is going wrong?? And whats the solution?
Your SSCCE helps me to see everything -- thanks! I've voted to open your question and have up-voted it. You're killing yourself with your unrealistic JTextArea row numbers, and then setting the size of your GUI. Get rid of all setSize(...) and setPreferredSize(...) method calls. Make your JTextArea row counts 5 or 10, not 50, not 100. Call pack() before setVisible(true).
For example, please see the changes I've made below as well as comments with !! in them. Note that I've tried to get rid of most of your magic numbers, but you still need to do the same with the column counts. I've also added text to your text components for the sake of debugging, so that I can see at a glance which text component goes with which variable. You'll of course not want to have this text present in the presentation code, but again, it's a useful debugging tool:
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class SSCE {
private static final int SMALL_ROWS = 5; // !! was 20!
private static final int BIG_ROWS = 10; // !! was 50!
SSCE() {
JFrame f1 = new JFrame();
GridBagLayout gbl = new GridBagLayout();
JButton btnAddAcc = new JButton("Add Acount");
JButton insertId = new JButton("Insert");
JButton insertTweet = new JButton("Insert2");
JButton tweetButton = new JButton("TweetButton");
JLabel accountStatusHeader = new JLabel("account status Header");
JLabel accountDisplayNameHeader = new JLabel(
"account displayname Header");
JLabel enterInterval = new JLabel("enter Interval!!");
final JTextArea accountDispName = new JTextArea("accountDispName JTA",
BIG_ROWS, 50);
final JTextArea statusDisplay = new JTextArea("statusDisplay JTA",
BIG_ROWS, 50);
final JTextArea jTextAreaId = new JTextArea("jTextAreaId JTA",
SMALL_ROWS, 50);
final JTextArea jTextAreaTweets = new JTextArea("jTextAreaTweets JTA",
SMALL_ROWS, 50);
jTextAreaId.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.PINK, Color.GREEN));
final JTextArea tweetLog = new JTextArea("tweetLog JTA", BIG_ROWS, 100); // was
// 100!
// !! tweetLog.setPreferredSize(new Dimension(1000, 5000));
JScrollPane tweetLogPaneScroll = new JScrollPane(tweetLog);
JScrollPane idScrollPane = new JScrollPane(jTextAreaId);
JScrollPane tweetScrollPane = new JScrollPane(jTextAreaTweets);
final JTextField timeIntervalInput = new JTextField(
"timeIntervalInput JTF", 20);
final JTextField tagIdInsertTextBox = new JTextField(
"tagIdInsertTextBox JTF", 50);
final JTextField tweetInsertTextBox = new JTextField(
"tweetInsertTextBox JTF", 50);
f1.setLayout(gbl);
f1.add(btnAddAcc, makeGbc(0, 0, 1, 2));
f1.add(accountDisplayNameHeader, makeGbc(1, 0));
f1.add(accountStatusHeader, makeGbc(1, 1));
f1.add(accountDispName, makeGbc(2, 0));
f1.add(statusDisplay, makeGbc(2, 1));
f1.add(enterInterval, makeGbc(3, 0));
f1.add(timeIntervalInput, makeGbc(3, 1));
f1.add(new JLabel("Twitter Ids"), makeGbc(4, 0));
f1.add(new JLabel("Tweets"), makeGbc(4, 1));
f1.add(idScrollPane, makeGbc(5, 0, 5));
f1.add(tweetScrollPane, makeGbc(5, 1, 5));
f1.add(tagIdInsertTextBox, makeGbc(10, 0));
f1.add(tweetInsertTextBox, makeGbc(10, 1));
f1.add(insertId, makeGbc(11, 0));
f1.add(insertTweet, makeGbc(11, 1));
f1.add(tweetButton, makeGbc(12, 0, 1, 2));
f1.add(tweetLogPaneScroll, makeGbc(13, 0, 6, 2));
// !! f1.setSize(800, 400);
f1.pack(); // !!
f1.setVisible(true);
f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
accountDispName.setVisible(false);
statusDisplay.setVisible(false);
}
private GridBagConstraints makeGbc(int y, int x) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
// gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
System.out.printf("gridwidth, gridheight: [%d, %d]%n", gbc.gridwidth,
gbc.gridheight);
return gbc;
}
private GridBagConstraints makeGbc(int y, int x, int gridheight) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x, int gridheight,
int gridwidth) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SSCE a1;
a1 = new SSCE();
}
});
}
}
This results in a GUI that looks like so:
Note, I would also change the GridBagConstraints for JTextFields from BOTH to HORIZONTAL.
Edit
You state in comment:
One more question if u dont mind answering.the TimeIntervalInput is appearing so wide although I have defined it to hold at max 20 chars.Any solution to that?
You need to continue to play with your grid bag constraints as the ones you're using are quite restrictive. For example, note what happens when I use more exacting constraints on the GBC for that JTextField:
GridBagConstraints gbc = makeGbc(3, 1);
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
f1.add(timeIntervalInput, gbc);