Does GridBagLayout affect JLabel images? - java

Currently trying to add a header image to my JFrame based GUI, I've developed the layout of the project and everything looks good, but every time I run the project the image does not load (no error messages).
My code (partial):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class DeltaFlightFrame extends JFrame implements ActionListener, ChangeListener{
//<SNIPPED CODE FOR EASE OF VIEWING>
//Labels for inputs
//<SNIPPED CODE FOR EASE OF VIEWING>
private JLabel deltaLogo;
//icon
private Icon logo;
//<SNIPPED CODE FOR EASE OF VIEWING>
DeltaFlightFrame() {
GridBagConstraints layoutConst = null;
//<SNIPPED CODE FOR EASE OF VIEWING>
setTitle("Delta Flight Price Estimator");
//<SNIPPED CODE FOR EASE OF VIEWING>
//initialize delta logo
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height" + logo.getIconHeight());
System.out.println("Width" + logo.getIconWidth());
//<SNIPPED CODE FOR EASE OF VIEWING>
// Create frame and add components using GridBagLayout
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
//layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 0;
//layoutConst.gridwidth = 4;
add(deltaLogo, layoutConst);
//<SNIPPED CODE FOR EASE OF VIEWING>
}
//TODO: this
public void stateChanged(ChangeEvent event) {
}
//TODO, also: this
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception ignored){}
DeltaFlightFrame myFrame = new DeltaFlightFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
My full code (I didn't want to put it all, it's a disgusting mess and I'm a first year student so this isn't... nice... hahaha):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class DeltaFlightFrame extends JFrame implements ActionListener, ChangeListener{
//Text Fields
private JTextField desCityField; // Holds destination city abbreviation,
private JTextField depCityField; // Holds departure city abbreviation.
private JTextField finalOutputField; //Shows final price
//Drop Down
//=====TODO
//Labels for inputs
private JLabel desCityLabel;
private JLabel depCityLabel;
private JLabel tripTypeLabel;
private JLabel seatTypeLabel;
private JLabel adultTravelerCountLabel;
private JLabel childTravelerCountLabel;
private JLabel finalOutput; //final price
private JLabel flightTitle;
private JLabel passengerTitle;
private JLabel deltaLogo;
//icon
private Icon logo;
//dropdown
String[] seatClassChoices = { "Basic Economy", "Business+ Comfort", "First Class" };
private JComboBox seatClassDrop;
//JSpinners
private JSpinner adultTravelerCount;
private JSpinner childTravelerCount;
//radio button
private JRadioButton oneWay;
private JRadioButton roundTrip;
//Buttons
private JButton calculateButton;
/* Constructor creates GUI components and adds GUI components
using a GridBagLayout. */
DeltaFlightFrame() {
GridBagConstraints layoutConst = null;
SpinnerNumberModel spinnerModelAdult = null;
SpinnerNumberModel spinnerModelChild = null;
String desInit = "ATL";
String depInit = "JFK";
double priceInit = 150.00;
int passCountMin = 0;
int passCountMax = 9;
int passAdultInit = 1;
int passChildInit = 0;
//Set Frame Title
setTitle("Delta Flight Price Estimator");
//create labels
depCityLabel = new JLabel("Departure City: ");
desCityLabel = new JLabel("Destination City: ");
tripTypeLabel = new JLabel("Trip Type: ");
seatTypeLabel = new JLabel("Seat Class: ");
adultTravelerCountLabel = new JLabel("Travelling Adults: ");
childTravelerCountLabel = new JLabel("Travelling Children: ");
finalOutput = new JLabel("Price: ");
flightTitle = new JLabel("Flight Information");
flightTitle.setFont(new Font("Sans-Serif", Font.BOLD, 20));
passengerTitle = new JLabel("Passenger Information");
passengerTitle.setFont(new Font("Sans-Serif", Font.BOLD, 20));
//create dropdown
seatClassDrop = new JComboBox<String>(seatClassChoices);
//create spinners
spinnerModelAdult = new SpinnerNumberModel(passAdultInit, passCountMin, passCountMax, 1);
adultTravelerCount = new JSpinner(spinnerModelAdult);
spinnerModelChild = new SpinnerNumberModel(passChildInit, passCountMin, passCountMax, 1);
childTravelerCount = new JSpinner(spinnerModelChild);
//initialize delta logo
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height" + logo.getIconHeight());
System.out.println("Width" + logo.getIconWidth());
//initialize text fields
desCityField = new JTextField("JFK");
desCityField.setEditable(true);
desCityField.setDocument(new LengthRestrictedDocument(3));
desCityField.setColumns(3);
depCityField = new JTextField("ATL");
depCityField.setEditable(true);
depCityField.setDocument(new LengthRestrictedDocument(3));
depCityField.setColumns(3);
//radio button
oneWay = new JRadioButton("One Way");
roundTrip = new JRadioButton("Round Trip");
//button
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
ButtonGroup tripType = new ButtonGroup();
tripType.add(oneWay);
tripType.add(roundTrip);
// Create frame and add components using GridBagLayout
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
//layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 0;
//layoutConst.gridwidth = 4;
add(deltaLogo, layoutConst);
setLayout(new GridBagLayout());
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 1;
layoutConst.gridwidth = 4;
add(flightTitle, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(desCityLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 2;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(depCityLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 1;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(desCityField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 3;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
add(depCityField, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 0;
layoutConst.gridy = 4;
layoutConst.gridwidth = 1;
add(roundTrip, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 2;
layoutConst.gridy = 4;
layoutConst.gridwidth = 2;
add(seatClassDrop, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 1, 1);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 0;
layoutConst.gridy = 5;
layoutConst.gridwidth = 1;
add(oneWay, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(50, 10, 1, 1);
layoutConst.anchor = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 6;
layoutConst.gridwidth = 4;
add(passengerTitle, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 1);
layoutConst.fill = GridBagConstraints.LINE_START;
layoutConst.gridx = 0;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(adultTravelerCountLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 1;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(adultTravelerCount, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.LINE_START;
layoutConst.gridx = 2;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(childTravelerCountLabel, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.insets = new Insets(10, 10, 10, 10);
layoutConst.fill = GridBagConstraints.HORIZONTAL;
layoutConst.gridx = 3;
layoutConst.gridy = 7;
layoutConst.gridwidth = 1;
add(childTravelerCount, layoutConst);
}
//TODO: this
public void stateChanged(ChangeEvent event) {
}
//TODO, also: this
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception ignored){}
DeltaFlightFrame myFrame = new DeltaFlightFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
}
I did do some messing around, here:
logo = new ImageIcon("../img/logo.png");
deltaLogo = new JLabel(logo);
System.out.println("Height: " + logo.getIconHeight());
System.out.println("Width: " + logo.getIconWidth());
And the output of that was:
Height: -1
Width: -1
Which I do find odd, if that's a starting point.
SO, my question is: Does my setup with GridBagLayout affect the display of the of the JLabel image?

Using the website provided by #camickr, I was able to successfully render the image using their "createImageIcon" method.

Related

Java Swing GridBagLayout JTextField Changing size after adding error message

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());
}
}

For loop for JLabel in GridBagConstraints confusion, GUI displays black symbol instead of days

Below you will find my code at my attempt to create a GUI in Java for a calendar. I only need to create a month GUI for October. I do not need any active or dynamic setup it simply needs to be static.
It just needs to display the month of October. However, I have ran into issues I am not familiar with that I never ran into just printing out to the terminal.
Using a the AWT, and the Swing components is new for me.
My main issue is that the loop I have created which is supposed to create the days of the calander, is printing out a weird dark shape instead of the numbers.
I know it has something to do with the JLabel, I tried converting the int to a string but I feel like maybe I am missing something that is over my head.
I apologize for all the code but I want you all to see all of it to see if my mistake lays elsewhere.
The mistake is in my loop however which is right below this.
layoutConst = new GridBagConstraints();
for (int y = 2; y <= 6; y++) {
for (int x = 0; x <= 6; x++) {
layoutConst.gridx = x;
layoutConst.gridy = y;
for (int a = 1; a <= 31; a++) {
layoutConst.insets = new Insets(10,10,10,10);
this.add(new JLabel(String.valueOf(a)), layoutConst);
}
}
}
Here is the rest of the code for the class as well.
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.*;
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.BorderFactory;
import java.util.Arrays;
public class CalendarFrame extends JFrame {
public CalendarFrame() {
JLabel month = null;
GridBagConstraints layoutConst = null;
month = new JLabel ("October");
this.setTitle("Monthly Calendar");
this.setLayout(new GridBagLayout() );
// create gb contstraints
layoutConst = new GridBagConstraints();
layoutConst.gridx = 3;
layoutConst.gridy = 0;
layoutConst.insets = new Insets (0,0,0,0);
this.add(month, layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 0;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("S "), layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 1;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("M "), layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 2;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("T"), layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 3;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("W"), layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 4;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("T"), layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 5;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("F "), layoutConst);
layoutConst = new GridBagConstraints();
layoutConst.gridx = 6;
layoutConst.gridy = 1;
layoutConst.insets = new Insets(10, 10, 10, 10);
this.add(new JLabel("S"), layoutConst);
//GridBagConstraints gbc = new GridBagConstraints();
layoutConst = new GridBagConstraints();
for (int y = 2; y <= 6; y++) {
for (int x = 0; x <= 6; x++) {
layoutConst.gridx = x;
layoutConst.gridy = y;
for (int a = 1; a <= 31; a++) {
//String b = String.valueOf(a);
layoutConst.insets = new Insets(10,10,10,10);
this.add(new JLabel(String.valueOf(a)), layoutConst);
//this.add(new JLabel(Integer.toString(a)), layoutConst);
//this.add(new JLabel(b), gbc);
}
}
}
}// end calendar frame
}// end class
Below this is the picture of my output. Why am I getting these weird symbols?

Componenets alignment in GridBagLayout

I am using GridBagLayout to align components. Actually, i have two buttons which i want to align like this:
Desired layout:
But the following code results in the following layout:
Resulted layout:
My code:
iconAdd = new ImageIcon(getClass().getResource("../images/add.png"));
add = new JButton(iconAdd);
add.setPreferredSize(new Dimension(130, 100));
add.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
add.setCursor(Cursor.getPredefinedCursor(12));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
pane.add(add, gbc);
iconSearch = new
ImageIcon(getClass().getResource("../images/search.png"));
search = new JButton(iconSearch);
search.setCursor(Cursor.getPredefinedCursor(12));
search.setPreferredSize(new Dimension(130, 100));
search.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
pane.add(search, gbc);
Any help would be highly appreciated.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayoutDemo extends JFrame{
GridBagLayoutDemo(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWeights = new double[]{1.0, 1.0, 1.0};
gridBagLayout.columnWidths = new int[]{0,0,300};
getContentPane().setLayout(gridBagLayout);
JButton button1 = new JButton("Long Button");
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.HORIZONTAL;
c1.weightx = 0.0;
c1.gridwidth = 3;
c1.gridx = 0;
c1.gridy = 0;
getContentPane().add(button1, c1);
JButton button2 = new JButton("Button 2");
GridBagConstraints c2 = new GridBagConstraints();
c2.weightx = 0.5;
c2.gridx = 0;
c2.gridy = 1;
getContentPane().add(button2, c2);
JButton button3 = new JButton("Button 3");
GridBagConstraints c3 = new GridBagConstraints();
c3.weightx = 0.5;
c3.gridx = 1;
c3.gridy = 1;
getContentPane().add(button3, c3);
pack();
setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GridBagLayoutDemo();
}
});
}
}
gbc.weightx = 1;
You are telling the layout to give extra space to each component. So essentially each component becomes half the size of the frame.
You really only want that constraint set for the second button, so it takes up all the remaining space.
Read the section from the Swing tutorial on How to Use GridBagLayout which explains how the weightx/y constraints should be used.
Also, an easier solution would be do just use a FlowLayout. Create a panel with a FlowLayout. Add the buttons to the panel. Then add the panel to the BorderLayout.PAGE_START of the frame.

GUI won't display two seperate scrollpanes

As you can see in my code, there are two scroll panes at the bottom. I need my gui to show both of these scroll panes on the right side, the smaller one(displaying the current amount of money the player has, this one I need to stay one line thick) and the second one, which will be constantly spitting out information of the player's rolls on the bottom.
Also how do I make it so that my combo box listener will give every item a 10 to its output to start out with then when it is being sent out it gives each 1 more so that they have their unique number starting at 11 then 12, 13, and so on.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dicebot extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
private JButton btnConfirm;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dicebot frame = new dicebot();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dicebot() {
setTitle("Dice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldStartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMultiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_textFieldPassword = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldOdds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMaxBet = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}else if (e.getSource() == btnConfirm){
Dicebotcode dbc = new Dicebotcode();
dbc.dbc();
}
}
}
Two things...
One, if you've added the same scroll pane twice...
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
^--- Note no "l"
And, even if you have added the two scroll pane instances, you've added them to the same place, BorderLayout.CENTER
BorderLayout only allows a single component to be added to one of the available positions it supports, so, in this case, only the second scroll pane would be visible

How do I set the size of a JButton?

The button takes up the whole screen, and I try using setSize() but that doesn't appear to be doing anything. Here's my code so far:
JButton start = new JButton("PLAY");
start.setSize(new Dimension(100, 100));
myFrame.add(start);
By default, JFrame has BorderLayout with CENTER alignment. Thats why single component will takes full screen. So add a suitable Layout Manager to JFrame.
For details, go through, How to Use Various Layout Managers.
you can try using GridBagLayout to set it's size within a Container.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test extends JPanel{
private static final long serialVersionUID = 1L;
JButton b1, b2, b3, b4, b5;
GridBagConstraints g = new GridBagConstraints();
public test() {
setLayout(new GridBagLayout());
g.insets = new Insets(1, 1, 1, 1);
b1 = new JButton("Button 1");
g.gridx = 0;
g.gridy = 6;
g.gridwidth = 2;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b1, g);
b2 = new JButton("Button 2");
g.gridx = 0;
g.gridy = 0;
g.gridwidth = 3;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b2, g);
b3 = new JButton("Button 3");
g.gridx = 2;
g.gridy = 2;
g.gridwidth = 1;
g.gridheight = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b3, g);
b4 = new JButton("Button 4");
g.gridx = 6;
g.gridy = 0;
g.gridheight = 3;
g.gridwidth = 1;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b4, g);
b5 = new JButton("Button 5");
g.gridx = 1;
g.gridy = 3;
g.gridheight = 1;
g.gridwidth = 2;
g.fill = GridBagConstraints.HORIZONTAL;
g.fill = GridBagConstraints.VERTICAL;
add(b5, g);
}
public static void main(String[] args) {
test t = new test();
JFrame frame = new JFrame("test");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.add(t);
}
}

Categories