Swing Error with GridBagLayout - java

I am writing a mutlientry dialog box using the gridbag layout manager, when I am trying to run this program it is showing me some weird error which I never encountered.
public class MultiEntryDlg extends JDialog {
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel() ;
private DButton pb_OK = null ;
private DButton pb_CANCEL = null ;
private JLabel lb_Name = null ;
private JTextField ef_name = null ;
private JLabel lb_taxonomyValue = null;
private JTextField ef_taxonomyValue = null ;
private JLabel lb_subscriptionKey = null ;
private JTextField ef_subscriptionKey = null ;
private JCheckBox cb_subscribable = null ;
private JTextField ef_alias = null ;
private JLabel lb_alias = null ;
private JLabel lb_orderNumber = null ;
private JTextField ef_orderNum = null ;
private JTextAreaCounter mle_DESCRIPTION_COUNTER = null ;
private SpellCheckPanel spellCheckPanel = null ;
private JLabel lb_contentLocation = null ;
private JComboBox contentlocCombo = null ;
private JLabel lb_brandSubGrp = null ;
private JComboBox brandSubGrpCombo = null ;
private JLabel lb_fixedLocation = null ;
private JComboBox fixedlocCombo = null ;
private JLabel lb_taxonomyType = null ;
private JComboBox taxonomyCombo = null ;
private NoTabJTextArea mle_DESCRIPTION = null ;
private MultiEntryDlg(){
creatAndShowGUI();
}
public void actionPerformed ( ActionEvent e ) {
if ( ( e.getSource() == pb_OK )
dispose();
else if (e.getSource() ==pb_CANCEL)
dispose();
}
private void creatAndShowGUI(){
initializeBasicProperty();
addComponents();
}
private void addComponents() {
// TODO Auto-generated method stub
lb_Name = new JLabel("Name (Max 75 char)");
addLeftAlign(lb_Name, 0, 1);
ef_name = new JTextField(10);
addMergeColumn(ef_name, 1, 1, 2);
spellCheckPanel = new SpellCheckPanel();
spellCheckPanel.setTextComponent(ef_name);
addCenterAlign(spellCheckPanel, 3, 1);
lb_alias = new JLabel("Alias");
addLeftAlign(lb_alias, 0, 2);
ef_alias = new JTextField(10);
addMergeColumn(ef_alias, 1, 2, 3);
lb_orderNumber = new JLabel("Order Number");
addLeftAlign(lb_orderNumber, 0, 3);
ef_orderNum = new JTextField(10);
addCenterAlign(ef_orderNum, 1, 3);
lb_contentLocation = new JLabel("Content Location");
addCenterAlign(lb_contentLocation, 2, 3);
contentlocCombo = new JComboBox();
addCenterAlign(contentlocCombo, 3, 3);
lb_brandSubGrp = new JLabel("Brand Sub Group");
addLeftAlign(lb_brandSubGrp, 0, 4);
brandSubGrpCombo = new JComboBox();
addCenterAlign(brandSubGrpCombo, 1, 4);
lb_fixedLocation = new JLabel("Fixed Location");
addLeftAlign(lb_fixedLocation, 2, 4);
fixedlocCombo = new JComboBox();
addCenterAlign(fixedlocCombo, 3, 4);
lb_taxonomyValue = new JLabel("Taxonomy Value");
addLeftAlign(lb_taxonomyValue, 0, 5);
ef_taxonomyValue = new JTextField(10);
addCenterAlign(ef_taxonomyValue, 1, 5);
lb_taxonomyType = new JLabel ("Taxonomy Type");
addLeftAlign(lb_taxonomyType, 2, 5);
taxonomyCombo = new JComboBox();
addCenterAlign(taxonomyCombo, 3, 5);
cb_subscribable = new JCheckBox("Subscribable");
addLeftAlign(cb_subscribable, 0, 6);
lb_subscriptionKey = new JLabel("Subscription Key");
addCenterAlign(lb_Name, 2, 6);
ef_subscriptionKey = new JTextField(10);
addCenterAlign(ef_subscriptionKey, 3, 6);
addControlButton();
}
public static void main(String[] args) {
try {
MultiEntryDlg dialog = new MultiEntryDlg();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
private void addControlButton() {
// TODO Auto-generated method stub
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPanel,BorderLayout.SOUTH);
pb_OK = new DButton(Str.getStr(STR_OK));
pb_CANCEL = new DButton(Str.getStr(STR_CANCEL));
pb_OK.addActionListener(this);
pb_CANCEL.addActionListener(this);
buttonPanel.add(pb_OK);
buttonPanel.add(pb_CANCEL);
}
private void addLeftAlign (Component component , int x, int y){
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(0, 0, 5, 5);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridx = x;
constraints.gridy = y;
contentPanel.add(component, constraints);
}
private void addCenterAlign (Component component , int x ,int y){
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(0, 0, 5, 0);
constraints.anchor = GridBagConstraints.HORIZONTAL;
constraints.gridx = x;
constraints.gridy = y;
contentPanel.add(component, constraints);
}
private void addMergeColumn (Component component , int x, int y, int weight){
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(0, 0, 5, 5);
constraints.anchor = GridBagConstraints.HORIZONTAL;
constraints.gridx = x;
constraints.gridy = y;
constraints.gridwidth = weight;
contentPanel.add(component, constraints);
}
private void initializeBasicProperty() {
// TODO Auto-generated method stub
setBounds(100, 100, 500, 250);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
GridBagLayout gbl_contentPanel = new GridBagLayout();
gbl_contentPanel.columnWidths = new int[]{0, 0, 0};
gbl_contentPanel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_contentPanel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_contentPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
contentPanel.setLayout(gbl_contentPanel);
}
}
I am getting following error.
strArray in strObject is null. String Index:1 Language Ind:0
strArray in strObject is null. String Index:2 Language Ind:0
Exception in thread "main" java.lang.StackOverflowError
at com.ibm.nzna.projects.qit.gui.MultiEntryDlg.setVisible(MultiEntryDlg.java:523)
at com.ibm.nzna.projects.qit.gui.MultiEntryDlg.setVisible(MultiEntryDlg.java:523)
at com.ibm.nzna.projects.qit.gui.MultiEntryDlg.setVisible(MultiEntryDlg.java:523)
etc..
Could anyone help me with this error?

This doesn't answer your question directly. But really don't use GridBagLayout.. its a crazy layoutmanager. Look at the amount of code you need to write to layout your components. IMO, thats the reason why many people moved away from not writing Swing application.
Instead use the jgoodies form layout. Here it is: http://www.jgoodies.com/freeware/forms/
If you haven't heard about it.. its a very simple layout manager. You can specify the column and row specs as simple strings. You can use existing PanelBuider or FormBuilder in the library or make one of your own. I have made one here:
http://code.google.com/p/swingobjects/source/browse/SwingObjects/src/org/aesthete/swingobjects/view/SwingObjFormBuilder.java

Related

Program runs good in IDE but not as an exported file [duplicate]

This question already has answers here:
I can run .jar files through cmd, but I cannot double click them [closed]
(7 answers)
Closed 2 years ago.
My MineSweeper project works perfectly in the IDE, but it doesn't work when I export is as "Runnable Jar File" in Eclipse and executing it afterwards.
My MANIFEST.MF
I also tried to navigate via cmd there and do javac Minesweeper.jar.
Console says it cant find the command "javac".
If i cd into my folder and just do java Minesweeper.jar it says: "Cant find or load Mainclass Minesweeper.jar"
This is my code in which the main method is located:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JSpinner;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Font;
import javax.swing.ImageIcon;
#SuppressWarnings("serial")
public class Anzeigen extends JFrame {
private JPanel contentPane;
int spaltenAnzahl,bombenAnzahl,reihenAnzahl;
Logik logik;
public Anzeigen() {
logik = new Logik();
reihenAnzahl = 2;
spaltenAnzahl = 2;
bombenAnzahl = 1;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(800, 300, 700, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblReihenanzahl = new JLabel("ReihenAnzahl");
lblReihenanzahl.setFont(new Font("Tahoma", Font.BOLD, 15));
GridBagConstraints gbc_lblReihenanzahl = new GridBagConstraints();
gbc_lblReihenanzahl.insets = new Insets(0, 0, 5, 5);
gbc_lblReihenanzahl.gridx = 4;
gbc_lblReihenanzahl.gridy = 0;
contentPane.add(lblReihenanzahl, gbc_lblReihenanzahl);
JLabel lblSpaltenanzahl = new JLabel("SpaltenAnzahl");
lblSpaltenanzahl.setFont(new Font("Tahoma", Font.BOLD, 15));
GridBagConstraints gbc_lblSpaltenanzahl = new GridBagConstraints();
gbc_lblSpaltenanzahl.insets = new Insets(0, 0, 5, 5);
gbc_lblSpaltenanzahl.gridx = 7;
gbc_lblSpaltenanzahl.gridy = 0;
contentPane.add(lblSpaltenanzahl, gbc_lblSpaltenanzahl);
JLabel lblAnzahlminen = new JLabel("AnzahlMinen");
lblAnzahlminen.setFont(new Font("Tahoma", Font.BOLD, 15));
GridBagConstraints gbc_lblAnzahlminen = new GridBagConstraints();
gbc_lblAnzahlminen.insets = new Insets(0, 0, 5, 0);
gbc_lblAnzahlminen.gridx = 9;
gbc_lblAnzahlminen.gridy = 0;
contentPane.add(lblAnzahlminen, gbc_lblAnzahlminen);
JSpinner spinner_1 = new JSpinner();
spinner_1.setFont(new Font("Tahoma", Font.PLAIN, 20));
GridBagConstraints gbc_spinner_1 = new GridBagConstraints();
gbc_spinner_1.gridheight = 4;
gbc_spinner_1.fill = GridBagConstraints.BOTH;
gbc_spinner_1.insets = new Insets(0, 0, 5, 5);
gbc_spinner_1.gridx = 7;
gbc_spinner_1.gridy = 1;
contentPane.add(spinner_1, gbc_spinner_1);
JSpinner spinner_2 = new JSpinner();
spinner_2.setFont(new Font("Tahoma", Font.PLAIN, 20));
GridBagConstraints gbc_spinner_2 = new GridBagConstraints();
gbc_spinner_2.fill = GridBagConstraints.BOTH;
gbc_spinner_2.gridheight = 4;
gbc_spinner_2.insets = new Insets(0, 0, 5, 0);
gbc_spinner_2.gridx = 9;
gbc_spinner_2.gridy = 1;
contentPane.add(spinner_2, gbc_spinner_2);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon(Anzeigen.class.getResource("/javax/swing/plaf/metal/icons/Warn.gif")));
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.fill = GridBagConstraints.BOTH;
gbc_label.insets = new Insets(0, 0, 0, 5);
gbc_label.gridx = 6;
gbc_label.gridy = 9;
label.setVisible(false);
JSpinner spinner = new JSpinner();
spinner.setFont(new Font("Tahoma", Font.PLAIN, 20));
GridBagConstraints gbc_spinner = new GridBagConstraints();
gbc_spinner.fill = GridBagConstraints.BOTH;
gbc_spinner.gridheight = 4;
gbc_spinner.insets = new Insets(0, 0, 5, 5);
gbc_spinner.gridx = 4;
gbc_spinner.gridy = 1;
contentPane.add(spinner, gbc_spinner);
spinner.setValue(2);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.fill = GridBagConstraints.BOTH;
gbc_lblNewLabel.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel.gridx = 7;
gbc_lblNewLabel.gridy = 9;
lblNewLabel.setVisible(false);
contentPane.add(lblNewLabel, gbc_lblNewLabel);
spinner_1.setValue(2);
spinner_2.setValue(1);
JButton btnStart = new JButton("Start");
btnStart.setFont(new Font("Tahoma", Font.PLAIN, 20));
btnStart.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
lblNewLabel.setVisible(false);
spaltenAnzahl = (int) spinner_1.getValue();
reihenAnzahl = (int) spinner.getValue();
bombenAnzahl = (int) spinner_2.getValue();
System.out.println("SpaltenAnzahl: "+spaltenAnzahl);
System.out.println("ReihenAnzahl: "+reihenAnzahl);
System.out.println("BombenAnzahl: "+bombenAnzahl);
if(bombenAnzahl > spaltenAnzahl * reihenAnzahl) {
label.setVisible(true);
lblNewLabel.setVisible(true);
lblNewLabel.setText("Mehr Minen oder mehr Reihen/Spalten");
}
else if(reihenAnzahl * spaltenAnzahl >= 2500) {
lblNewLabel.setText("Zu Groß!");
lblNewLabel.setVisible(true);
}
else {
logik.inizialisieren(reihenAnzahl,spaltenAnzahl,bombenAnzahl);
setVisible(false);
}
}
});
JLabel lblDirektStarten = new JLabel("Direkt Starten:");
lblDirektStarten.setFont(new Font("Tahoma", Font.BOLD, 15));
GridBagConstraints gbc_lblDirektStarten = new GridBagConstraints();
gbc_lblDirektStarten.insets = new Insets(0, 0, 5, 5);
gbc_lblDirektStarten.gridx = 1;
gbc_lblDirektStarten.gridy = 7;
contentPane.add(lblDirektStarten, gbc_lblDirektStarten);
GridBagConstraints gbc_btnStart = new GridBagConstraints();
gbc_btnStart.insets = new Insets(0, 0, 5, 0);
gbc_btnStart.gridx = 9;
gbc_btnStart.gridy = 7;
contentPane.add(btnStart, gbc_btnStart);
JButton btnNewButton = new JButton("Einfach");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
logik.inizialisieren(9, 9, 10);
setVisible(false);
}
});
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.fill = GridBagConstraints.VERTICAL;
gbc_btnNewButton.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 8;
contentPane.add(btnNewButton, gbc_btnNewButton);
JButton btnNewButton_1 = new JButton("Mittel");
btnNewButton_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
setVisible(false);
logik.inizialisieren(16, 16, 40);
}
});
GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
gbc_btnNewButton_1.fill = GridBagConstraints.VERTICAL;
gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_1.gridx = 1;
gbc_btnNewButton_1.gridy = 8;
contentPane.add(btnNewButton_1, gbc_btnNewButton_1);
JButton btnNewButton_2 = new JButton("Schwer");
btnNewButton_2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
setVisible(false);
logik.inizialisieren(16, 30, 99);
}
});
GridBagConstraints gbc_btnNewButton_2 = new GridBagConstraints();
gbc_btnNewButton_2.fill = GridBagConstraints.BOTH;
gbc_btnNewButton_2.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_2.gridx = 2;
gbc_btnNewButton_2.gridy = 8;
contentPane.add(btnNewButton_2, gbc_btnNewButton_2);
contentPane.add(label, gbc_label);
}
public static void main(String[] args) {
Anzeigen frame = new Anzeigen();
frame.setVisible(true);
}
}
The way to run a runnable jar is with the -jar parameter, e.g. java -jar Minesweeper.jar . Otherwise it assumes you mean a class name on the CLASSPATH environment variable, which you shouldn't rely on.
Figured it out i had to change stuff in my registry
I can run .jar files through cmd, but I cannot double click them
sry for asking this another time when there is an answer already..

