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.
Related
I have read several articles regarding this topic as well the documentation, yet I still can't seem to solve my problem.
I have created a GUI that needs to be resizeable; however, I would like to maintain that there are 3 JTextFields for each row.
I have tried adjusting the weightx, yet no success.
Here is a snippet of my code:
JPanel panelMain = new JPanel();
getContentPane().add(panelMain);
JPanel panelForm = new JPanel(new GridBagLayout());
panelMain.add(panelForm);
//JScrollPane scrollpane = new JScrollPane(panelForm);
//panelMain.add(scrollpane);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
// Row 1
buttonAddCourses = new JButton("Add Credit Hours");
buttonAddCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c.gridx = 0;
c.weightx = 0.2;
for(int i = 0; i < 15; i++) {
JTextField newTextField = new JTextField(20);
listTextFields.add(newTextField);
panelMain.add(newTextField,c);
c.gridy++;
}
panelMain.validate();
panelMain.repaint();
}
});
panelForm.add(buttonAddCourses, c);
c.gridx++;
Before Resize : !https://imgur.com/a/XCUtJ
After Resize :
!https://imgur.com/a/a4Qo4
JPanel panelMain = new JPanel(); // <- gets a FlowLayout by default
// ..
JPanel panelForm = new JPanel(new GridBagLayout()); // panel with GBL
// ...
panelMain.add(newTextField,c); // No, this should be panelForm.add(..);
JScrollPane scrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(23, 11, 603, 123);
contentPane.add(scrollPane);
JPanel panel = new JPanel();
JLabel[] labels=new JLabel[callout.getRedCount()]; //callout.getRedCount() = 8
panel.setLayout(null);
int x = 50;
int y = 50;
for (int i=0;i<callout.getRedCount();i++){ //callout.getRedCount() = 8
labels[i]=new JLabel("Red" + i);
labels[i].setBounds(x, y, 32, 32);
panel.add(labels[i]);
x += 150;
}
scrollPane.setViewportView(panel);
I'm trying to add these labels to the panel that is embedded in a scrollPane. The labels are display correctly except for when the last few are over the size of the panel. The scrollPane does not scroll. I have tried .setLayout to various different layouts and still no results. Am I missing something on how to do this?
Okay I got this working with GridBagLayout.
public static void main(String args[]){
JFrame contentPane = new JFrame();
JScrollPane scrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(23, 11, 50, 50);
contentPane.add(scrollPane);
JPanel panel = new JPanel();
JLabel[] labels=new JLabel[8]; //callout.getRedCount() = 8
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0,10,0,0);
int x = 50;
int y = 50;
for (int i=0;i<8;i++){ //callout.getRedCount() = 8
labels[i]=new JLabel("Red" + i);
gbc.gridx = i;
panel.add(labels[i], gbc);
}
scrollPane.setViewportView(panel);
contentPane.setSize(50,50);
contentPane.setVisible(true);
}
You can change around the values, this is very rough. Hope this helps!
As you can see in my code, there are two scroll panes at the bottom. I need my gui to show both of these scroll panes on the right side, the smaller one(displaying the current amount of money the player has, this one I need to stay one line thick) and the second one, which will be constantly spitting out information of the player's rolls on the bottom.
Also how do I make it so that my combo box listener will give every item a 10 to its output to start out with then when it is being sent out it gives each 1 more so that they have their unique number starting at 11 then 12, 13, and so on.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dicebot extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
private JButton btnConfirm;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dicebot frame = new dicebot();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dicebot() {
setTitle("Dice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldStartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMultiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_textFieldPassword = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldOdds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMaxBet = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}else if (e.getSource() == btnConfirm){
Dicebotcode dbc = new Dicebotcode();
dbc.dbc();
}
}
}
Two things...
One, if you've added the same scroll pane twice...
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
^--- Note no "l"
And, even if you have added the two scroll pane instances, you've added them to the same place, BorderLayout.CENTER
BorderLayout only allows a single component to be added to one of the available positions it supports, so, in this case, only the second scroll pane would be visible
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 :
I have a JPanel with the following code:
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(3, 2, 10, 30));
final JTextField fileName = new JTextField();
pane.add(fileName);
JButton creater = new JButton("Create File");
pane.add(creater);
JButton deleter = new JButton("Delete File");
pane.add(deleter);
I was wondering, how do I make it so that the JTextField takes up two spaces on the GridLayout, while having the two buttons share a row by taking up one space each on the same line?
It is a hard to do with GridLyout. You have create wider cells (e.g. new GridLayout(2, 2, 10, 30), then add TextField to the fist cell. Then you have to create yet another panel with GridLayout(2, 1), put it into the cell in second line and add your button into 1 st cell of this nested grid layout.
Shortly you need GridLayout into other GridLayout.
There are better tools to implement this. First take a look on GridBagLayout. It is just to be sure that life is not always pick-nick :). Then take a look on alternative solutions like MigLayout. It is not a part of JDK but it really powerful tool that makes your life easier.
You cannot do column spans with GridLayout. I recomend you try GridBagLayout and GridBagConstraints
After trashing the suggestion of 3rd party layouts, and since I possess a malevolent hatred of GBL, I thought it was about to time to 'put my code where my mouth is' for public scrutiny (and trashing).
This SSCCE uses a nested layout.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class SimpleLayoutTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JPanel ui = new JPanel( new BorderLayout(20,20) );
// I would go for an EmptyBorder here, but the filled
// border is just to demonstrate where the border starts/ends
ui.setBorder( new LineBorder(Color.RED,15) );
// this should be a button that pops a JFileChooser, or perhaps
// a JTree of the existing file system structure with a JButton
// to prompt for the name of a new File.
final JTextField fileName = new JTextField();
ui.add(fileName, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 10, 30));
ui.add(buttonPanel, BorderLayout.CENTER);
JButton creater = new JButton("Create File");
buttonPanel.add(creater);
JButton deleter = new JButton("Delete File");
buttonPanel.add(deleter);
JOptionPane.showMessageDialog(null, ui);
}
};
SwingUtilities.invokeLater(r);
}
}
Take a look at the tutorial on How to Use GridBagLayout.
Sample code:
JPanel pane = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
pane.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
final JTextField fileName = new JTextField();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 0;
pane.add(fileName, c);
JButton creater = new JButton("Create File");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
pane.add(creater, c);
JButton deleter = new JButton("Delete File");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
pane.add(deleter, c);