public class InputURL {
public InputURL() {
input();
}
private static JFrame mainFrame = Launcher.returnFrame();
private static JPanel mainPanel;
private void input(){
//Defining a Panel on which everything will be set
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
//To put the GridBagLayout Constraints
GridBagConstraints c = new GridBagConstraints();
//Set Panel Size
mainPanel.setSize(Constants.windowWidth,Constants.windowHeight);
//Setting the Input Box
JTextField inputURL = new JTextField();
c.fill = GridBagConstraints.CENTER;
c.ipady = 50;
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
mainPanel.add(inputURL, c);
//Adding the start button
JButton submitURL = new JButton(Constants.SUBMIT_URL_BUTTON);
submitURL.addActionListener(new ActionListener() {
//The action performed by the start button
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
}
});
//The placement of the button
c.fill = GridBagConstraints.VERTICAL;
c.ipady = 50;
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 2;
mainPanel.add(submitURL, c);
//Adding the components on Panel to Frame
mainFrame.add(mainPanel);
}
}
The ouput and expected output can be viewed here. Need help regarding the Output. E.G.:
I've tried using GridBagConstraints and for some reason I cannot play much with the UI.
A lot will come down to you final needs, for example, this just makes use of some of the basic properties of GridBagConstraints
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout {
public static void main(String[] args) {
new TestLayout();
}
public TestLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField inputURL;
private JButton submitURL ;
public TestPane() {
inputURL = new JTextField(20);
submitURL = new JButton("Submit the URL");
submitURL.setMargin(new Insets(10, 10, 10, 10));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 10, 10);
add(new JLabel("Header"), gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 10, 20, 10);
add(inputURL, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.weighty = 1.0;
add(submitURL, gbc);
}
}
}
A more complex solution might make use of compound layouts, using a mixture of BorderLayout, GridLayout and GridBagLayout
For example...
public class TestPane extends JPanel {
private JTextField inputURL;
private JButton submitURL ;
public TestPane() {
setLayout(new BorderLayout());
JLabel header = new JLabel("Header");
header.setHorizontalAlignment(JLabel.CENTER);
header.setBorder(new EmptyBorder(10, 10, 10, 10));
add(header, BorderLayout.NORTH);
inputURL = new JTextField(20);
submitURL = new JButton("Submit the URL");
submitURL.setMargin(new Insets(10, 10, 10, 10));
JPanel content = new JPanel(new GridLayout(2, 1));
JPanel field = new JPanel(new GridBagLayout());
field.add(inputURL);
content.add(field);
JPanel actions = new JPanel(new GridBagLayout());
actions.add(submitURL);
content.add(actions);
add(content);
}
}
While it might sound stupid, spend more time focusing on the actual workflow of the user, this will lead you to the best layout decisions, rather then focus on the physical layout itself
Related
everyone. I would like to have custom JPanels ( I prefer absolute position layout for my use) in GridLayout. GridLayout is in ScrollPane.
public class App extends JFrame {
public App() {
super("bamlOperator");
JPanel panel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(scrollPane, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel.add(new MyCustomPanel());
panel.add(new MyCustomPanel());
panel.add(new MyCustomPanel());
panel.add(new MyCustomPanel());
panel.add(new MyCustomPanel());
panel.add(new MyCustomPanel());
pack();
setVisible(true);
}
public static void main(String[] args) {
new App();
}
}
And MyPanel :
public class MyCustomPanel extends JPanel {
private JLabel aaa = new JLabel("aaa:");
private JLabel bbb = new JLabel("bbb");
private JLabel ccc = new JLabel("ccc:");
public MyCustomPanel() {
setPreferredSize(new Dimension(100,100));
JPanel amlPanel = new JPanel();
amlPanel.setLayout(null);
amlPanel.setBounds(0,0,100,100);
aaa.setBounds(10,20,30,40);
amlPanel.add(aaa);
bbb.setBounds(20,30,40,50);
amlPanel.add(bbb);
ccc.setBounds(30,40,50,60);
amlPanel.add(ccc);
add(amlPanel);
}
}
But it doesnt work.
I said, I prefer absolute position layout but I know It is bad practice. I can use another but I need JPanel something like this :
Project of JPanel
So, your fundamental problem is you're mixing absolute layouts with layout managers - the problem is MyCustomPanel isn't providing any sizing hints which the layout manager can use to make better decisions about how best to layout your component. So, if you really want to use absolute layouts, you're going to have to do ALL the work that the layout management API would have done for you
Can you tell me which layout manager will be the best for my use?
All of them. Don't get fixated on a single layout manager achieving everything your want, instead, combine them together to produce the results you're after.
I don't have your "exact" requirements, but I was able to achieve this by using BorderLayout and GridBagLayout
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
public MainPane() {
// You could use a GridLayout, but GridBagLayout will
// honour the preferred sizs of each component
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
GridBagConstraints gbc = new GridBagConstraints();
add(new LeftPane(), gbc);
add(new MiddleLeftPane(), gbc);
add(new MiddlePane(), gbc);
add(new RightPane(), gbc);
}
}
public class LeftPane extends JPanel {
public LeftPane() {
setLayout(new GridBagLayout());
JPanel main = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
for (int index = 0; index < 6; index++) {
if (index % 2 == 0) {
gbc.anchor = GridBagConstraints.LINE_START;
} else {
gbc.anchor = GridBagConstraints.LINE_END;
}
main.add(new JLabel("Label"), gbc);
}
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(main, gbc);
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
add(new JButton("Button"));
}
}
public class MiddleLeftPane extends JPanel {
public MiddleLeftPane() {
setLayout(new BorderLayout());
BufferedImage img = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.drawLine(0, 0, 200, 200);
g2d.drawLine(200, 0, 0, 200);
g2d.dispose();
JLabel label = new JLabel(new ImageIcon(img));
label.setBorder(new LineBorder(Color.GRAY));
add(label);
}
}
public class RightPane extends JPanel {
public RightPane() {
setLayout(new BorderLayout());
BufferedImage img = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.drawLine(0, 0, 200, 200);
g2d.drawLine(200, 0, 0, 200);
g2d.dispose();
JLabel label = new JLabel(new ImageIcon(img));
label.setBorder(new LineBorder(Color.GRAY));
add(label);
}
}
public class MiddlePane extends JPanel {
public MiddlePane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JButton("Button"), gbc);
gbc.gridx++;
add(new JButton("Button"), gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 2;
add(new JButton("Button"), gbc);
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(new JTextArea("Text Area", 5, 10)), gbc);
}
}
}
You are using a null layout for layout of your custom panel. When you add this inside another panel of grid layout, since the sizes are not set, it would not be painted. Try using a proper layout for your custom panel as well.
And, see the answer for Using a JPanel with a null layout .
I am building a toolbar for a program using GridBagLayout, but even using weightx and fill, the components are not the sizes they should be and they are not filling the JPanel.
For instance, when the total size of jidest.x_size is 1920, the total size of the components is 1776
package jide.parts;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import jide.jidest;
#SuppressWarnings("serial")
public class BottomBar extends JPanel implements MouseListener{
JPanel charCountPanel = new JPanel();
JPanel lineCountPanel = new JPanel();
JPanel cursorPositionPanel = new JPanel();
JPanel spacer1 = new JPanel();
JPanel spacer2 = new JPanel();
JPanel spacer3 = new JPanel();
JPanel morespace = new JPanel();
JLabel charCount = new JLabel("charcount");
JLabel lineCount = new JLabel("linecount");
JLabel cursorPosition = new JLabel("TEST:TEST");
public BottomBar(){
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
charCountPanel.setToolTipText("Click here for more complete stats");
lineCountPanel.setToolTipText("Click here for more complete stats");
setPreferredSize(new Dimension((int) jidest.x_size,20));
setBackground(Color.red);
cursorPositionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
cursorPositionPanel.add(cursorPosition);
//cursorPositionPanel.setSize(50,20);
lineCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
lineCountPanel.add(lineCount);
//lineCountPanel.setSize(50,20);
charCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
charCountPanel.add(charCount);
//charCountPanel.setSize(50,20);
morespace.setSize((int) (jidest.x_size-156),20);
//add(cursorPositionPanel);
spacer1.setBackground(Color.BLACK);
//spacer1.setSize(1,20);
spacer2.setBackground(Color.BLACK);
//spacer2.setSize(1,20);
spacer3.setBackground(Color.BLACK);
//spacer3.setPreferredSize(new Dimension(1,20));
//size is 156, width is 7
gbc.fill=GridBagConstraints.BOTH;
gbc.weighty=1;
gbc.gridx = 1;
gbc.weightx=(1.0)/jidest.x_size;
add(spacer1,gbc);
gbc.gridx=2;
gbc.weightx=(50.0)/jidest.x_size;
add(cursorPositionPanel,gbc);
gbc.gridx=3;
gbc.weightx=(1.0)/jidest.x_size;
add(spacer2,gbc);
gbc.gridx=4;
gbc.weightx=(50.0)/jidest.x_size;
add(lineCountPanel,gbc);
gbc.gridx=5;
gbc.weightx=(1.0)/jidest.x_size;
add(spacer3,gbc);
gbc.gridx=6;
gbc.weightx=(50.0)/jidest.x_size;
add(charCountPanel,gbc);
gbc.gridy = 0;
gbc.gridx=0;
gbc.weightx=(jidest.x_size-153)/jidest.x_size;
add(morespace,gbc);
System.out.println((spacer1.getWidth()+cursorPositionPanel.getWidth()+spacer2.getWidth()+lineCountPanel.getWidth()+spacer3.getWidth()+morespace.getWidth())+" should be " + jidest.x_size);
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
In future, please post an MCVE. This works to spread the components across the width of the bar.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BottomBarGUI {
private JComponent ui = null;
BottomBarGUI() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(new BottomBar());
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BottomBarGUI o = new BottomBarGUI();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
class BottomBar extends JPanel {
JPanel charCountPanel = new JPanel();
JPanel lineCountPanel = new JPanel();
JPanel cursorPositionPanel = new JPanel();
JPanel spacer1 = new JPanel();
JPanel spacer2 = new JPanel();
JPanel spacer3 = new JPanel();
JPanel morespace = new JPanel();
JLabel charCount = new JLabel("charcount");
JLabel lineCount = new JLabel("linecount");
JLabel cursorPosition = new JLabel("TEST:TEST");
public BottomBar() {
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 0;
gbc.weightx = .5;
charCountPanel.setToolTipText("Click here for more complete stats");
lineCountPanel.setToolTipText("Click here for more complete stats");
setBackground(Color.red);
cursorPositionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
cursorPositionPanel.add(cursorPosition);
lineCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
lineCountPanel.add(lineCount);
charCountPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
charCountPanel.add(charCount);
spacer1.setBackground(Color.BLACK);
spacer2.setBackground(Color.BLACK);
spacer3.setBackground(Color.BLACK);
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.gridx = 0;
add(spacer1, gbc);
gbc.gridx = 1;
add(cursorPositionPanel, gbc);
gbc.gridx = 2;
add(spacer2, gbc);
gbc.gridx = 3;
add(lineCountPanel, gbc);
gbc.gridx = 4;
add(spacer3, gbc);
gbc.gridx = 5;
add(charCountPanel, gbc);
gbc.gridx = 0;
}
}
I am using a GridBagLayout for my components in a JFrame. I just started using it, and I keep confusing myself. What I want is; Patch notes in the top left, buttons (vertical) on the right, play button on the bottom. I'm not sure what the issue really is, but can you please help me organize this?
Here's my code:
package counter.main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class HomeFrame {
private static JPanel panel;
private static JButton play = new JButton("Play");
private static JPanel p;
File patch = new File(Main.class.getResource("/counter/res/ResourceCounterPatchNotes.txt").getFile());
//private static JLabel text;
public static JLabel greet = new JLabel("", SwingConstants.CENTER);
static JFrame frame = new JFrame("Resource Counter - Home"); {
frame.setSize(800, 500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.repaint();
frame.revalidate();
createView();
}
private void createView() {
setIcon();
panel = new JPanel();
frame.getContentPane().add(panel);
p = new JPanel();
frame.getContentPane().add(p);
p.setLayout(new FlowLayout(FlowLayout.CENTER, 400, 360));
play.setPreferredSize(new Dimension(200, 70));
p.add(play);
JPanel p2 = new JPanel();
frame.getContentPane().add(p2);
p2.setLayout(new GridBagLayout());
JButton button = new JButton(" Button ");
play.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
Thread.sleep(500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
SelectionFrame.frame1.setVisible(true);
frame.setVisible(false);
}
});
JTextArea ta = new JTextArea();
p2.setBackground(Color.BLACK);
ta.setForeground(Color.WHITE);
ta.setFont(new Font("Lucida Sans", Font.PLAIN, 12));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(-150, 5, 5, 30);
gbc.gridx = 0;
gbc.gridy = 0;
p2.add(ta, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
p2.add(button, gbc);
/*gbc.anchor = GridBagConstraints.SOUTH;
gbc.gridx = 0;
gbc.gridy = 2;
p2.add(play, gbc);*/
try {
ta.read(new FileReader(patch), null);
ta.setEditable(false);
//p2.add(ta, BorderLayout.WEST);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
greet.setFont(new Font( "Dialog", Font.BOLD, 20));
frame.getContentPane().add(greet, BorderLayout.NORTH);
}
public void setIcon() {
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/counter/res/Iron-Pickaxe-icon.png")));
}
}
Here is what I get:
Your code is a mess (sorry), I could spent a lot of time trying to unravel your compound layouts, but it would be easier to just start again. Not saying that you might not consider using a compound layout concept, but I think that's what's got you into such a mess to start with...
So I've basically create a simplified example of what I "guess" your description is asking for...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = gbc.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
JTextArea patch = new JTextArea(10, 20);
add(new JScrollPane(patch), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
for (int index = 0; index < 6; index++) {
add(new JButton("Button #" + index), gbc);
gbc.gridy++;
}
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JButton("Play >"), gbc);
}
}
}
With layouts, it's best to start with pen and paper, group the elements you need to together (like the buttons down the right side for example) and devise a plan for how you might lay them out and prototype of view ideas...
Updated
1) How can I have it so that there is space between the TextArea and the buttons, and vertical space on the buttons? I tried using the Insets but I haven't arranged the numbers in a correct way yet.
insets is the correct way to go...
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(2, 8, 2, 4);
gbc.anchor = GridBagConstraints.NORTH;
for (int index = 0; index < 6; index++) {
core.add(new JButton("Button #" + index), gbc);
gbc.gridy++;
}
2) I would like the "Play" button at the center-bottom of the screen, and have it be larger
You "could" do this with GridBagLayout, but I decided not to, as it can cause some issues if you're not careful with how your setup the constraints for the other components, so instead, I used a combination of BorderLayout and GridBagLayout.
To make the "play" button larger, you could modify the font or adjust the button's margins...
playButton.setMargin(new Insets(12, 12, 12, 12));
depending on the effect you're after
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout(0, 4));
JPanel core = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JTextArea patch = new JTextArea(10, 20);
core.add(new JScrollPane(patch), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(2, 8, 2, 4);
gbc.anchor = GridBagConstraints.NORTH;
for (int index = 0; index < 6; index++) {
core.add(new JButton("Button #" + index), gbc);
gbc.gridy++;
}
add(core);
JButton playButton = new JButton("Play >");
playButton.setMargin(new Insets(12, 12, 12, 12));
add(playButton, BorderLayout.SOUTH);
}
}
I'm fairly new to java and I'm having a problem trying to put more than one button on a row,
at the moment I'm adding both buttons to the panel, but I don't know how to separate their x locations, i.e. they are both being added directly on to of each other.
Do I need to create a new layout or can I find a solution using what I have at the moment?
public class Question1 {
public static void main (String[] args){
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame{
MyFrame(String title){
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init(){
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
this.setContentPane(mainPanel);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf,cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JButton b = new JButton("Submit");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
b = new JButton("Cancel");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
this.pack();
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) ;
this.setVisible(true);
}
Just increment the gridx value:
JButton b = new JButton("Submit");
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
b = new JButton("Cancel");
cButton.gridx++;
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
Also you need to use the constraints created when adding your component to the grid bag layout using container.
e.g.,
import java.awt.*;
import javax.swing.*;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
private static final int GAP = 2;
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JTextField tf = new JTextField(20);
mainPanel.add(tf, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
JButton b = new JButton("Submit");
mainPanel.add(b, gbc);
b = new JButton("Cancel");
gbc.gridx++;
mainPanel.add(b, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
Try the following code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf, cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JPanel demoPanel = new JPanel();
JButton b = new JButton("Submit");
gbLayout.setConstraints(demoPanel, cButton);
demoPanel.add(b);
b = new JButton("Cancel");
// gbLayout.setConstraints(b,cButton);
demoPanel.add(b);
mainPanel.add(demoPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
I have just put the two buttons inside a JPanel and put the JPanel inside the GridBagLayout Panel !
I'm not exactly new to java (I've been using it for a year now) but this is my first go at swing. I'm trying to make a very simple chat client to learn both socket and swing at once. My question is "What must I do to align my panels correctly?". I've tried a lot of things (Though I don't have it in my code). Usually I work something like this out on my own, but I'm to the point I need to ask for help. Do I need to change the wieghtx, weighty? What I want the client to look like is something like this.
This is what it currently looks like.
Here is my code.
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
GridBagConstraints c = new GridBagConstraints();
//Main Panel
JPanel window = new JPanel();
window.setLayout(new GridBagLayout());
window.setBackground(Color.black);
//Panels
JPanel display = new JPanel();
JPanel chat = new JPanel();
chat.setLayout(new GridBagLayout());
JPanel users = new JPanel();
display.setBackground(Color.blue);
c.gridx = 0;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(display, c);
chat.setBackground(Color.red);
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 1;
c.insets= new Insets(5,5,5,5);
window.add(chat, c);
users.setBackground(Color.green);
c.gridx = 2;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(users, c);
//Buttons
//Text fields
JTextArea text = new JTextArea("DEREADFADSFEWFASDFSADFASDF");
c.gridx = 0;
c.gridy = 0;
chat.add(text);
JTextField input = new JTextField("type here to chat", 50);
c.gridx = 0;
c.gridy = 1;
c.insets= new Insets(5,5,5,5);
chat.add(input);
add(window);
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
}
If you wanted something like this as an output :
You can take help from this code example, though you can remove the last ButtonPanel if you don't need that :
package to.uk.gagandeepbali.swing.messenger.gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextField;
public class ChatPanel extends JPanel
{
private JButton backButton;
private JButton exitButton;
private JButton sendButton;
private JTextPane chatPane;
private JTextPane namePane;
private JTextField chatField;
private GridBagConstraints gbc;
private final int GAP = 10;
private final int SMALLGAP = 1;
public ChatPanel()
{
gbc = new GridBagConstraints();
}
protected void createGUI()
{
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
centerPanel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
chatPane = new JTextPane();
JScrollPane scrollerChat = new JScrollPane();
scrollerChat.setBorder(BorderFactory.createTitledBorder("Chat"));
scrollerChat.setViewportView(chatPane);
centerPanel.add(scrollerChat, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
namePane = new JTextPane();
JScrollPane scrollerName = new JScrollPane(namePane);
scrollerName.setBorder(BorderFactory.createTitledBorder("Names"));
centerPanel.add(scrollerName, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.HORIZONTAL;
chatField = new JTextField();
chatField.setOpaque(true);
chatField.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("")
, BorderFactory.createEmptyBorder(SMALLGAP, SMALLGAP, SMALLGAP, SMALLGAP)));
centerPanel.add(chatField, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
sendButton = new JButton("Send");
sendButton.setBorder(BorderFactory.createTitledBorder(""));
centerPanel.add(sendButton, gbc);
JPanel bottomPanel = new JPanel();
bottomPanel.setOpaque(true);
bottomPanel.setBackground(Color.WHITE);
bottomPanel.setBorder(
BorderFactory.createTitledBorder(""));
bottomPanel.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.WHITE);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
backButton = new JButton("Back");
exitButton = new JButton("Exit");
buttonPanel.add(backButton);
buttonPanel.add(exitButton);
bottomPanel.add(buttonPanel, BorderLayout.CENTER);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public JTextPane getChatPane()
{
return chatPane;
}
public JTextPane getNamePane()
{
return namePane;
}
public JTextField getChatField()
{
return chatField;
}
public JButton getExitButton()
{
return exitButton;
}
public JButton getBackButton()
{
return backButton;
}
public JButton getSendButton()
{
return sendButton;
}
}
What you could do, and probably gives the desired result
JPanel somethingHere = ...;
JPanel chat = ...;
JPanel userList = ...;
JPanel leftPanel = new JPanel( new BorderLayout() );
leftPanel.add( somethingHere, BorderLayout.CENTER );
leftPanel.add( chat, BorderLayout.SOUTH );
JPanel total = new JPanel( new BorderLayout() );
total.add( leftPanel, BorderLayout.CENTER );
total.add( userList, BorderLayout.EAST );
Way simpler then messing with GridBagLayout
Here is what I came out with thus far. The red box is where I plan to add a simple 2D avatar interface with LWJGL.
Here is the code for it
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
//Main Panels
JPanel window = new JPanel(new BorderLayout());
JPanel center = new JPanel(new BorderLayout());
JPanel right = new JPanel(new BorderLayout());
//Panels
JPanel display = new JPanel( new BorderLayout());
display.setBackground(Color.red);
JPanel chat = new JPanel();
chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
chat.setBackground(Color.blue);
JPanel users = new JPanel(new BorderLayout());
users.setBackground(Color.green);
//TextFields
JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50);
chatBox.setEditable(false);
JTextField chatWrite = new JTextField();
JScrollPane userList = new JScrollPane();
JTextField userSearch = new JTextField(10);
userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
users.add(userList);
users.add(userSearch, BorderLayout.NORTH);
chat.add(chatBox);
chat.add(chatWrite);
chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
//Menu bar
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem ipconnect = new JMenuItem("Connect to IP");
file.add(ipconnect);
file.add(exit);
menu.add(file);
//Main window adding
right.add(users);
center.add(display, BorderLayout.CENTER);
center.add(chat, BorderLayout.SOUTH);
window.add(center, BorderLayout.CENTER);
window.add(right, BorderLayout.EAST);
window.add(menu, BorderLayout.NORTH);
add(window);
//Listeners
chatWrite.addKeyListener(new KeyLis());
ipconnect.addActionListener(new ActLis());
exit.addActionListener(new ActLis());
}
static class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println("Message recieved.");
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "Exit"){
System.exit(0);
} else if(e.getActionCommand() == "Connect to IP"){
System.out.println("Connecting....");
JFrame frameip = new JFrame();
JPanel panelip = new JPanel();
JButton buttonip = new JButton("Hello");
frameip.add(panelip);
panelip.add(buttonip);
JDialog ippop = new JDialog(frameip, "Enter IP", false);
}
}
}
}
I had to build a similar layout using a GridBagLayout. The code below shows how I achieved it.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridBagLayoutTest {
public GridBagLayoutTest() {
JFrame jframe = new JFrame();
jframe.setLayout(new GridBagLayout());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(800, 600);
jframe.setVisible(true);
// Left
JPanel leftPanel = new JPanel(new GridBagLayout());
leftPanel.setBackground(Color.YELLOW);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .7f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
jframe.add(leftPanel, gridBagConstraints);
JPanel leftTopPanel = new JPanel(new FlowLayout());
leftTopPanel.setBackground(Color.RED);
GridBagConstraints gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .7f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 0;
leftPanel.add(leftTopPanel, gridBagConstraints0);
JPanel leftMiddlePanel = new JPanel(new FlowLayout());
leftMiddlePanel.setBackground(Color.BLACK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .2f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 1;
leftPanel.add(leftMiddlePanel, gridBagConstraints0);
JPanel leftBottomBottomPanel = new JPanel(new FlowLayout());
leftBottomBottomPanel.setBackground(Color.PINK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .1f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 2;
leftPanel.add(leftBottomBottomPanel, gridBagConstraints0);
// Right
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.GREEN);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .3f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
jframe.add(rightPanel, gridBagConstraints);
}
public static void main (String args[]) {
new GridBagLayoutTest();
}