JFrame not becoming transparent - java

Recently I have been trying to get a transparent JFrame without success.
I want to make all components visible but not the frame and I see that people set the background to transparent and set Opaque to false.
I am doing this but without success.
public class KeyDialog extends JFrame {
public static MapPanel mapPanel = new MapPanel();
public KeyDialog() {
GridBagConstraints customGridBagLayout = new GridBagConstraints();
setLayout(new GridBagLayout());
setUndecorated(true);
// Title - Row 1
JTextField row1 = new JTextField();
row1.setSize(new Dimension(this.getWidth(), HEIGHT));
row1.setFont(new Font("Arial", Font.PLAIN, 30));
PromptSupport.setPrompt("Title Goes Here", row1);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.gridy = 0;
add(row1, customGridBagLayout);
// Key - Row 2
JPanel row2 = new JPanel();
row2.setOpaque(false);
// With Key
JPanel withKey = titleBoxKey(true);
withKey.setBackground(new Color(0, 0, 0, 0));
row2.add(withKey);
// Against Key
JPanel againstKey = titleBoxKey(false);
againstKey.setBackground(new Color(0, 0, 0, 0));
row2.add(againstKey);
customGridBagLayout.gridy = 1;
add(row2, customGridBagLayout);
pack();
}
public static JPanel titleBoxKey(boolean with) {
JPanel keyPanel = new JPanel();
keyPanel.setLayout(new GridBagLayout());
GridBagConstraints customGridBagLayout = new GridBagConstraints();
customGridBagLayout.insets = new Insets(7, 7, 7, 7); // Padding
Color republicanColor = null;
Color democraticColor = null;
if (with) {
republicanColor = mapPanel.getRepublicanWithColor();
democraticColor = mapPanel.getRepublicanAgainstColor();
} else if (!with) {
republicanColor = mapPanel.getDemocraticAgainstColor();
democraticColor = mapPanel.getDemocraticAgainstColor();
}
// Row 1 - Rectangles and Text Field
// Democratic Rectangle
JLabel republicanRect = mapPanel.drawRect(republicanColor);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 0;
customGridBagLayout.gridy = 0;
keyPanel.add(republicanRect, customGridBagLayout);
// Republican Rectangle
JLabel democraticRect = mapPanel.drawRect(democraticColor);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 1;
customGridBagLayout.gridy = 0;
keyPanel.add(democraticRect, customGridBagLayout);
// With/Against Label
JLabel infoLabel;
if (with) {
infoLabel = new JLabel("With");
} else {
infoLabel = new JLabel("Against");
}
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 2;
customGridBagLayout.gridy = 0;
keyPanel.add(infoLabel, customGridBagLayout);
// Row 2 - Bottom Text
// Republican Label
JLabel republicanLabel = new JLabel("Republican");
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 0;
customGridBagLayout.gridy = 1;
keyPanel.add(republicanLabel, customGridBagLayout);
// Democrat Label
JLabel democraticLabel = new JLabel("Democratic");
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 1;
customGridBagLayout.gridy = 1;
keyPanel.add(democraticLabel, customGridBagLayout);
return keyPanel;
}
}

You've made a nice attempt, but try this instead.
// Apply a transparent colour
setBackground(new Color(0, 255, 0, 0));
Simply add that code and your done :)

I set the background to frame.setBackground(new Color(0, 0, 0, 0)); thanks to the help of #JontyMorris
I then set all the contents on the frame to opaque panel.setOpaque(false);
and removed the backgrounds I set so the stripped down version looks like this...
// Frame
JFrame frame = new JFrame();
frame.setBackground(new Color(0, 0, 0, 0)); // Setting frame to be transparent
// Components
JPanel panel = new JPanel();
//add stuff to panel...
panel.setOpaque(false);

Actually there's a bit more to it than setting the background color. You have to change the undecorated property to true. Here's a quick tutorial you can follow. Well explained.
https://www.youtube.com/watch?v=zecGJfNHPWo

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

thread.sleep(5000) is not working