putting a JPanel in a JFrame: setContentPane() and add() both work?

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.

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

JLabel's setText() is not working when called outside of the class that created it

Can a setText() operation of a JLabel be called outside a JPanel ou the class that created it? Because i have to change my JLabel on a Singleton i created. When i use the setText() function, the text attribute of the JLabel is changed(i can see it from debug), but visually it is still the same old text.
But when i change the text from inside the JPanel that created the JLabel, it works... But i don't want this. I have to make setText() work outside of a JPanel. I am calling it from a Singleton which is created inside the JPanel construction.
The class that contains my JLabel is TelaPrincipal. And on it´s constructor, i change the text of the JLabel via a "setText()" and it workds just fine:
public TelaPrincipal() {
setTitle("codefont2file");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{12, 92, 42, 42, 92};
gbl_contentPane.rowHeights = new int[]{19, 19, 19, 19, 19, 19, 19, 19};
gbl_contentPane.columnWeights = new double[]{0.2, 1.0, 0.1, 0.1, 0.6};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE, 0.0};
contentPane.setLayout(gbl_contentPane);
JLabel TituloTela = DefaultComponentFactory.getInstance().createTitle("CodeFont 2 File");
TituloTela.setFont(new Font("Tahoma", Font.BOLD, 15));
TituloTela.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_TituloTela = new GridBagConstraints();
gbc_TituloTela.gridwidth = 7;
gbc_TituloTela.gridheight = 1;
gbc_TituloTela.insets = new Insets(0, 0, 5, 5);
gbc_TituloTela.anchor = GridBagConstraints.NORTH;
gbc_TituloTela.fill = GridBagConstraints.HORIZONTAL;
gbc_TituloTela.gridx = 0;
gbc_TituloTela.gridy = 0;
contentPane.add(TituloTela, gbc_TituloTela);
JLabel descricao_software = DefaultComponentFactory.getInstance().createLabel("Bem vindo ao Codefont2File! Escolha seu projeto que converteremos");
GridBagConstraints gbc_descricao_software = new GridBagConstraints();
gbc_descricao_software.insets = new Insets(0, 0, 5, 0);
gbc_descricao_software.gridx = 0;
gbc_descricao_software.gridy = 1;
gbc_descricao_software.gridwidth = 8;
gbc_descricao_software.gridheight = 1;
contentPane.add(descricao_software, gbc_descricao_software);
JLabel descricao_software2 = DefaultComponentFactory.getInstance().createLabel("o c\u00F3digo fonte para um \u00FAnico PDF!");
descricao_software2.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_descricao_software2 = new GridBagConstraints();
gbc_descricao_software2.gridwidth = 8;
gbc_descricao_software2.gridheight = 1;
gbc_descricao_software2.insets = new Insets(0, 0, 5, 0);
gbc_descricao_software2.gridx = 0;
gbc_descricao_software2.gridy = 2;
contentPane.add(descricao_software2, gbc_descricao_software2);
JLabel lblTtulo = DefaultComponentFactory.getInstance().createLabel("T\u00EDtulo:");
GridBagConstraints gbc_lblTtulo = new GridBagConstraints();
gbc_lblTtulo.anchor = GridBagConstraints.EAST;
gbc_lblTtulo.insets = new Insets(0, 0, 5, 5);
gbc_lblTtulo.gridx = 0;
gbc_lblTtulo.gridy = 3;
contentPane.add(lblTtulo, gbc_lblTtulo);
campo_nome_projeto = new JTextField();
GridBagConstraints gbc_campo_nome_projeto = new GridBagConstraints();
gbc_campo_nome_projeto.insets = new Insets(0, 0, 5, 5);
gbc_campo_nome_projeto.fill = GridBagConstraints.HORIZONTAL;
gbc_campo_nome_projeto.gridx = 1;
gbc_campo_nome_projeto.gridy = 3;
contentPane.add(campo_nome_projeto, gbc_campo_nome_projeto);
campo_nome_projeto.setColumns(10);
JButton botaoHintNomeProjeto = new JButton("?");
botaoHintNomeProjeto.setToolTipText("Nome do seu projeto");
GridBagConstraints gbc_botaoHintNomeProjeto = new GridBagConstraints();
gbc_botaoHintNomeProjeto.insets = new Insets(0, 0, 5, 5);
gbc_botaoHintNomeProjeto.gridx = 2;
gbc_botaoHintNomeProjeto.gridy = 3;
contentPane.add(botaoHintNomeProjeto, gbc_botaoHintNomeProjeto);
JLabel label_diretorio = DefaultComponentFactory.getInstance().createLabel("Diret\u00F3rio:");
GridBagConstraints gbc_label_diretorio = new GridBagConstraints();
gbc_label_diretorio.anchor = GridBagConstraints.EAST;
gbc_label_diretorio.insets = new Insets(0, 0, 5, 5);
gbc_label_diretorio.gridx = 0;
gbc_label_diretorio.gridy = 4;
gbc_label_diretorio.gridwidth = 1;
gbc_label_diretorio.gridheight = 1;
contentPane.add(label_diretorio, gbc_label_diretorio);
campo_preencher_diretorio = new JTextField();
GridBagConstraints gbc_campo_preencher_diretorio = new GridBagConstraints();
gbc_campo_preencher_diretorio.insets = new Insets(0, 0, 5, 5);
gbc_campo_preencher_diretorio.fill = GridBagConstraints.HORIZONTAL;
gbc_campo_preencher_diretorio.gridx = 1;
gbc_campo_preencher_diretorio.gridy = 4;
gbc_campo_preencher_diretorio.gridheight = 1;
gbc_descricao_software.gridwidth = 1;
contentPane.add(campo_preencher_diretorio, gbc_campo_preencher_diretorio);
campo_preencher_diretorio.setColumns(20);
JButton botao_selecionar_pasta_projeto = new JButton("...");
botao_selecionar_pasta_projeto.setAction(acaoSelecionarPastaProjeto);
GridBagConstraints gbc_botao_selecionar_pasta_projeto = new GridBagConstraints();
gbc_botao_selecionar_pasta_projeto.insets = new Insets(0, 0, 5, 5);
gbc_botao_selecionar_pasta_projeto.gridx = 2;
gbc_botao_selecionar_pasta_projeto.gridy = 4;
gbc_botao_selecionar_pasta_projeto.gridheight = 1;
contentPane.add(botao_selecionar_pasta_projeto, gbc_botao_selecionar_pasta_projeto);
JButton botao_explicacao_selecione_diretorio = new JButton("?");
botao_explicacao_selecione_diretorio.setHorizontalAlignment(SwingConstants.LEFT);
botao_explicacao_selecione_diretorio.setToolTipText("escolha a pasta raiz do seu projeto");
GridBagConstraints gbc_botao_explicacao_selecione_diretorio = new GridBagConstraints();
gbc_botao_explicacao_selecione_diretorio.insets = new Insets(0, 0, 5, 5);
gbc_botao_explicacao_selecione_diretorio.gridx = 3;
gbc_botao_explicacao_selecione_diretorio.gridy = 4;
gbc_botao_explicacao_selecione_diretorio.gridheight = 1;
contentPane.add(botao_explicacao_selecione_diretorio, gbc_botao_explicacao_selecione_diretorio);
//PARTE REFERENTE A ADICIONAR EXTENSÃO(ANDREWS)
JPanel painel_adicionar_extensao = new JPanel();
TitledBorder tituloPainelExtensoes;
tituloPainelExtensoes = BorderFactory.createTitledBorder("Extensões");
painel_adicionar_extensao.setBorder(tituloPainelExtensoes);
GridBagConstraints gbc_painel_adicionar_extensao = new GridBagConstraints();
gbc_painel_adicionar_extensao.insets = new Insets(0, 0, 5, 0);
gbc_painel_adicionar_extensao.anchor = GridBagConstraints.NORTH;
gbc_painel_adicionar_extensao.gridheight = 7;
gbc_painel_adicionar_extensao.gridx = 4;
gbc_painel_adicionar_extensao.gridy = 3;
gbc_painel_adicionar_extensao.gridwidth = 4;
contentPane.add(painel_adicionar_extensao, gbc_painel_adicionar_extensao);
GridBagLayout gbl_painel_adicionar_extensao = new GridBagLayout();
gbl_painel_adicionar_extensao.columnWidths = new int[]{20, 20, 20, 20};
gbl_painel_adicionar_extensao.rowHeights = new int[]{20, 20, 20, 20};
gbl_painel_adicionar_extensao.columnWeights = new double[]{0.4, 0.4, 0.4, 0.4};
gbl_painel_adicionar_extensao.rowWeights = new double[]{0.4, 0.4, 0.4, 0.4};
painel_adicionar_extensao.setLayout(gbl_painel_adicionar_extensao);
textFieldAdicionarExtensoes = new JTextField();
GridBagConstraints gbc_textFieldAdicionarExtensoes = new GridBagConstraints();
gbc_textFieldAdicionarExtensoes.gridwidth = 3;
gbc_textFieldAdicionarExtensoes.insets = new Insets(0, 0, 0, 5);
gbc_textFieldAdicionarExtensoes.fill = GridBagConstraints.HORIZONTAL;
gbc_textFieldAdicionarExtensoes.gridx = 0;
gbc_textFieldAdicionarExtensoes.gridy = 3;
painel_adicionar_extensao.add(textFieldAdicionarExtensoes, gbc_textFieldAdicionarExtensoes);
textFieldAdicionarExtensoes.setColumns(10);
buttonRemoverExtensoes = new JButton("-");
GridBagConstraints gbc_buttonRemoverExtensoes = new GridBagConstraints();
gbc_buttonRemoverExtensoes.insets = new Insets(0, 0, 5, 0);
gbc_buttonRemoverExtensoes.gridx = 3;
gbc_buttonRemoverExtensoes.gridy = 0;
painel_adicionar_extensao.add(buttonRemoverExtensoes, gbc_buttonRemoverExtensoes);
buttonRemoverExtensoes.addActionListener(this);
this.listModel = new DefaultListModel<String>();
this.listaExtensoes = new JList<String>(listModel);
GridBagConstraints gbc_listaExtensoes = new GridBagConstraints();
gbc_listaExtensoes.gridheight = 3;
gbc_listaExtensoes.gridwidth = 4;
gbc_listaExtensoes.insets = new Insets(0, 0, 5, 25);
gbc_listaExtensoes.gridx = 0;
gbc_listaExtensoes.gridy = 0;
listaExtensoes.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
listaExtensoes.setLayoutOrientation(JList.VERTICAL);
listaExtensoes.setVisibleRowCount(-1);
JScrollPane scrollPane = new JScrollPane(listaExtensoes);
scrollPane.setPreferredSize(new Dimension(80, 120));
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
ListSelectionModel listSelectionModel = listaExtensoes.getSelectionModel();
listSelectionModel.addListSelectionListener(
new ListenerListaExtensoes(buttonRemoverExtensoes,listaExtensoes));
painel_adicionar_extensao.add(scrollPane, gbc_listaExtensoes);
buttonAdicionarExtensoes = new JButton("+");
GridBagConstraints gbc_buttonAdicionarExtensoes = new GridBagConstraints();
gbc_buttonAdicionarExtensoes.gridx = 3;
gbc_buttonAdicionarExtensoes.gridy = 3;
painel_adicionar_extensao.add(buttonAdicionarExtensoes, gbc_buttonAdicionarExtensoes);
buttonAdicionarExtensoes.addActionListener(this);
extensoes= new LinkedList<String>();
JLabel label_autor = DefaultComponentFactory.getInstance().createLabel("Autor:");
GridBagConstraints gbc_label_autor = new GridBagConstraints();
gbc_label_autor.anchor = GridBagConstraints.EAST;
gbc_label_autor.insets = new Insets(0, 0, 5, 5);
gbc_label_autor.gridx = 0;
gbc_label_autor.gridy = 5;
gbc_label_autor.gridheight = 1;
contentPane.add(label_autor, gbc_label_autor);
campo_preencher_autor = new JTextField();
GridBagConstraints gbc_campo_preencher_autor = new GridBagConstraints();
gbc_campo_preencher_autor.insets = new Insets(0, 0, 5, 5);
gbc_campo_preencher_autor.fill = GridBagConstraints.HORIZONTAL;
gbc_campo_preencher_autor.gridx = 1;
gbc_campo_preencher_autor.gridy = 5;
gbc_campo_preencher_autor.gridheight = 1;
contentPane.add(campo_preencher_autor, gbc_campo_preencher_autor);
campo_preencher_autor.setColumns(20);
JLabel label_versao = DefaultComponentFactory.getInstance().createLabel("Vers\u00E3o:");
GridBagConstraints gbc_label_versao = new GridBagConstraints();
gbc_label_versao.anchor = GridBagConstraints.EAST;
gbc_label_versao.insets = new Insets(0, 0, 5, 5);
gbc_label_versao.gridx = 0;
gbc_label_versao.gridy = 6;
gbc_label_versao.gridheight = 1;
contentPane.add(label_versao, gbc_label_versao);
campo_preencher_versao = new JTextField();
GridBagConstraints gbc_campo_preencher_versao = new GridBagConstraints();
gbc_campo_preencher_versao.insets = new Insets(0, 0, 5, 5);
gbc_campo_preencher_versao.fill = GridBagConstraints.HORIZONTAL;
gbc_campo_preencher_versao.gridx = 1;
gbc_campo_preencher_versao.gridy = 6;
contentPane.add(campo_preencher_versao, gbc_campo_preencher_versao);
gbc_campo_preencher_versao.gridheight = 1;
campo_preencher_versao.setColumns(10);
JLabel label_output = DefaultComponentFactory.getInstance().createLabel("Output:");
GridBagConstraints gbc_label_output = new GridBagConstraints();
gbc_label_output.anchor = GridBagConstraints.EAST;
gbc_label_output.insets = new Insets(0, 0, 5, 5);
gbc_label_output.gridx = 0;
gbc_label_output.gridy = 7;
gbc_label_output.gridheight = 1;
contentPane.add(label_output, gbc_label_output);
campo_preencher_output = new JTextField();
GridBagConstraints gbc_campo_preencher_output = new GridBagConstraints();
gbc_campo_preencher_output.insets = new Insets(0, 0, 5, 5);
gbc_campo_preencher_output.fill = GridBagConstraints.HORIZONTAL;
gbc_campo_preencher_output.gridx = 1;
gbc_campo_preencher_output.gridy = 7;
gbc_campo_preencher_output.gridheight = 1;
contentPane.add(campo_preencher_output, gbc_campo_preencher_output);
campo_preencher_output.setColumns(10);
JButton botao_especificar_arquivo_output = new JButton("...");
botao_especificar_arquivo_output.setAction(acaoEspecificarOutput);
GridBagConstraints gbc_botao_especificar_arquivo_output = new GridBagConstraints();
gbc_botao_especificar_arquivo_output.insets = new Insets(0, 0, 5, 5);
gbc_botao_especificar_arquivo_output.gridx = 2;
gbc_botao_especificar_arquivo_output.gridy = 7;
gbc_botao_especificar_arquivo_output.gridheight = 1;
contentPane.add(botao_especificar_arquivo_output, gbc_botao_especificar_arquivo_output);
JButton botaoEspecificarPastas = new JButton("Avançado...");
botaoEspecificarPastas.setAction(acaoBotaoEspecificarPastasArquivosProjeto);
GridBagConstraints gbc_botaoEspecificarPastas = new GridBagConstraints();
gbc_botaoEspecificarPastas.gridwidth = 2;
gbc_botaoEspecificarPastas.insets = new Insets(5, 0, 5, 5);
gbc_botaoEspecificarPastas.gridx = 1;
gbc_botaoEspecificarPastas.gridy = 8;
contentPane.add(botaoEspecificarPastas, gbc_botaoEspecificarPastas);
JButton botao_explicacao_especificar_pastas = new JButton("?");
botao_explicacao_especificar_pastas.setToolTipText("especificar que pastas/arquivos de seu projeto você quer no PDF");
GridBagConstraints gbc_botao_explicacao_especificar_pastas = new GridBagConstraints();
gbc_botao_explicacao_especificar_pastas.insets = new Insets(5, 0, 5, 5);
gbc_botao_explicacao_especificar_pastas.gridx = 2;
gbc_botao_explicacao_especificar_pastas.gridy = 8;
contentPane.add(botao_explicacao_especificar_pastas, gbc_botao_explicacao_especificar_pastas);
JButton botaoGerarPDF = new JButton("Gerar PDF");
botaoGerarPDF.setAction(acaoGerarPdf);
GridBagConstraints gbc_botaoGerarPDF = new GridBagConstraints();
gbc_botaoGerarPDF.gridheight = 3;
gbc_botaoGerarPDF.gridwidth = 2;
//gbc_botaoGerarPDF.insets = new Insets(0, 0, 0, 5);
gbc_botaoGerarPDF.gridx = 1;
gbc_botaoGerarPDF.gridy = 9;
contentPane.add(botaoGerarPDF, gbc_botaoGerarPDF);
JProgressBar barraDeProgresso = new JProgressBar();
GridBagConstraints gbc_JProgressBarUsuarioClicouNoBotaoAvancado = new GridBagConstraints();
gbc_JProgressBarUsuarioClicouNoBotaoAvancado.gridheight = 1;
gbc_JProgressBarUsuarioClicouNoBotaoAvancado.gridwidth = 2;
gbc_JProgressBarUsuarioClicouNoBotaoAvancado.gridx = 1;
gbc_JProgressBarUsuarioClicouNoBotaoAvancado.gridy = 10;
contentPane.add(barraDeProgresso, gbc_JProgressBarUsuarioClicouNoBotaoAvancado);
SingletonBarraDeProgresso.getInstance().setBarraDeProgresso(barraDeProgresso);
textoBarraDeProgresso = new JLabel("oi meu nome é andrews e eu sou uma pessoa legal como vocês são e eu falo muito não é vamos falar mais um pouco");
GridBagConstraints gbc_textoBarraDeProgresso = new GridBagConstraints();
gbc_textoBarraDeProgresso.gridheight = 1;
gbc_textoBarraDeProgresso.gridwidth = 2;
gbc_textoBarraDeProgresso.gridx = 1;
gbc_textoBarraDeProgresso.gridy = 11;
contentPane.add(textoBarraDeProgresso, gbc_textoBarraDeProgresso);
textoBarraDeProgresso.setText("oi meu nome é andrews");
textoBarraDeProgresso.setVisible(true);
SingletonBarraDeProgresso.getInstance().setTextoBarraDeProgresso(textoBarraDeProgresso);
SingletonBarraDeProgresso.getInstance().setTelaPrincipal(this);
extensoes= new LinkedList<String>();
//vamos verificar se n jah existem extensoes no arquivo .txt que podemos usar
this.verificarSeJaExistemExtensoesNoTxtParaJaPovoarAGuiComEstasExtensoes();
}
But when i try to change it via my Singleton on this method:
public void inicializarBarraDeProgresso(int valorMaximo, String textoBarra)
{
if(barraDeProgresso != null)
{
barraDeProgresso.setVisible(true);
barraDeProgresso.setStringPainted(true);
barraDeProgresso.setValue(0);
this.barraDeProgresso.setMaximum(valorMaximo);
this.barraDeProgresso.setMinimum(0);
this.textoBarraDeProgresso.setVisible(true);
this.textoBarraDeProgresso.setText(textoBarra);
}
}
Which is called inside many classes(TelaPrincipal is one of them, but there are a lot of other classes), the text stays the same: "oi meu nome é andrews"
I have also tried myJLabel.update(myJLabel.getGraphics()); after the setText(), but it bugs by text(it´s like it creates a loop which puts a lot of text over each other).
This post is the real lifesaver:
Why isn't setText updating the JLabel?
Basically, all you have to do is:
label.paintImmediately(label.getVisibleRect());
Right after the settext().
Java swing is confusing and annoying. I really do like working with android better ^^

