I am going to have some behavior I want to be coupled with some other jcomboboxes, so I am using setModel() to fill in the arrays as values. While doing this and running the gui, I noticed after selecting a different element than the first one, that other element is not showing in the combo box. For example...
As you can see it doesn't say charTwo, even though that is what I selected. Here is the code.
Note: Line#101 is where the setModel() happens...
import org.apache.commons.lang3.ArrayUtils;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class TestGui extends JFrame {
private final String[] guiCharSelDefault = {"--- Select Character ---"};
private final String[] characters = {"charOne", "charTwo", "charThree", "charFour"};
private final String[] GuiCharSel = (String[]) ArrayUtils.addAll(guiCharSelDefault, characters);
private JComboBox charCombo = createStandardCombo(GuiCharSel);
private BackgroundPanel backgroundFrame = createBackgroundFrame("../images/Background.png");
private JPanel topFrame = createTopFrame();
private JScrollPane topFrameScroll = createTopScrollPane();
private JPanel centerFrame = createCenterFrame();
//**************************************************************************************
// Constructor
TestGui(){
setContentPane(backgroundFrame);
add(topFrameScroll, BorderLayout.NORTH);
add(centerFrame, BorderLayout.CENTER);
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//**************************************************************************************
// Support Methods
private static GridBagConstraints setGbc(int gridx, int gridy, int gridWidth, int gridHeight, int ipadx, int ipady, String anchorLocation, double weightx, double weighty, Insets insets){
GridBagConstraints gbc = new GridBagConstraints();
if (anchorLocation.toUpperCase().equals("NORTHWEST")){
gbc.anchor = GridBagConstraints.NORTHWEST;
} else if (anchorLocation.toUpperCase().equals("NORTH")){
gbc.anchor = GridBagConstraints.NORTH;
} else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
gbc.anchor = GridBagConstraints.NORTHEAST;
} else if (anchorLocation.toUpperCase().equals("WEST")){
gbc.anchor = GridBagConstraints.WEST;
} else if (anchorLocation.toUpperCase().equals("EAST")){
gbc.anchor = GridBagConstraints.EAST;
} else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
gbc.anchor = GridBagConstraints.SOUTHWEST;
} else if (anchorLocation.toUpperCase().equals("SOUTH")){
gbc.anchor = GridBagConstraints.SOUTH;
} else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
gbc.anchor = GridBagConstraints.SOUTHEAST;
} else {
gbc.anchor = GridBagConstraints.CENTER;
}
gbc.gridx = gridx; // column
gbc.gridy = gridy; // row
gbc.gridwidth = gridWidth; // number of columns
gbc.gridheight = gridHeight; // number of rows
gbc.ipadx = ipadx; // width of object
gbc.ipady = ipady; // height of object
gbc.weightx = weightx; // shifts rows to side of set anchor
gbc.weighty = weighty; // shifts columns to side of set anchor
gbc.insets = insets; // placement inside cell
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
return gbc;
}
private Insets setInsets(int top, int left, int bottom, int right){
Insets insets = new Insets(top,left,bottom,right);
return insets;
}
//**************************************************************************************
// Interactive Object Methods
private JComboBox createStandardCombo(String[] defaultValues){
JComboBox comboBox = new JComboBox(defaultValues);
DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
dlcr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
comboBox.setRenderer(dlcr);
comboBox.setPrototypeDisplayValue("X" + guiCharSelDefault + "X");
return comboBox;
}
//**************************************************************************************
// Object Action Methods
private void setCharComboAction(){
charCombo.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String charName = ((JComboBox)(e.getSource())).getSelectedItem().toString();
if (!(charName.equals(guiCharSelDefault[0]))){
charCombo.setModel(new DefaultComboBoxModel(characters));
}
}
}
);
}
//**************************************************************************************
// Panel Methods
private BackgroundPanel createBackgroundFrame(String imgLocName){
Image backgroundImg = null;
try {
backgroundImg = ImageIO.read(getClass().getResource(imgLocName));
System.out.println("File: " + imgLocName.toString());
} catch (Exception e) {
System.out.println("Cannot read file: " + e);
}
BackgroundPanel bgPanel = new BackgroundPanel(backgroundImg, BackgroundPanel.SCALED, 0.0f, 0.0f);
return bgPanel;
}
private JPanel createTopFrame(){
JPanel pnl = new JPanel();
pnl.setLayout(new GridBagLayout());
setCharComboAction();
pnl.add(charCombo, setGbc(0,0, 1,1, 0,0, "WEST", 0, 0, setInsets(0, 10, 0, 0)));
pnl.setOpaque(false);
return pnl;
}
private JScrollPane createTopScrollPane(){
JScrollPane scrollPane = new JScrollPane(backgroundFrame);
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border lineBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, new Color(224,224,224));
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);
scrollPane.setBorder(compoundFinal);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
scrollPane.getViewport().setView(topFrame);
return scrollPane;
}
private JPanel createCenterFrame() {
JPanel pnl = new JPanel();
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Color lineColor = new Color(224, 224, 224);
Border lineBorder = BorderFactory.createMatteBorder(5, 5, 5, 5, lineColor);
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);
TitledBorder topFrameTitle = BorderFactory.createTitledBorder(compoundFinal, "Stuff");
topFrameTitle.setTitleJustification(TitledBorder.CENTER);
pnl.setBorder(topFrameTitle);
pnl.setLayout(new GridBagLayout());
pnl.setOpaque(false);
return pnl;
}
//**************************************************************************************
public static void main(String[] args) {
new TestGui();
}
}
Is there a way I can have it keep the selected item after selecting it?
Why you don't restore the selection???
private void setCharComboAction(){
charCombo.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String charName = ((JComboBox)(e.getSource())).getSelectedItem().toString();
if (!(charName.equals(guiCharSelDefault[0]))){
DefaultComboBoxModel model = new DefaultComboBoxModel(characters);
model.setSelectedItem(charName);
charCombo.setModel(model);
}
}
}
);
}
Related
I have a JPanel using GridBagLayout inside a JScrollPane. The GridBagLayout, has line split borders set between some columns (colored in blue). The issue is I can't get the behavior to act correctly, while removing the unnecessary right scroll bar from the JScrollPane.
The Code...
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestGui extends JFrame {
//**************************************************************************************
//************************************** Variables *************************************
//**************************************************************************************
private String[] showHideComboBoxValue = {"Show hiddenLabel", "Hide hiddenLabel"};
private JComboBox showHideComboBox = createShowHideComboBox(showHideComboBoxValue);
private JLabel labelHiddenOrShown = createDefaultLabel("This label is hidden or shown depending on the status of the combo box", 14);
private JPanel topFrame = createTopFrame();
private JScrollPane topFrameScroll = createTopScrollPane();
private JScrollPane centerFrameScroll = createCenterScrollPane();
//**************************************************************************************
//************************************* Constructor ************************************
//**************************************************************************************
private TestGui() {
add(topFrameScroll, BorderLayout.NORTH);
add(centerFrameScroll, BorderLayout.CENTER);
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//**************************************************************************************
//*********************************** Support Method ***********************************
//**************************************************************************************
private static GridBagConstraints setGbc(int gridx, int gridy, int gridWidth, int gridHeight, int ipadx, int ipady, String anchorLocation, double weightx, double weighty, Insets insets, boolean fillCell){
GridBagConstraints gbc = new GridBagConstraints();
if (anchorLocation.toUpperCase().equals("NORTHWEST")){
gbc.anchor = GridBagConstraints.NORTHWEST;
} else if (anchorLocation.toUpperCase().equals("NORTH")){
gbc.anchor = GridBagConstraints.NORTH;
} else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
gbc.anchor = GridBagConstraints.NORTHEAST;
} else if (anchorLocation.toUpperCase().equals("WEST")){
gbc.anchor = GridBagConstraints.WEST;
} else if (anchorLocation.toUpperCase().equals("EAST")){
gbc.anchor = GridBagConstraints.EAST;
} else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
gbc.anchor = GridBagConstraints.SOUTHWEST;
} else if (anchorLocation.toUpperCase().equals("SOUTH")){
gbc.anchor = GridBagConstraints.SOUTH;
} else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
gbc.anchor = GridBagConstraints.SOUTHEAST;
} else {
gbc.anchor = GridBagConstraints.CENTER;
}
gbc.gridx = gridx; // column
gbc.gridy = gridy; // row
gbc.gridwidth = gridWidth; // number of columns
gbc.gridheight = gridHeight; // number of rows
gbc.ipadx = ipadx; // width of object
gbc.ipady = ipady; // height of object
gbc.weightx = weightx; // shifts columns to side of set anchor
gbc.weighty = weighty; // shifts rows to side of set anchor
gbc.insets = insets; // placement inside cell
if (fillCell){
gbc.fill = GridBagConstraints.BOTH;
}
return gbc;
}
//**************************************************************************************
//*********************************** Object Methods ***********************************
//**************************************************************************************
private JComboBox createShowHideComboBox(String[] comboValues){
JComboBox comboBox = new JComboBox(comboValues);
comboBox.setPrototypeDisplayValue("X" + comboValues[0] + "X");
return comboBox;
}
private void createShowHideComboBoxAction(){
showHideComboBox.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selection = ((JComboBox) (e.getSource())).getSelectedItem().toString();
if (selection.equals(showHideComboBoxValue[1])){
labelHiddenOrShown.setVisible(false);
} else {
labelHiddenOrShown.setVisible(true);
}
}
}
);
}
private JLabel createDefaultLabel(String text, int textSize){
JLabel lbl = new JLabel(text);
lbl.setFont(new Font(text, Font.BOLD, textSize));
return lbl;
}
//**************************************************************************************
//************************************ Panel Methods ***********************************
//**************************************************************************************
private JPanel createTopFrame() {
JPanel pnl = new JPanel();
Border lineSplitterBoarder = BorderFactory.createMatteBorder(0, 0, 0, 5, Color.BLUE);
JLabel lineSplitterOne = new JLabel();
lineSplitterOne.setBorder(lineSplitterBoarder);
JLabel lineSplitterTwo = new JLabel();
lineSplitterTwo.setBorder(lineSplitterBoarder);
pnl.setLayout(new GridBagLayout());
createShowHideComboBoxAction();
pnl.add(showHideComboBox,setGbc(0,1, 1,1, 0,0,"CENTER", 0, 0, new Insets(10, 10, 10, 0), false));
pnl.add(createDefaultLabel("Label",14), setGbc(1,0,1,1,0,0,"CENTER",0,0,new Insets(10,10,0,10),false));
pnl.add(createDefaultLabel("Label",14), setGbc(1,1,1,1,0,0,"CENTER",0,0,new Insets(0,10,0,10),false));
pnl.add(createDefaultLabel("Label",14), setGbc(1,2,1,1,0,0,"CENTER",0,0,new Insets(0,10,0,10),false));
pnl.add(createDefaultLabel("Label",14), setGbc(1,3,1,1,0,0,"CENTER",0,0,new Insets(0,10,10,10),false));
pnl.add(lineSplitterOne, setGbc(2,0,1,4,0,0,"CENTER",0,0,new Insets(0,0,0,0),true));
pnl.add(createDefaultLabel("Hidden Label Below", 14), setGbc(3,0,8,1,9,9,"CENTER",0,0,new Insets(10,10,0,10),false));
JPanel labelHiddenOrShownPanel = new JPanel();
labelHiddenOrShownPanel.setLayout(new GridLayout(1,1));
labelHiddenOrShownPanel.add(labelHiddenOrShown);
pnl.add(labelHiddenOrShownPanel, setGbc(3,1,1,1,0,0,"WEST",0,0,new Insets(0,5,0,0),false));
pnl.add(lineSplitterTwo, setGbc(11,0,1,4,0,0,"CENTER",0,0,new Insets(0,5,0,0),true));
pnl.add(createDefaultLabel("Label",14), setGbc(12,0,1,1,0,0,"CENTER",0,0,new Insets(10,10,0,0),false));
pnl.add(createDefaultLabel("Label",14), setGbc(12,1,1,1,0,0,"CENTER",0,0,new Insets(0,10,0,0),false));
pnl.add(createDefaultLabel("Label",14), setGbc(12,2,1,1,0,0,"CENTER",0,0,new Insets(0,10,0,0),false));
pnl.add(createDefaultLabel("Label",14), setGbc(12,3,1,1,0,0,"CENTER",0,0,new Insets(0,10,10,0),false));
return pnl;
}
private JScrollPane createTopScrollPane(){
JScrollPane scrollPane = new JScrollPane();
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border lineBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, new Color(224,224,224));
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);
//scrollPane.setPreferredSize(new Dimension(0, 160));
scrollPane.setBorder(compoundFinal);
scrollPane.getViewport().setView(topFrame);
return scrollPane;
}
private JScrollPane createCenterScrollPane(){
JScrollPane scrollPane = new JScrollPane();
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border lineBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, new Color(224,224,224));
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compoundSetup = BorderFactory.createCompoundBorder(raisedBevel, lineBorder);
Border compoundFinal = BorderFactory.createCompoundBorder(compoundSetup, loweredBevel);
scrollPane.setBorder(compoundFinal);
return scrollPane;
}
//**************************************************************************************
//************************************ Start Program ***********************************
//**************************************************************************************
public static void main(String[] args) {
new TestGui();
}
}
Steps to reproduce issue(s)...
Step 1: run the program and observe the unnecessary scroll bar on the right of the top JScrollPane...
Step 2: maximize the window, and watch both scroll bars disappear with the objects in the JPanel being put where they should be...
This behavior is good and we want to keep this. You can close the program now.
Step 3: Now to remove the right scroll bar (in Step 1), lets change a line of code (line#145) from //scrollPane.setPreferredSize(new Dimension(0, 160)); to scrollPane.setPreferredSize(new Dimension(0, 160));, and re-run the program...
Great! the right bar was removed. But wait a minute...
Step 4: Now lets maximize the window...
Notice extra space added between the border lines (we don't want this behavior).
Note 1: It's important to keep the option to show/hide hidden label without resizing the cells in the GridBagLayout. After researching, the only way I found to do this was to have the hidden JLabel in it's own JPanel using GridLayout.
Note 2: I noticed this behavior (in Step 1) started happening after the width became long enough to require the horizontal scroll bar to start appearing.
What I need is the behavior from image 3 (when window is not maximized), and image 2 (when window is maximized). If anyone has any idea to get these 2 combinations of behaviors working together, please help. Thanks
Update: due to complaints of code being too large, I shortened it to 169 lines. Every component in this code is required to monitor the 2 behaviors as mentioned above.
Please have a look at the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestForm extends JFrame
{
private JLabel firstLabel, secondLabel;
private JTextField firstTxt, secondTxt;
private GridBagLayout mainLayout = new GridBagLayout();
private GridBagConstraints mainCons = new GridBagConstraints();
private JPanel centerPanel;
public TestForm()
{
this.setLayout(mainLayout);
//Declaring instance variables
firstLabel = new JLabel("First: ");
secondLabel = new JLabel("Second: ");
firstTxt = new JTextField(7);
secondTxt = new JTextField(7);
mainCons.anchor = GridBagConstraints.WEST;
mainCons.weightx = 1;
mainCons.gridy = 2;
mainCons.gridx = 1;
mainCons.insets = new Insets(15, 0, 0, 0);
this.add(createCenterPanel(), mainCons);
System.out.println("Center Panel Width: "+centerPanel.getWidth());
this.setTitle("The Test Form");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
centerPanel.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,10,0,0);
centerPanel.add(secondLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,-10,0,0);
centerPanel.add(secondTxt,gbc);
centerPanel.setBorder(BorderFactory.createTitledBorder("The Testing Form"));
centerPanel.setPreferredSize(centerPanel.getPreferredSize());
centerPanel.validate();
System.out.println("Width is: "+centerPanel.getWidth());
System.out.println("Width is: "+centerPanel.getHeight());
return centerPanel;
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TestForm();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I am trying to get the width of the centerPanel in 2 places. But in both cases, I get 0 as the answer! I must get the width and height somehow because the southPanel (not included here) will use those values, with some reduce to the height. Please help!
The width is 0 before pack() or setSize() is called. You can get the width and use it after pack() call
or
define your own LayoutManager which use the width for the height of another layout part (southPanel)
I have to create 5 Jlists in succession to make their backgrounds look in different colors. My existing code creates these 5 lists without the colors (the default JList). I understand that I can only customize the inside/border of a jlist and not the margin/padding around it? Or Am I wrong and is there a way to it?
Btw, The space above the list is a Jlabel (not shown in the pic above) and the layout managers in use are GroupLayout and GridBagLayout.
UPDATE
AT, as per your suggestion, here is a comparison to how the lists look like when surrounded by a jpanel. The lists in the back are the ones with the Jpanel surrounded with a minimal empty border of size 1.
The issue with creating a JPanel with preferredsize overridden is that the jlists are in horizontal jpanel and above them is another jpanel with labels. So, wrapping jlist in a jpanel is not going to do it.
Please do have a look at this code example. Is it closer to what you wanted, else you define the changes that needs to be done. I be on them as soon as I get the reply from your side :-)
Here is the outcome :
import java.awt.*;
import javax.swing.*;
public class JListExample
{
private JList<String> list1;
private JList<String> list2;
private JList<String> list3;
private JList<String> list4;
private JList<String> list5;
private CustomPanel panel1;
private CustomPanel panel2;
private CustomPanel panel3;
private CustomPanel panel4;
private CustomPanel panel5;
private String[] data = {"one", "two", "three", "four"};
private int width = 110;
private int height = 300;
private void displayGUI()
{
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5, 2, 2));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
panel1 = new CustomPanel(width, height, Color.GRAY, "List 1");
list1 = new JList<String>(data);
panel1.add(list1, gbc);
panel2 = new CustomPanel(width, height,
Color.GREEN.brighter().brighter(), "List 2");
list2 = new JList<String>(data);
panel2.add(list2, gbc);
panel3 = new CustomPanel(width, height,
Color.ORANGE.brighter(), "List 3");
list3 = new JList<String>(data);
panel3.add(list3, gbc);
panel4 = new CustomPanel(width, height,
Color.BLUE.brighter(), "List 4");
list4 = new JList<String>(data);
panel4.add(list4, gbc);
panel5 = new CustomPanel(width, height, Color.RED, "List 5");
list5 = new JList<String>(data);
panel5.add(list5, gbc);
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
contentPane.add(panel4);
contentPane.add(panel5);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JListExample().displayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
private final int GAP = 5;
private int width;
private int height;
private Color backgroundColour;
private JLabel titleLabel;
public CustomPanel(int w, int h, Color c, String title)
{
width = w;
height = h;
backgroundColour = c;
titleLabel = new JLabel(title, JLabel.CENTER);
setBackground(backgroundColour);
setBorder(
BorderFactory.createEmptyBorder(
GAP, GAP, GAP, GAP));
setLayout(new GridBagLayout());
titleLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
add(titleLabel, gbc);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(width, height));
}
}
**LATEST EDIT : **
As rightly pointed by #kleopatra (not something that is new for me :-)), too good judgement call. Done the edit related to that below :
import java.awt.*;
import javax.swing.*;
public class JListExample
{
private final int GAP = 5;
private JList<String> list1;
private JList<String> list2;
private JList<String> list3;
private JList<String> list4;
private JList<String> list5;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JPanel panel4;
private JPanel panel5;
private String[] data = {"one", "two", "three", "four"};
private int width = 110;
private int height = 300;
private GridBagConstraints gbc = new GridBagConstraints();
private void displayGUI()
{
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5, 2, 2));
panel1 = getPanel(Color.GRAY, "List 1");
list1 = new JList<String>(data);
panel2 = getPanel(Color.GREEN.brighter().brighter(), "List 2");
list2 = new JList<String>(data);
panel3 = getPanel(Color.ORANGE.brighter(), "List 3");
list3 = new JList<String>(data);
panel4 = getPanel(Color.BLUE.brighter(), "List 4");
list4 = new JList<String>(data);
panel5 = getPanel(Color.RED, "List 5");
list5 = new JList<String>(data);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
panel1.add(list1, gbc);
panel2.add(list2, gbc);
panel3.add(list3, gbc);
panel4.add(list4, gbc);
panel5.add(list5, gbc);
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
contentPane.add(panel4);
contentPane.add(panel5);
frame.setContentPane(contentPane);
frame.setSize(610, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getPanel(Color c, String title)
{
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBorder(
BorderFactory.createEmptyBorder(
GAP, GAP, GAP, GAP));
panel.setBackground(c);
panel.setLayout(new GridBagLayout());
JLabel label = new JLabel(title, JLabel.CENTER);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
panel.add(label, gbc);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JListExample().displayGUI();
}
});
}
}
I see that GridBagLayout positions it's children with center alignment within cells. How to align left or right?
UPDATE
Constructing code (I know I could reuse c)
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
// placing controls to dialog
GridBagConstraints c;
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(inputSource_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
add(inputSource_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
add(output_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
add(output_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
add(button_panel, c);
When using GridBagLayout for a tabular display of JLabel : JTextField, I like to have a method that makes my GridBagConstraints for me based on the x, y position. For example something like so:
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
The following code makes a GUI that looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GridBagEg {
private static void createAndShowGui() {
PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();
int result = JOptionPane.showConfirmDialog(null, playerEditorPane,
"Edit Player", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// TODO: do something with info
for (PlayerEditorPanel.FieldTitle fieldTitle :
PlayerEditorPanel.FieldTitle.values()) {
System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
playerEditorPane.getFieldText(fieldTitle));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
enum FieldTitle {
NAME("Name"), SPEED("Speed"), STRENGTH("Strength");
private String title;
private FieldTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
};
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
public PlayerEditorPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Player Editor"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
GridBagConstraints gbc;
for (int i = 0; i < FieldTitle.values().length; i++) {
FieldTitle fieldTitle = FieldTitle.values()[i];
gbc = createGbc(0, i);
add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
gbc = createGbc(1, i);
JTextField textField = new JTextField(10);
add(textField, gbc);
fieldMap.put(fieldTitle, textField);
}
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
public String getFieldText(FieldTitle fieldTitle) {
return fieldMap.get(fieldTitle).getText();
}
}
In this example, I display the JPanel in a JOptionPane, but it could just as easily be displayed in a JFrame or JApplet or JDialog or ...
For example
public class DimsPanel extends JPanel
{
public static void main(String[] args){
JFrame main = new JFrame("Dims");
JPanel myPanel = new DimsPanel();
main.setContentPane(myPanel);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(400, 400);
main.setLocationRelativeTo(null);
main.setVisible(true);
}
JButton ok_button = new JButton("OK"), cancel_button = new JButton("Cancel");
JLabel inputSource_label = new JLabel("Input source:"),
output_label = new JLabel("Output:");
JComboBox inputSource_combo = new JComboBox(new String[]{"A", "B", "C"}),
output_combo = new JComboBox(new String[]{"A", "B", "C"});
public DimsPanel(){
super(new BorderLayout());
Box main = new Box(BoxLayout.Y_AXIS);
Dimension labelsWidth = new Dimension(100, 0);
JPanel inputPanel = new JPanel(new BorderLayout());
inputSource_label.setPreferredSize(labelsWidth);
inputPanel.add(inputSource_label, BorderLayout.WEST);
inputPanel.add(inputSource_combo);
JPanel outputPanel = new JPanel(new BorderLayout());
output_label.setPreferredSize(labelsWidth);
outputPanel.add(output_label, BorderLayout.WEST);
outputPanel.add(output_combo);
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
main.add(inputPanel);
main.add(outputPanel);
add(main, BorderLayout.NORTH);
add(button_panel);
}
}
You can run and see it. Resizing works like a charm and the layout code has only 18 lines.
The only disadvantage is that you need to specify the width of the labels by hand. If you really don't want to see setPreferredSize() in the code, then be my guest and go with GridBag. But I personally like this code more.
As you can see in the runnable code below, i try to have a Box with expandable child-boxes. The children Boxes can change they size and this all works good. The main problem is that the size is always relative to the parent. But I want them to have a specific size and in case there is no place anymore use the JScrollPane. At the moment they shrink the other children-boxes only.
I tried Glue and Filler, but it didn't work. The glue just had no effect and the filler had the side effect to keep always some place at the (even when the ScrollPane is in action). That is pretty ugly to have there so much free space.
So, do you know a good way to prevent the Boxes from stretching the children?
Thank you in advance!
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class ExpandableMenueDemo {
Box allBoxes;
ExpandableMenueDemo(){
allBoxes = Box.createVerticalBox();
TitledBorder title;
title = BorderFactory.createTitledBorder("Filter");
allBoxes.setBorder(title);
for (int i = 0 ;i<3;i++){
//generate collapsable components
SubBox b = new SubBox("SubBox"+i);
allBoxes.add(b.getSwingBox());
}
allBoxes.add(Box.createVerticalGlue());
}
public Container getMenue(){
return allBoxes;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
ExpandableMenueDemo m = new ExpandableMenueDemo();
Box mainBox = Box.createHorizontalBox();
mainBox.add(new JScrollPane(m.getMenue()));
mainBox.add(new JTable(20,5));
frame.setContentPane(mainBox);
frame.pack();
frame.setVisible(true);
}
class SubBox{
Box box;
Box header;
String name;
JButton cBtn;
boolean isCollapsed = true;
JLabel headerLine;
SubBox(String name) {
this.name= name;
box = Box.createVerticalBox();
headerLine = new JLabel(name+" () :");
header= Box.createHorizontalBox();
cBtn = new JButton("v");
cBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
if (isCollapsed)show();
else collapse();
}
});
collapse();
header.add(cBtn);
header.add(Box.createHorizontalStrut(10));
header.add(headerLine);
header.add(Box.createHorizontalGlue());
}
Box getSwingBox() {
Box b = Box.createVerticalBox();
b.add(header);
b.add(box);
return b;
}
public void collapse(){
System.out.println("collapse");
box.removeAll();
this.isCollapsed=true;
cBtn.setText("v");
}
public void show(){
System.out.println("show");
box.removeAll();
this.isCollapsed=false;
cBtn.setText("^");
for (int i = 0; i<3;i++) {
Box b = Box.createHorizontalBox();
b.add(Box.createHorizontalStrut(20));
b.add(new JCheckBox("checkBox "+i));
b.add(Box.createHorizontalGlue());
box.add(b);
}
}
}
}
BoxLayout can accepting setXxxSize,
maybe better example for expanding/collapsing JPanels nests another JComponents
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ExpandingPanels extends MouseAdapter {
private ActionPanel[] aps;
private JPanel[] panels;
public ExpandingPanels() {
assembleActionPanels();
assemblePanels();
}
#Override
public void mousePressed(MouseEvent e) {
ActionPanel ap = (ActionPanel) e.getSource();
if (ap.target.contains(e.getPoint())) {
ap.toggleSelection();
togglePanelVisibility(ap);
}
}
private void togglePanelVisibility(ActionPanel ap) {
int index = getPanelIndex(ap);
if (panels[index].isShowing()) {
panels[index].setVisible(false);
} else {
panels[index].setVisible(true);
}
ap.getParent().validate();
}
private int getPanelIndex(ActionPanel ap) {
for (int j = 0; j < aps.length; j++) {
if (ap == aps[j]) {
return j;
}
}
return -1;
}
private void assembleActionPanels() {
String[] ids = {"level 1", "level 2", "level 3", "level 4"};
aps = new ActionPanel[ids.length];
for (int j = 0; j < aps.length; j++) {
aps[j] = new ActionPanel(ids[j], this);
}
}
private void assemblePanels() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 1, 2, 1);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
JPanel p1 = new JPanel(new GridBagLayout());
gbc.gridwidth = GridBagConstraints.RELATIVE;
p1.add(new JButton("button 1"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p1.add(new JButton("button 2"), gbc);
gbc.gridwidth = GridBagConstraints.RELATIVE;
p1.add(new JButton("button 3"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p1.add(new JButton("button 4"), gbc);
JPanel p2 = new JPanel(new GridBagLayout());
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.EAST;
p2.add(new JLabel("enter"), gbc);
gbc.anchor = GridBagConstraints.WEST;
p2.add(new JTextField(8), gbc);
gbc.anchor = GridBagConstraints.CENTER;
p2.add(new JButton("button 1"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
p2.add(new JButton("button 2"), gbc);
JPanel p3 = new JPanel(new BorderLayout());
JTextArea textArea = new JTextArea(8, 12);
textArea.setLineWrap(true);
p3.add(new JScrollPane(textArea));
JPanel p4 = new JPanel(new GridBagLayout());
addComponents(new JLabel("label 1"), new JTextField(12), p4, gbc);
addComponents(new JLabel("label 2"), new JTextField(16), p4, gbc);
gbc.gridwidth = 2;
gbc.gridy = 2;
p4.add(new JSlider(), gbc);
gbc.gridy++;
JPanel p5 = new JPanel(new GridBagLayout());
p5.add(new JButton("button 1"), gbc);
p5.add(new JButton("button 2"), gbc);
p5.add(new JButton("button 3"), gbc);
p5.add(new JButton("button 4"), gbc);
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
p4.add(p5, gbc);
panels = new JPanel[]{p1, p2, p3, p4};
}
private void addComponents(Component c1, Component c2, Container c, GridBagConstraints gbc) {
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
c.add(c1, gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
c.add(c2, gbc);
gbc.anchor = GridBagConstraints.CENTER;
}
private JPanel getComponent() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(1, 3, 0, 3);
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int j = 0; j < aps.length; j++) {
panel.add(aps[j], gbc);
panel.add(panels[j], gbc);
panels[j].setVisible(false);
}
JLabel padding = new JLabel();
gbc.weighty = 1.0;
panel.add(padding, gbc);
return panel;
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
ExpandingPanels test = new ExpandingPanels();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(test.getComponent()));
f.setSize(360, 500);
f.setLocation(200, 100);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(doRun);
}
}
class ActionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private String text;
private Font font;
private boolean selected;
private BufferedImage open, closed;
public Rectangle target;
final int OFFSET = 30,
PAD = 5;
ActionPanel(String text, MouseListener ml) {
this.text = text;
addMouseListener(ml);
font = new Font("sans-serif", Font.PLAIN, 12);
selected = false;
setBackground(new Color(200, 200, 220));
setPreferredSize(new Dimension(200, 20));
setBorder(BorderFactory.createRaisedBevelBorder());
setPreferredSize(new Dimension(200, 20));
createImages();
setRequestFocusEnabled(true);
}
public void toggleSelection() {
selected = !selected;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
if (selected) {
g2.drawImage(open, PAD, 0, this);
} else {
g2.drawImage(closed, PAD, 0, this);
}
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = font.getLineMetrics(text, frc);
float height = lm.getAscent() + lm.getDescent();
float x = OFFSET;
float y = (h + height) / 2 - lm.getDescent();
g2.drawString(text, x, y);
}
private void createImages() {
int w = 20;
int h = getPreferredSize().height;
target = new Rectangle(2, 0, 20, 18);
open = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = open.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fillRect(0, 0, w, h);
int[] x = {2, w / 2, 18};
int[] y = {4, 15, 4};
Polygon p = new Polygon(x, y, 3);
g2.setPaint(Color.green.brighter());
g2.fill(p);
g2.setPaint(Color.blue.brighter());
g2.draw(p);
g2.dispose();
closed = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g2 = closed.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fillRect(0, 0, w, h);
x = new int[]{3, 13, 3};
y = new int[]{4, h / 2, 16};
p = new Polygon(x, y, 3);
g2.setPaint(Color.red);
g2.fill(p);
g2.setPaint(Color.blue.brighter());
g2.draw(p);
g2.dispose();
}
}
Instead of re-inventing the wheel, you might consider to use JXTaskPane/-Container contained in SwingX. Its demo shows it in action (as taskPanes) at the left - that's the part for choosing the demos.