Actually I am working on a project which produces a dialogue on button click and dispose it in 5 sec via Thread.sleep(5000)
I have written following under run method
void showpopup(String p, String t) throws IOException {
JPanel app = new JPanel();
popup = new JFrame();
// app.setSize(300,400);
GridBagConstraints c1 = new GridBagConstraints();
app.setLayout(new GridBagLayout());
app.setVisible(true);
app.setBackground(new Color(39, 170, 225));
popup.setUndecorated(true);
popup.setSize(300, 100);
popup.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
JLabel header = new JLabel();
header.setText(p);
c1.gridx = 0;
c1.gridy = 0;
c1.weightx = 1.0f;
c1.weighty = 1.0f;
c1.insets = new Insets(5, 5, 5, 5);
c1.fill = GridBagConstraints.BOTH;
header.setFont(new Font("comfortaa", Font.BOLD, 15));
app.add(header, c1);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 0.3f;
constraints.weighty = 0.3f;
constraints.fill = GridBagConstraints.BOTH;
popup.add(app, constraints);
BufferedImage Butico = ImageIO.read(new File("C:/Users/utkarsh/Desktop/close.png"));
JButton close = new JButton(new ImageIcon(Butico));
close.setContentAreaFilled(false);
close.setBorder(BorderFactory.createEmptyBorder());
c1.gridx = 1;
c1.weightx = 0f;
c1.weighty = 0f;
c1.insets = new Insets(5, 5, 5, 5);
c1.fill = GridBagConstraints.NONE;
c1.anchor = GridBagConstraints.NORTH;
close.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
popup.dispose();
}
});
app.add(close, c1);
JPanel cont = new JPanel(new GridBagLayout());
// cont.setSize(arg0, arg1);
String a = "hello";
JLabel text = new JLabel("<HtML>" + t);
text.setAlignmentX(Component.LEFT_ALIGNMENT);
cont.setVisible(true);
cont.setBackground(new Color(241, 242, 242));
c1.gridx = 0;
c1.gridy = 0;
c1.weightx = 1.0f;
c1.weighty = 1.0f;
c1.insets = new Insets(5, 5, 5, 5);
c1.anchor = GridBagConstraints.NORTH;
c1.fill = GridBagConstraints.BOTH;
cont.add(text, c1);
constraints.gridx = 0;
constraints.gridy += 1;
constraints.weightx = 2.5f;
constraints.weighty = 2.5f;
constraints.fill = GridBagConstraints.BOTH;
popup.add(cont, constraints);
text.setFont(new Font("Comfortaa", Font.PLAIN, 12));
text.setForeground(Color.DARK_GRAY);
header.setForeground(Color.WHITE);
popup.getRootPane().setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(188, 188, 188)));
popup.setVisible(true);
Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
Insets th = Toolkit.getDefaultToolkit().getScreenInsets(popup.getGraphicsConfiguration());
popup.setLocation(s.width - popup.getWidth() - 5, s.height - th.bottom - popup.getHeight() - 5);
popup.setAlwaysOnTop(true);
new Thread() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
popup.dispose();
}
}
}.start();
}
Now when I click on the button once it works fine but for multiple button clicks multiple Jdialog pop-up appear
And only the last one gets disposed after 5s
So what changes I have to make in order to close every JDialog box
Popup is not local to this method
popup = new JFrame();
as therefore this code is not threadsafe.
Each time you click, you are replacing the popup object with a newly created one, so popup.dispose(); will dispose of the last one.

Swing - using GridLayout and JList

