So I'm originally using a BorderLayout for the mainscreen, but once the user hits start, it converts to a GridBagLayout with the intention of being 80% game screen on the left and 20% menu, score, etc on the right.
| --- GameScreen --- | Score |
However I'm having difficulty getting this as either I can't resize the score screen or it doesn't print out correctly at all. This is the code I'm currently using.
public Launcher(String title) {
super(title);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
cp = getContentPane();
// cp.setSize((int)(1920*0.5), (int)(1080*0.5));
cp.setLayout(new BorderLayout());
panel = new JPanel();
panel.setBackground(Color.YELLOW);
// panel.setSize(this.getWidth()/4, this.getHeight());
panel.add(startButton);
panel.add(pauseButton);
panel.add(quitButton);
setSize(1920, 1100);
cp.add(panel, BorderLayout.SOUTH);
this.getContentPane().setBackground(Color.GREEN);
//ActionListenerStuff for buttons
.
.
.
This is the ACtionListenerMethod that calls the updateGui method.
else if (e.getSource() == startButton) {
cp.remove(panel);
panel.setSize(1200, getHeight());
state = STATE.RUNNING;
updateState();
updateGui();
createGameLoop();
}
This is the method where I change the layout and add the JPanels.
private void updateGui() {
cp.setLayout(new GridBagLayout());
GridBagConstraints layoutConstraints = new GridBagConstraints();
layoutConstraints.fill = GridBagConstraints.VERTICAL;
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.8;
cp.add(house, layoutConstraints);
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.2;
cp.add(panel, layoutConstraints);
}
It ends up with the 'house' JPanel being 80% but the 'panel' variable is still on the border of the bottom from the previous borderlayout. Not sure why though.
I'm not entirely sure if that's enough information and will gladly post whatever information that's required.
Edit: Tried adding layoutConstraints.gridy = 1; but that didn't work either.
private void updateGui() {
cp.setLayout(new GridBagLayout());
GridBagConstraints layoutConstraints = new GridBagConstraints();
layoutConstraints.fill = GridBagConstraints.VERTICAL;
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.8;
house.setMinimumSize(new Dimension(1600, 1080));
cp.add(house, layoutConstraints);
GridBagConstraints layoutConstraints2 = new GridBagConstraints();
layoutConstraints2.fill = GridBagConstraints.VERTICAL;
layoutConstraints2.weighty = 1;
layoutConstraints2.weightx = 0.2;
layoutConstraints.gridy = 1;
cp.add(panel, layoutConstraints2);
}
private void updateState() {
if (roomGenerator == null) {
roomGenerator = new RoomGenerator();
}
roomGenerator.updateRoom();
Room room = roomGenerator.getRoom();
house = (House) roomGenerator.getRoom();
house.setSize(300, getHeight());
this.getContentPane().add(house, BorderLayout.CENTER);
startButton.setVisible(false);
// this plugin puts the buttons in the House JPanel
// house.add(pauseButton);
// house.add(quitButton);
}
This is what I currently have. This is what's displaying.
The drawing should be the "80%" portion and the yellow should be the 20%.
Edit 2: Using Camickr's changes I end up with this.
It's a step in the right direction, but it's not setting the size of the house JPanel correctly as far as I can tell.
private void updateGui() {
cp.add(panel, BorderLayout.LINE_END);
panel.setVisible(true);
cp.revalidate();
}
private void updateState() {
if (roomGenerator == null) {
roomGenerator = new RoomGenerator();
}
roomGenerator.updateRoom();
Room room = roomGenerator.getRoom();
house = (House) roomGenerator.getRoom();
house.setSize(1500, getHeight());
this.getContentPane().add(house, BorderLayout.CENTER);
startButton.setVisible(false);
}
If anyone was curious I figured it out. I did it via this way...
cp.setLayout(new GridBagLayout());
GridBagConstraints layoutConstraints = new GridBagConstraints();
layoutConstraints.fill = GridBagConstraints.BOTH;
layoutConstraints.gridx = 0;
layoutConstraints.gridy = 0;
layoutConstraints.weighty = 1;
layoutConstraints.weightx = 0.8;
house.setMinimumSize(new Dimension(1500, 1080));
cp.add(house, layoutConstraints);
GridBagConstraints layoutConstraints2 = new GridBagConstraints();
layoutConstraints2.fill = GridBagConstraints.BOTH;
layoutConstraints2.weighty = 1;
layoutConstraints2.weightx = 0.2;
layoutConstraints2.gridx = 1;
layoutConstraints2.gridy = 0;
cp.add(dataPanel, layoutConstraints2);
dataPanel.setVisible(true);
cp.revalidate();
Related
My code is meant to but the JButton at the top but when I add a image it goes on top of the image which is good but instead of being at the top it is in the middle and you can't get a value for gridy so I don't know how to make it go to the top. I have got lots of buttons on the Container but I will just put the code for one to make it shorter but if you need full code I will provide it. Thank you Here is my code
public void add(Container pane){
setBackground(Color.black);
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
URL resource = getClass().getResource("Graphitebackground.v2.jpg");
ImageIcon i2 = new ImageIcon(resource);
URL resource3 = getClass().getResource("Graphitebackground.v4.jpg");
ImageIcon i3 = new ImageIcon(resource3);
URL resource1 = getClass().getResource("Graphitebackground.v3.jpg");
ImageIcon i1 = new ImageIcon(resource1);
JLabel background = new JLabel(i2);
background.setSize(new Dimension(1000,1000));
background.setVisible(true);
background.setLayout(new GridBagLayout());
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
JButton label2 = new JButton(i1);
c.weightx = 0.5;
label2.setText("Level1");
label2.setPreferredSize(new Dimension(100,100));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
label2.setForeground(Color.RED);
label2.setFont(new Font("Arial", Font.BOLD,100));
label2.setHorizontalTextPosition(JButton.CENTER);
label2.setVerticalTextPosition(JButton.CENTER);
label2.setBorderPainted(false);
label2.addMouseListener(new java.awt.event.MouseAdapter(){
public void mouseEntered(java.awt.event.MouseEvent evt){
label2.setBorderPainted(true);
label2.setBorder(BorderFactory.createLineBorder(Color.red,3));
}
public void mouseExited(java.awt.event.MouseEvent evt){
label2.setBorderPainted(false);
}
});
background.add(label2,c);
pane.add(background);
}
I am trying to make a JFrame with a 30px JPanel at the top, then add the Minecraft Applet underneath, Both need to resize automatically, I am trying to achieve this with a GridBagLayout, so far I have:
public void start(Applet mcApplet, String user, String session) throws MalformedURLException {
JLabel label = new JLabel();
Thread animation = new Thread();
Dimension size = new Dimension(900, 540);
JPanel basic = new JPanel(new GridBagLayout());
basic.setPreferredSize(size);
GridBagConstraints c = new GridBagConstraints();
// ADD MINEBOOK MENU
JLabel menu = new JLabel(new ImageIcon(new URL("http://modpacks.minebook.co.uk/images/menu.png")));
if(!animationname.equalsIgnoreCase("empty")) {
try {
animation.start();
label = new JLabel(new ImageIcon(animationname));
label.setBounds(0, 0, size.width, size.height);
fixSize(size);
getContentPane().setBackground(Color.black);
add(label);
animation.sleep(3000);
animation.stop();
} catch (Exception e) {
label.add(label);
} finally {
remove(label);
}
}
try {
appletWrap = new Launcher(mcApplet, new URL("http://www.minecraft.net/game"));
} catch (MalformedURLException ignored) { }
appletWrap.setParameter("username", user);
appletWrap.setParameter("sessionid", session);
appletWrap.setParameter("stand-alone", "true");
mcApplet.setStub(appletWrap);
mcApplet.setPreferredSize(size);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.ipady = 30;
basic.add(menu, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 1;
c.ipady = 0;
basic.add(appletWrap, c);
add(basic);
pack();
validate();
appletWrap.init();
appletWrap.start();
fixSize(size);
setVisible(true);
}
I suggest that you use a BorderLayout, and place your 30px panel in the NORTH position, while your Minecraft applet in the CENTER position.
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 a Swing Form that contains a JScrollPane(activityScrollPane) for a JPanel(activityPanel). The panel contains a JTextField and a JButton (that is used to add more fields to the Panel). Now the problem is that the elements start from the center of the panel as in the image below (with the borders marking the activityScrollPane boundary)
Following is the code I am currently using to make the scroll pane and associated components.
//part of the code for creating the ScrollPane
final JPanel activityPanel = new JPanel(new GridBagLayout());
gbc.gridx=0;
gbc.gridy=0;
JScrollPane activityScrollPane = new JScrollPane(activityPanel);
//adding activity fields
activityFields = new ArrayList<JTextField>();
fieldIndex = 0;
activityFields.add(new JTextField(30));
final GridBagConstraints activityGBC = new GridBagConstraints();
activityGBC.gridx=0;
activityGBC.gridy=0;
activityGBC.anchor = GridBagConstraints.FIRST_LINE_START;
activityPanel.add(activityFields.get(fieldIndex),activityGBC);
fieldIndex++;
JButton btn_more = (new JButton("more"));
activityGBC.gridx=1;
activityPanel.add(btn_more,activityGBC);
How can I make the JTextField and the JButton or for that matter any component to appear on the top left corner of the JScrollPane. I have already tried using
activityConstraints.anchor = GridBagConstraints.NORTHWEST;
as pointed in the SO post, but it does not at all seem to work.
You simply forgot to provide any weightx/weighty values, atleast one having a non-zero value will do. have a look at this code example :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Latest EDIT : No spacing along Y-Axis
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private JTextField tfield2;
private JButton button2;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
//gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
tfield2 = new JTextField(10);
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield2, gbc);
button2 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button2, gbc);
JScrollPane scroller = new JScrollPane(contentPane);
frame.add(scroller);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Sorry as my answer me be on the off-side of what you have asked, but why dont you use GroupLayout instead of GridBag Layout, thats much more easier to handle
try it with BorderLayout: controls.setLayout(new BorderLayout()); and then apply it for your JPanel controls.add(yourPanel, BorderLayout.PAGE_START);
I also have problems with GridBagLayout so i solved it with BorderLayout and it works so fine.
So i wrote for your little example:
private void initComponents() {
controls = new Container();
controls = getContentPane();
controls.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
field = new JTextField(20);
c.gridx = 0;
c.gridy = 0;
panel.add(field, c);
one = new JButton("Go!");
c.gridx = 1;
c.gridy = 0;
panel.add(one, c);
controls.add(panel, BorderLayout.PAGE_START);
}
Hope it helps!
I think this could be simple and possible, you can
put Nested JPanel to the JScrollPane
to this JPanel
put JPanels contains JComponent to the GridLayout (notice about scrolling, you have to change scrolling increment)
or use most complex JComponents as
put JPanels contains JComponent as Item to the JList
put JPanels contains JComponent as row to the JTable (with only one Column, with or without TableHeader)
Add one panel at the right and one at the bottom.
Right Panel:
Set Weight X to 1.0.
Set Fill to horizontal.
Bottom Panel:
Set Weight Y to 1.0.
Set Fill to vertical
There may be better ways to that, but this one worked for me.
Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
How can I make that each JPanel is 300px width and 400px in height?
for GridBaglayout you have to set
fill
anchor
weightx and weighty
gridx / gridy (depend of orientations)
then is possible for example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 20;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 60;
//gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 2;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
on most cases will be better use another LayoutManager
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
Box content = new Box(BoxLayout.X_AXIS);
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
content.add(P1panel);
content.add(P2panel);
tradeframe.setContentPane(content);
tradeframe.setVisible(true);
Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.
Here is the way to do that :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest
{
public GridBagLayoutTest()
{
JFrame frame = new JFrame("GridBag Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
container.add(leftPanel, gbc);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.fill = GridBagConstraints.BOTH;
container.add(rightPanel, gbc);
frame.setSize(600, 400);
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new GridBagLayoutTest();
}
};
SwingUtilities.invokeLater(runnable);
}
}
OUTPUT :
You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.
The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.