How to use multiple layouts, without having blank space inbetween panels?

I'm trying to use multiple layouts (Border and Gridbag) to make a standalone visual application that shows the status of recovery rooms. I want my company logo to be in the top left corner. Directly to the right of the logo I want to have information shown in text format such as available beds, how many total occupants, ect...
Below that I am using the Grid bag layout to place bed icons as well as room numbers. There will be a lot more icons later on, I've only got two added at the moment just to show where they will start on the page.
I've provided an image of what it currently looks like with my source code.
TLDR: I need to beds shown in the image to be in the upper left part of the screen about half an inch from the bottom of the sample logo.
I tried to add an image, but I don't have enough reputation. here is a link to it if you need to see.
http://imgur.com/DViRSuJ
Source code for image above:
public static void showUI() {
int bedCount = getBedCount();
bedCount = bedCount - 5;
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
ImageIcon maleBed = new ImageIcon("Images/Male.png");
ImageIcon femaleBed = new ImageIcon("Images/Female.png");
ImageIcon emptyBed = new ImageIcon("Images/empty.png");
ImageIcon logo = new ImageIcon("Images/logo-sample.png");
ImageIcon mlogo = new ImageIcon("Images/Medicalistics_Logo.png");
JFrame window = new JFrame("Ft Lauderdale");
window.setVisible(true);
window.setSize(xSize, ySize);
JPanel mainPanel = new JPanel();
mainPanel.setBackground(Color.white);
mainPanel.setBounds(900, 900, 900, 900);
mainPanel.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(mainPanel);
JPanel logoPane = new JPanel();
logoPane.setLayout(new BorderLayout());
logoPane.setBackground(Color.white);
mainPanel.add(logoPane, BorderLayout.NORTH);
JPanel bedsPane = new JPanel();
bedsPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel logoLabel = new JLabel(logo);
logoLabel.setHorizontalAlignment(JLabel.LEFT);
logoPane.add(logoLabel, BorderLayout.NORTH);
mainPanel.add(bedsPane, BorderLayout.CENTER);
JLabel bedLabel = new JLabel(emptyBed);
c.gridheight = 5;
c.gridwidth = 5;
c.gridx = 50;
c.gridy = 0;
bedsPane.add(bedLabel, c);
JLabel bedLabel2 = new JLabel(femaleBed);
c.gridx = 0;
c.gridy = 0;
bedsPane.add(bedLabel2, c);
}
Well for the blank around panels you probably need to set the insets
eg: c.insets = new Insets(0, 0, 0, 0);
I am not sure how you want to handle 2 layout but you can do the effect you want with simply GridBagLayout.
You can see my test code here :
package Main;
import java.awt.*;
import javax.swing.*;
public class dummyGUI {
private static JPanel infopane, bedsPane, logopane, mainPanel;
private static JLabel lmalebed, lfemalebed, logoLabel;
public dummyGUI() {
showUI();
}
public static void showUI() {
int bedCount = 7; // getBedCount();
bedCount = bedCount - 5;
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
ImageIcon maleBed = new ImageIcon("Images/Male.png");
ImageIcon femaleBed = new ImageIcon("Images/Female.png");
ImageIcon emptyBed = new ImageIcon("Images/empty.png");
ImageIcon logo = new ImageIcon("Images/logo-sample.png");
ImageIcon mlogo = new ImageIcon("Images/Medicalistics_Logo.png");
JFrame window = new JFrame("Ft Lauderdale");
window.setVisible(true);
window.setSize(xSize, ySize);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 897, 0 };
gridBagLayout.rowHeights = new int[] { 504, 0, 0 };
gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
window.getContentPane().setLayout(gridBagLayout);
mainPanel = new JPanel();
mainPanel.setBackground(Color.white);
GridBagConstraints gbc_mainPanel = new GridBagConstraints();
gbc_mainPanel.insets = new Insets(0, 0, 5, 0);
gbc_mainPanel.fill = GridBagConstraints.BOTH;
gbc_mainPanel.gridx = 0;
gbc_mainPanel.gridy = 0;
window.getContentPane().add(mainPanel, gbc_mainPanel);
GridBagLayout gbl_mainPanel = new GridBagLayout();
gbl_mainPanel.columnWidths = new int[] { 286, 518, 0 };
gbl_mainPanel.rowHeights = new int[] { 101, 367, 0 };
gbl_mainPanel.columnWeights = new double[] { 1.0, 2.0, Double.MIN_VALUE };
gbl_mainPanel.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
mainPanel.setLayout(gbl_mainPanel);
logopane = new JPanel();
logopane.setBackground(Color.WHITE);
GridBagConstraints gbc_logopane = new GridBagConstraints();
gbc_logopane.insets = new Insets(0, 0, 0, 0);
gbc_logopane.fill = GridBagConstraints.BOTH;
gbc_logopane.gridx = 0;
gbc_logopane.gridy = 0;
mainPanel.add(logopane, gbc_logopane);
logopane.setLayout(new BorderLayout());
logoLabel = new JLabel(logo);
logopane.add(logoLabel, BorderLayout.NORTH);
logoLabel.setHorizontalAlignment(JLabel.LEFT);
infopane = new JPanel();
infopane.setBackground(Color.WHITE);
GridBagConstraints gbc_infopane = new GridBagConstraints();
gbc_infopane.insets = new Insets(0, 0, 0, 0);
gbc_infopane.fill = GridBagConstraints.BOTH;
gbc_infopane.gridx = 1;
gbc_infopane.gridy = 0;
mainPanel.add(infopane, gbc_infopane);
infopane.setLayout(new BorderLayout());
bedsPane = new JPanel();
GridBagConstraints gbc_bedsPane = new GridBagConstraints();
gbc_bedsPane.gridwidth = 2;
gbc_bedsPane.fill = GridBagConstraints.BOTH;
gbc_bedsPane.gridx = 0;
gbc_bedsPane.gridy = 1;
mainPanel.add(bedsPane, gbc_bedsPane);
GridBagLayout gbl_bedsPane = new GridBagLayout();
gbl_bedsPane.columnWidths = new int[] { 1, 0, 0, 0, 0 };
gbl_bedsPane.rowHeights = new int[] { 1, 0, 0, 0 };
gbl_bedsPane.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
gbl_bedsPane.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
bedsPane.setLayout(gbl_bedsPane);
lmalebed = new JLabel(maleBed);
GridBagConstraints gbc_lmalebed = new GridBagConstraints();
gbc_lmalebed.insets = new Insets(0, 0, 0, 0);
gbc_lmalebed.gridx = 1;
gbc_lmalebed.gridy = 1;
bedsPane.add(lmalebed, gbc_lmalebed);
lfemalebed = new JLabel(femaleBed);
GridBagConstraints gbc_lfemalebed = new GridBagConstraints();
gbc_lfemalebed.gridx = 3;
gbc_lfemalebed.gridy = 1;
bedsPane.add(lfemalebed, gbc_lfemalebed);
}
public static void main(String[] args) {
new dummyGUI();
}
}
The part here
gbl_bedsPane.columnWidths = new int[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_bedsPane.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_bedsPane.rowHeights = new int[] { 1, 0, 0, 0, 0 };
gbl_bedsPane.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
is where you can tell the number of row and column. I did not set enough column that is why you see it appear on the right when you add more.
I also did a function like i said in the comment :
private static JLabel add_bed(String sex, int x, int y){
JLabel bed = null;
if (sex == "female"){
bed = new JLabel(femaleBed);
GridBagConstraints gbc_lfemalebed = new GridBagConstraints();
gbc_lfemalebed.insets = new Insets(0, 0, 0, 0);
gbc_lfemalebed.gridx = x;
gbc_lfemalebed.gridy = y;
bedsPane.add(lfemalebed, gbc_lfemalebed);
}else if (sex == "male"){
lmalebed = new JLabel(maleBed);
GridBagConstraints gbc_lmalebed = new GridBagConstraints();
gbc_lmalebed.insets = new Insets(0, 0, 0, 0);
gbc_lmalebed.gridx = x;
gbc_lmalebed.gridy = y;
bedsPane.add(lmalebed, gbc_lmalebed);
}
return bed;
}
Then i can just do
add_bed("female", 5 , 1);

Categories