Apologies for my code being so messy. I've added and changed and commented out a lot of code and haven't gotten round to cleaning any of it up yet.
My main problem is being confused about how to get a 5x5 set of images. I need to be able to update it regularly as it is a map. These updates are going to happen in a separate method from the main and it will be difficult to know what image is in a particular square - hence why I've made an ArrayList called previous map.
This is so I can remove the elements of the previous map, then add the new ones. This is really ugly though so I'm trying to change the way I'm doing this by using a JList. I don't fully understand it, but it's cropped up in a lot of the examples I've seen.
What I think is happening is that I can add all my 25 images (as JLabel components) to this list, then add this list to the panel I want it to show up in.
I'm also trying to use GridLayout as that's also shown up in a lot of examples. What I think is happening with grid layout is that I set up a 5x5 grid layout, then use setLayout(<GridLayout name>) to the panel I want the grid to be in. I then add the images I want to be in the map to this grid layout.
Is my understanding correct? I've looked at lots of examples and explanations but I'm still unsure. I'm also struggling to understand how I can combine these two ideas - do I have to? If so am I doing it in the right way? If not how would I do this?
So far, I have managed to get this:
However, for some reason,the images are showing up as a column and not in a 5x5 grid.
Here's the relevant code I've been working on:
public class GameGUI3 extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JFrame f = new JFrame("Dungeons of Doom");
JPanel textPanel = new JPanel();
JPanel leftPanel = new JPanel(new GridBagLayout());
JPanel moveButtonPanel = new JPanel(new GridBagLayout());
JPanel extraButtonPanel = new JPanel(new GridBagLayout());
JPanel mapPanel = new JPanel(new GridBagLayout());
GridLayout gl = new GridLayout(5, 5);
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);
String action;
ArrayList<String> previousMap = new ArrayList<String>();
GridBagConstraints mapC = new GridBagConstraints();
private static GUIClient3 client = new GUIClient3();
JButton n = new JButton("N");
JButton e = new JButton("E");
JButton s = new JButton("S");
JButton w = new JButton("W");
JButton look = new JButton("LOOK");
JButton pickup = new JButton("PICKUP");
JButton hello = new JButton("HELLO");
JButton quit = new JButton("QUIT");
public GameGUI3()
{
GridBagConstraints northC = new GridBagConstraints();
GridBagConstraints eastC = new GridBagConstraints();
GridBagConstraints southC = new GridBagConstraints();
GridBagConstraints westC = new GridBagConstraints();
GridBagConstraints leftTopC = new GridBagConstraints();
GridBagConstraints leftBottomC = new GridBagConstraints(GridBagConstraints extraC = new GridBagConstraints();
northC.insets = new Insets(10, 65, 10, 10);
eastC.insets = new Insets(10, 65, 10, 10);
southC.insets = new Insets(10, 65, 10, 10);
westC.insets = new Insets(10, 0, 10, 10);
leftTopC.insets = new Insets(10, 10, 30, 10);
mapC.insets = new Insets(30, 30, 30, 30);
extraC.insets = new Insets(10, 10, 10, 10);
f.setBounds(100, 100, 1000, 600); // (start on x-axis, start on y, width, height)
textPanel.setBounds(1000, 250, 500, 200);
textPanel.add(new JScrollPane(textArea));
f.getContentPane().add(leftPanel, BorderLayout.WEST);
leftTopC.gridx = 0;
leftTopC.gridy = 0;
leftTopC.anchor = GridBagConstraints.FIRST_LINE_START;
leftPanel.add(moveButtonPanel, leftTopC);
//mapC.gridx = 0;
//mapC.gridy = 1;
//mapC.anchor = GridBagConstraints.LINE_START;
//leftPanel.add(mapPanel, mapC);
//mapPanel.setLayout(gl);
leftPanel.add(mapPanel);
leftBottomC.gridx = 0;
leftBottomC.gridy = 2;
leftBottomC.anchor = GridBagConstraints.LAST_LINE_START;
leftPanel.add(extraButtonPanel, leftBottomC);
f.getContentPane().add(textPanel, BorderLayout.EAST);
textArea.setEditable(false);
this.setVisible(false);
northC.gridx = 0;
northC.gridy = 0;
northC.gridwidth = 3;
northC.anchor = GridBagConstraints.NORTH;
moveButtonPanel.add(n, northC);
westC.gridx = 0;
westC.gridy = 1;
westC.gridwidth = 1;
westC.anchor = GridBagConstraints.WEST;
moveButtonPanel.add(w, westC);
eastC.gridx = 2;
eastC.gridy = 1;
eastC.gridwidth = 3;
eastC.anchor = GridBagConstraints.EAST;
moveButtonPanel.add(e, eastC);
southC.gridx = 0;
southC.gridy = 2;
southC.gridwidth = 3;
southC.anchor = GridBagConstraints.SOUTH;
moveButtonPanel.add(s, southC);
mapC.gridx = 0;
mapC.gridy = 2;
//mapC.gridwidth = 10;
//mapC.anchor = GridBagConstraints.LINE_START;
//mapPanel.setLayout(gl);
leftPanel.add(mapPanel, mapC);
ImageIcon HereBeDragonsIcon = new ImageIcon("HereBeDragons.jpg", "Image");
JLabel HereBeDragonsLabel = new JLabel(HereBeDragonsIcon);
//mapPanel.add(HereBeDragonsLabel);
int count=0;
for(int i=0; i<4; i++)
{
listModel.add(count++, HereBeDragonsIcon);
//listModel.addElement(HereBeDragonsIcon);
previousMap.add("HereBeDragonsLabel");
//mapPanel.add(HereBeDragonsLabel);
}
//JList list = new JList(listModel);
//mapPanel.add(list);
mapPanel.add(list);
extraButtonPanel.add(look, extraC);
extraButtonPanel.add(pickup, extraC);
extraButtonPanel.add(hello, extraC);
extraButtonPanel.add(quit, extraC);
n.addActionListener(this);
e.addActionListener(this);
s.addActionListener(this);
w.addActionListener(this);
look.addActionListener(this);
pickup.addActionListener(this);
hello.addActionListener(this);
quit.addActionListener(this);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setVisible(true);
}
Many thanks - if anything is unclear please let me know and I will try and re-phrase my question or explain my code better.

Java : divide the screen

I try to do a simple swing window, but with the layout it's not easy...
I mean I just want a window with 3 panels :
header with 20% of window in height
content with 60% of window in height
footer with 20% of window in height
But I can't succeed to have what I want. I used a gridLayout(3,1) but I can't specify the height.
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridLayout grid = new GridLayout(3,1);
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
getContentPane().add(_header);
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp);
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
getContentPane().add(_footer);
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
Can you help me ?
Best regards
GridBagLayout is capable of dividing vertical or horizontal space proportionally.
Here's an example that displays a red JPanel in the top 20% of a window, a green JPanel in the middle 60%, and a blue JPanel in the bottom 20%:
JFrame window = new JFrame();
window.setLayout(new GridBagLayout());
JPanel top = new JPanel(), middle = new JPanel(), bottom = new JPanel();
top.setBackground(Color.red);
middle.setBackground(Color.green);
bottom.setBackground(Color.blue);
GridBagConstraints c = new GridBagConstraints();
// we want the layout to stretch the components in both directions
c.fill = GridBagConstraints.BOTH;
// if the total X weight is 0, then it won't stretch horizontally.
// It doesn't matter what the weight actually is, as long as it's not 0,
// because the grid is only one component wide
c.weightx = 1;
// Vertical space is divided in proportion to the Y weights of the components
c.weighty = 0.2;
c.gridy = 0;
window.add(top, c);
// It's fine to reuse the constraints object; add makes a copy.
c.weighty = 0.6;
c.gridy = 1;
window.add(middle, c);
c.weighty = 0.2;
c.gridy = 2;
window.add(bottom, c);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
Result:
GridLayout always spaces evenly. You could instead use GridBagLayout, the most evil of all the Java layout managers. I've given them "weights" of 20, 60, 20 so you can see which values are which. You can just as easily use 2, 6, 2, it doesn't matter it's just a ratio. Look at the GridBagLayout tutorial for more info.
Example
public class Window extends JFrame implements Serializable {
private JPanel _header;
private JPanel _content;
private JPanel _footer;
public Window() {
GridBagLayout grid = new GridBagLayout();
setLayout(grid);
_header = new JPanel();
_header.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_header, new GridBagConstraints(0, 0, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
// <=== add with constraints here
getContentPane().add(jsp, new GridBagConstraints(0, 1, 1, 1, 1, 60, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_footer = new JPanel();
_footer.setBackground(Color.GRAY);
// <=== add with constraints here
getContentPane().add(_footer, new GridBagConstraints(0, 2, 1, 1, 1, 20, GridBagConstraints.BASELINE, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
pack();
validate();
setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window();
}
});
}
}
Screenshot

GridBagLayout - Height of one row causes the width of next row to change

The UI I am working on displays a panel which lets a user select a movie and play. There are controls to play, pause, etc.
The layout seems to look the way I want. The panel uses a GridBagLayout. Row 2 displays a text area for status messages and row 3 displays a panel with buttons and a progress bar.
The problem I am running into is that when I have too many lines of text in the text area, the buttons in row 3 wrap around. This is irrespective of the height of the outer frame.
The height in row 2 is affecting the width in row 3. I don't understand this behavior. I am wondering if someone can tell me what is it that I am doing wrong and how I can fix it? I have attached the code.
On a slightly different topic, if you are looking at the code, can you also suggest a way to leave a margin between the bottom-most component and the outermost panel?
Thank you in advance for your help.
Regards,
Peter
private static JButton CreateImageButton(String fileName) {
JButton retVal = new JButton("xxx");
return retVal;
}
public MoviePanel() {
this.setLayout(new GridBagLayout());
this.setBackground(Color.WHITE);
JButton btnRefresh = CreateImageButton("refresh.png");
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.fill = GridBagConstraints.NORTH;
c.insets.left = 10; c.insets.right = 10; c.insets.top = 10;
this.add(btnRefresh, c);
JComboBox cbMovieList = new JComboBox();
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets.right = 10; c.insets.top = 10;
c.weightx = 1.0;
this.add(cbMovieList, c);
JButton btnAuthorize = new JButton("Get Info");
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.WEST;
c.insets.top = 10;
this.add(btnAuthorize, c);
JTextArea txtInfo = new JTextArea();
txtInfo.setFont( new Font("SansSerif", Font.BOLD, 12));
txtInfo.setBackground(Color.cyan);
// txtInfo.setText("abc\ndef");
txtInfo.setText("abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz");
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.anchor = GridBagConstraints.NORTHWEST;
c.weighty = 1.0;
c.insets.top = 10;
this.add(txtInfo, c);
JPanel controllerOuter = new JPanel();
controllerOuter.setLayout(new BoxLayout(controllerOuter, BoxLayout.Y_AXIS));
controllerOuter.setBorder(BorderFactory.createRaisedBevelBorder());
FlowLayout controllerLayout = new FlowLayout(FlowLayout.CENTER);
controllerLayout.setHgap(0);
JPanel controller = new JPanel(controllerLayout);
controller.setBorder(new EmptyBorder(10, 10, 10, 10));
Dimension dim = new Dimension(60, 40);
JButton btnPlay = CreateImageButton("play.png");
btnPlay.setPreferredSize(dim);
controller.add(btnPlay);
JButton btnPause = CreateImageButton("pause.png");
btnPause.setPreferredSize(dim);
controller.add(btnPause);
JButton btnStop = CreateImageButton("stop.png");
btnStop.setPreferredSize(dim);
controller.add(btnStop);
JButton btnForward = CreateImageButton("forward.png");
btnForward.setPreferredSize(dim);
controller.add(btnForward);
JComboBox cbAspectRatio = new JComboBox();
cbAspectRatio.setPreferredSize(new Dimension(100, 40));
cbAspectRatio.setBorder(new EmptyBorder(0, 10, 0, 0));
controller.add(cbAspectRatio);
controllerOuter.add(controller);
JProgressBar pbProgress = new JProgressBar(0, 100);
pbProgress.setPreferredSize(new Dimension(350, 40));
pbProgress.setBorder(new EmptyBorder(0, 10, 10, 10));
pbProgress.setValue(50);
pbProgress.setString("50/100");
pbProgress.setStringPainted(true);
pbProgress.setForeground(Color.BLUE);
pbProgress.setBorderPainted(true);
controllerOuter.add(pbProgress);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
c.weightx = 1.0;
this.add(controllerOuter, c);
}
I see several things in your code:
You force the preferredSize of the JButton's. If possible, I would remove that because this will often get you more problems than solutions. If you want to force the preferredSize, you should also pay attention to set the minimum and maximum sizes as well, otherwise you get weird behaviour like the one you are observing
You use a BoxLayout to display the controls. While this is perfectly acceptable, BoxLayout also relies on min/max size to perform the layout, which you did not set.
You use imbricated layouts. This is fine too, but why not use only the GridBagLayout of your MoviePanel?
Usually TextAreas are wrapped in JScrollPane, in case the text is too big. You can also setLineWrap(true) on the TextArea, so that it does not go too far on the right. By setting rows/columns on the TextArea, you will define its preferreSize (to prevent it from depending of the text it contains).
On your GridBagConstraints, the fill property can only be: NONE, VERTICAL, HORIZONTAL or BOTH (You used VERTICAL for one of them). Also, it is not needed to recreate a new instance, you can reuse the same GridBagConstraint over and over, it is automatically cloned by the LayoutManager when you set the constraint for the component.
Now for the solutions, I found several:
When you add the contollerOuter, also specify c.fill = GridBagConstraints.HORIZONTAL; (This is the easiest way to solve your issues)
When you set the preferredSize of the JButtons, also force their minimumSize to the same value.
Use only the GridBagLayout to layout all components. (This would be my favorite)
Replace the FlowLayout by a BoxLayout with a X_AXIS.
Rember that GridBagConstraints properties :
gridx, gridy: specifies the location
gridwidth, gridheight: specifies the colspan/rowspan
weightx, weighty: specifies who gets the extra horizontal/vertical space and in what proportion
anchor: specifies the alignement of the component withing its "cell", if the "cell" is bigger than the component
fill: specifies if the component should stretch to the cell width/height
Just adding one JPanel each for Center and Bottom will do the trick for you, so till your JTextArea your GridBagLayout will server the purpose and after that the BorderLayout of the MAIN JPanel will do. Moreover, adding JScrollPane also to the whole thing reduces the effort needed at other areas. Have a look at the code and output :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class JTextPaneExample extends JPanel
{
private Icon info = UIManager.getIcon("OptionPane.informationIcon");
private Icon error = UIManager.getIcon("OptionPane.errorIcon");
private static JButton CreateImageButton(String fileName) {
JButton retVal = new JButton("xxx");
return retVal;
}
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
JPanel centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
centerPanel.setLayout(new GridBagLayout());
centerPanel.setBackground(Color.WHITE);
JButton btnRefresh = CreateImageButton("refresh.png");
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.fill = GridBagConstraints.NORTH;
c.insets.left = 10; c.insets.right = 10; c.insets.top = 10;
centerPanel.add(btnRefresh, c);
JComboBox cbMovieList = new JComboBox();
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets.right = 10; c.insets.top = 10;
c.weightx = 1.0;
centerPanel.add(cbMovieList, c);
JButton btnAuthorize = new JButton("Get Info");
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.WEST;
c.insets.top = 10;
centerPanel.add(btnAuthorize, c);
JTextArea txtInfo = new JTextArea();
txtInfo.setFont( new Font("SansSerif", Font.BOLD, 12));
txtInfo.setBackground(Color.cyan);
// txtInfo.setText("abc\ndef");
txtInfo.setText("abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz");
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(txtInfo);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1.0;
c.insets.top = 10;
centerPanel.add(scroller, c);
JPanel controllerOuter = new JPanel();
controllerOuter.setLayout(new BoxLayout(controllerOuter, BoxLayout.Y_AXIS));
controllerOuter.setBorder(BorderFactory.createRaisedBevelBorder());
FlowLayout controllerLayout = new FlowLayout(FlowLayout.CENTER);
controllerLayout.setHgap(0);
JPanel controller = new JPanel(controllerLayout);
controller.setBorder(new EmptyBorder(10, 10, 10, 10));
Dimension dim = new Dimension(60, 40);
JButton btnPlay = CreateImageButton("play.png");
btnPlay.setPreferredSize(dim);
controller.add(btnPlay);
JButton btnPause = CreateImageButton("pause.png");
btnPause.setPreferredSize(dim);
controller.add(btnPause);
JButton btnStop = CreateImageButton("stop.png");
btnStop.setPreferredSize(dim);
controller.add(btnStop);
JButton btnForward = CreateImageButton("forward.png");
btnForward.setPreferredSize(dim);
controller.add(btnForward);
JComboBox cbAspectRatio = new JComboBox();
cbAspectRatio.setPreferredSize(new Dimension(100, 40));
cbAspectRatio.setBorder(new EmptyBorder(0, 10, 0, 0));
controller.add(cbAspectRatio);
controllerOuter.add(controller);
JProgressBar pbProgress = new JProgressBar(0, 100);
pbProgress.setPreferredSize(new Dimension(350, 40));
pbProgress.setBorder(new EmptyBorder(0, 10, 10, 10));
pbProgress.setValue(50);
pbProgress.setString("50/100");
pbProgress.setStringPainted(true);
pbProgress.setForeground(Color.BLUE);
pbProgress.setBorderPainted(true);
controllerOuter.add(pbProgress);
add(centerPanel, BorderLayout.CENTER);
add(controllerOuter, BorderLayout.PAGE_END);
frame.getContentPane().add(this);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JTextPaneExample().createAndDisplayGUI();
}
});
}
}
Here is the output as you add more lines :

Categories