I need help in Java, I can't insert 2 JPanel in one frame with different and preferred size, this is the code:
public class canvas extends JFrame {
public final String TITLE = "test"; /* Game's title */
public static int wWIDTH = 800; /* WIDTH of the window's games */
public static int wHEIGHT = 600; /* HEIGHT of the window's game */
/* => GAME ENGINEERING ATTRIBUTES <= */
private Dimension WINDOW_SIZE;
private Container c;
private rightpane rightpane;
private leftpane leftpane;
public canvas() {
Dimension SCREEN_SIZE = Toolkit.getDefaultToolkit().getScreenSize();
WINDOW_SIZE = new Dimension(wWIDTH, wHEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle(TITLE);
this.setUndecorated(false);
this.setSize(WINDOW_SIZE);
this.setResizable(false);
this.setLocation(((SCREEN_SIZE.width / 2) - (wWIDTH / 2)),
((SCREEN_SIZE.height / 2) - (wHEIGHT / 2)));
leftpane = new leftpane();
rightpane = new rightpane();
//leftpane.setPreferredSize(leftpane_dim);
this.add(rightpane,BorderLayout.EAST);
this.add(leftpane,BorderLayout.WEST);
this.setVisible(true);
}
and rightpane and leftpane class:
public class rightpane extends JPanel {
public JLabel lb;
public rightpane() {
this.setBackground(Color.YELLOW);
lb = new JLabel();
lb.setText("right paneeeeeeeee");
this.add(lb);
}
public void paintComponents(Graphics g) {
super.paintComponents(g);
}
}
public class leftpane extends JPanel {
public JLabel lb;
public leftpane() {
this.setBackground(Color.BLACK);
lb = new JLabel();
lb.setText("left pane");
this.add(lb);
}
public void paintComponents(Graphics g) {
super.paintComponents(g);
}
}
This is the result:
I tried with GridBagLayout:
GridBagLayout gl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
this.setLayout(gl);
c.ipadx = 200;
c.gridwidth = 2;
c.gridx = c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
c.gridheight = 3;
gl.setConstraints(leftpane, c);
this.add(new leftpane());
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 3;
c.anchor = GridBagConstraints.EAST;
gl.setConstraints(rightpane, c);
this.add(new rightpane());
And other solutions found in the network but still not working. Can anyone help me?
There were a few problems in your GridBagLayout. Here's the fixed version
GridBagLayout gl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
this.setLayout(gl);
c.fill = GridBagConstraints.BOTH; // <== need to set fill
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
c.weightx = 1; // <== need to set weight
c.weighty = 1; // <== need to set weight
// gl.setConstraints(leftpane, c); // <== constraints get overridden by your add() call...
this.add(new leftpane(), c); // pass constraints in here
c.gridx = 1;
c.weightx = 3; <== need to set weight, note different value, space shared in ratio 1:3
c.anchor = GridBagConstraints.EAST; // pass constraints in here
Picture
Related
I am using the GridBagLayout to arrange some components in a frame.
When the frame is first created, the components have a decent space in between them.
But as soon as I resize the frame there are alot of unwanted space between the components
I tried adjusting the weights and insets as suggested by some users, but it does not seem to fix the problem
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JTextArea;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
GridBagConstraints c = new GridBagConstraints();
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
menuBar.add(menu);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = c.REMAINDER;
c.fill = c.HORIZONTAL;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(menuBar, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(one, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(oneF, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(two, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(twoF, c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(three, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(threeF, c);
//setResizable(false);
pack();
setVisible(true);
}
}
ps:- I am new to GUI programming, so please forgive me for any noob mistakes.
edit 1: This is the what I want to have after I am done. I know the currently it does not look anyway near what I have in mind... I am still working on it
Thanks
use an nested layout (combinations of a few LayoutManagers), your picture talks me about,
still you can use GridBagLayout for components placed into left side,
in my code (simplest idea as is possible) JComponents placed on left side can't be resizable because are restricted from LayoutManager`s defaults, more in Oracle tutorial
.
.
painted from SSCCE/MCVE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame {
private static final long serialVersionUID = 1L;
private JFrame myFrame = new JFrame("Whatever");
private JPanel parentPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
#Override
public Color getBackground() {
return new Color(255, 000, 000);
}
};
private JPanel leftPanel = new JPanel(/*default is FlowLayout*/) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 000);
}
};
private JPanel leftChildPanel = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 225);
}
};
private JPanel rightPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 380);
}
#Override
public Color getBackground() {
return new Color(000, 255, 225);
}
};
public MyFrame() {
parentPanel.add(leftPanel, BorderLayout.WEST);
leftPanel.add(leftChildPanel);
parentPanel.add(rightPanel);
myFrame.add(parentPanel);
myFrame.setLocation(150, 150);
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new MyFrame();
});
}
}
The idea is to add empty row / columns that will grow to fill the available space:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0}; //this defines 4 rows
//make 2 last empty row grow
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0,1.0};
//do the same for columns
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0,1.0};
getContentPane().setLayout(gridBagLayout);
menuBar.add(menu);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 5;
c.fill = c.HORIZONTAL;
c.anchor = c.NORTH;
c.insets = new Insets(5, 5, 5, 0);
getContentPane().add(menuBar, c);
//better have a new GridBagConstraints for each component added
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 1;
c1.gridwidth = 1;
c1.fill = c1.NONE;
c1.anchor = c1.NORTH;
c1.insets = new Insets(5, 5, 0, 5);
getContentPane().add(one, c1);
GridBagConstraints c2 = new GridBagConstraints();
c2.gridx = 1;
c2.gridy = 1;
c2.fill = c2.NONE;
c2.anchor = GridBagConstraints.NORTHWEST;
c2.insets = new Insets(5, 5, 0, 5);
getContentPane().add(oneF, c2);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Frame1();
}
}
EDIT: in response to your edit: use the additional "growing" column for the "cover art"
The problem is your assignments of c.weightx and c.weighty. weightx and weighty determine how extra space is allocated to grid cells in a GridBagLayout when the container is made larger than necessary to accommodate the preferred sizes of the components.
The weightx and weighty should be zero for all cells except those cells which you want to grow larger when the window is made larger.
I have no real idea on how it is supposed to look like, but you could try to set for the labels c.anchor=GridBagConstraints.EAST and c.anchor=GridBagConstraints.WEST for the textfields.
Try also setting c.fill = GridBadConstraints.BOTH.
I am using GridBagLayout to design the interface. The interface has one JTabbedPane set at north and fill both directions as I resize, and just below the JTabbedPane there are two JButtons.
What I want to achieve is putting these two buttons at east with using only GridBagLayout capabilities (without introducing an extra JPanel), but I failed to do so.
|-[tab]--------------------------|
|---------------------------------|
|---------------------------------|
|---------------------------------|
|---------------------------------|
|-------------[button][button]|
When I set the layout constraint for both buttons to WEST (not EAST). Both go west correctly!
c.anchor = GridBagConstraints.WEST;
But when I set the layout constraint for both buttons to east
c.anchor = GridBagConstraints.EAST;
One of them go to east and the other go to west!
To solve this issue I added a JPanel which hold both buttons and added this JPanel into the interface, and set its layout constraint to c.anchor = GridBagConstraints.EAST;. It works well.
But is it possible to build the same GridBagLayout interface without using an extra JPanel as a container?
The following two classes are in SSCCE format; the first one show the problem GridBagTest, and the other show the solution GridBagTest_solved that make use of extra JPanel
Problem class:
import javax.swing.*;
import java.awt.*;
public class GridBagTest extends JPanel {
JFrame frame;
JTabbedPane tabbedPane;
JPanel panel_tab;
JButton btn_previous;
JButton btn_next;
private void create_and_layout() {
this.setLayout(new GridBagLayout());
tabbedPane = new JTabbedPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 150);
}
};
panel_tab = new JPanel();
tabbedPane.addTab("Tab 1", panel_tab);
btn_previous = new JButton("previous");
btn_next = new JButton(" next ");
GridBagConstraints c;
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.gridwidth = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTH;
this.add(tabbedPane, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(2, 0, 2, 2);
this.add(btn_previous, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(2, 0, 2, 2);
this.add(btn_next, c);
}
private void initGUI() {
create_and_layout();
frame = new JFrame("GridBagTest");
frame.getContentPane().add(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new GridBagTest()::initGUI);
}
}
Solution class:
import javax.swing.*;
import java.awt.*;
public class GridBagTest_solved extends JPanel {
JFrame frame;
JTabbedPane tabbedPane;
JPanel panel_tab;
JPanel panel_buttons;
JButton btn_previous;
JButton btn_next;
private void create_and_layout() {
this.setLayout(new GridBagLayout());
tabbedPane = new JTabbedPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 150);
}
};
panel_tab = new JPanel();
tabbedPane.addTab("Tab 1", panel_tab);
panel_buttons = new JPanel(new GridBagLayout());
btn_previous = new JButton("previous");
btn_next = new JButton(" next ");
GridBagConstraints c;
// Adding buttons to panel_buttons
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2, 0, 2, 2);
panel_buttons.add(btn_previous, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(2, 0, 2, 2);
panel_buttons.add(btn_next, c);
// Adding tabbedPane & panel_buttons to this (GridBagTest_solved)
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTH;
this.add(tabbedPane, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
this.add(panel_buttons, c);
}
private void initGUI() {
create_and_layout();
frame = new JFrame("GridBagTest_solved");
frame.getContentPane().add(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new GridBagTest_solved()::initGUI);
}
}
If you only have the three components - the JTabbedPane and two JButtons, you should consider using a simpler layout than GridBag. Just use a BorderLayout for the main panel, placing the JTabbedPane in CENTER, and a JPanel in SOUTH that has a FlowLayout with alignment of TRAILING, then just add the two buttons to that JPanel.
I have created a layout for a basic text editor, I would like the top bar to have the buttons alligned to the left, the top bar is a JPanel and it is using the FlowLayout manager. It is inside of a grid using the GridBag layout manager. Any suggestions?
import java.awt.*;
import javax.swing.*;
public class GridTest {
private static JButton firstButton, secondButton, thirdButton;
private static JPanel panel, sidebar, infoPanel;
private static JTextArea textArea;
public static void addComponentsToPane(Container container) {
container.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
firstButton = new JButton("Button 1");
secondButton = new JButton("Button 2");
thirdButton = new JButton("Button 3");
panel = new JPanel(new FlowLayout());
sidebar = new JPanel(new FlowLayout());
infoPanel = new JPanel(new FlowLayout());
textArea = new JTextArea("This is some generic text!");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.weighty = 0;
c.weightx = 1;
c.gridx = 0;
c.gridwidth = 3;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_START;
container.add(panel, c);
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(firstButton);
panel.add(secondButton);
panel.add(thirdButton);
c.fill = GridBagConstraints.BOTH;
c.ipady = 300;
c.ipadx = 100;
c.weighty = 1;
c.weightx = 0;
c.gridx = 0;
c.gridheight = 2;
c.gridwidth = 1;
c.gridy = 1;
container.add(sidebar, c);
sidebar.setBorder(BorderFactory.createLineBorder(Color.black));
c.fill = GridBagConstraints.BOTH;
c.ipady = 40;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.gridx = 1;
c.gridy = 1;
container.add(textArea, c);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.weighty = 0;
c.weightx = 0;
c.anchor = GridBagConstraints.PAGE_END;
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 2;
container.add(infoPanel, c);
infoPanel.setBorder(BorderFactory.createLineBorder(Color.black));
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Grid test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.setSize(800,600);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Consider using a JToolBar instead of a JPanel, as it has it's own layout manager, which, basically, does this any way.
Images from following tutorial...
Check out How to use Tool Bars for more details
One way: Change your FlowLayout to one that prefers to place its components on the left:
panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
Could you please help me use the ActionListener correclty in my code? The code compiles and the GUI is displayed correctly, but no button works!! If you want to test the code, note that you need to put the image in the same folder as the project file created and change the line "ImageIcon myImageIcon = new ImageIcon("rodeo.jpg");" according to the name of your photo.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageApplication extends JFrame implements ActionListener
{
public Image myImage;
public JLabel myImageLabel;
public ImageIcon myImageIcon;
public JFrame frame;
public JTextField txtWidth, txtHeight;
public int origWidth, origHeight;
public static void main(String[] args)
{
int origWidth, origHeight;
ImageApplication ia = new ImageApplication();
ia.setVisible(true);
JFrame frame = new JFrame();
ImageIcon myImageIcon = new ImageIcon("rodeo.jpg");
JLabel myImageLabel = new JLabel(myImageIcon, JLabel.CENTER);
Image myImage = myImageIcon.getImage();
origWidth = myImageIcon.getIconWidth();
origHeight = myImageIcon.getIconHeight();
JMenuBar myMenuBar = new JMenuBar();
JMenu myMenu = new JMenu("Options");
JMenuItem myMenuItem1 = new JMenuItem("Double");
JMenuItem myMenuItem2 = new JMenuItem("Reset");
myMenu.add(myMenuItem1);
myMenu.add(myMenuItem2);
myMenuBar.add(myMenu);
ia.setJMenuBar(myMenuBar);
JButton bAL = new JButton("Align Left");
JButton bAC = new JButton("Align Center");
JButton bAR = new JButton("Align Right");
JButton bResize = new JButton ("Resize");
bAL.setFocusPainted(false);
bAC.setFocusPainted(false);
bAR.setFocusPainted(false);
bResize.setFocusPainted(false);
JLabel lWidth = new JLabel("Width:");
JLabel lHeight = new JLabel("Height:");
JTextField txtWidth = new JTextField(Integer.toString(origWidth));
JTextField txtHeight = new JTextField(Integer.toString(origHeight));
JPanel GRID = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1f;
c.weighty = 0f;
c.gridx = 0;
c.gridy = 0;
GRID.add(bAL, c);
c.gridx++;
GRID.add(bAC, c);
c.gridx++;
GRID.add(bAR, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
GRID.add(myImageLabel, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
GRID.add(lWidth, c);
c.gridx++;
c.gridwidth = 2;
GRID.add(txtWidth, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 3;
GRID.add(lHeight, c);
c.gridx++;
c.gridwidth = 2;
GRID.add(txtHeight, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 4;
GRID.add(bResize, c);
ia.add(GRID, BorderLayout.CENTER);
ia.setSize(origWidth + 150, origHeight + 150);
myMenuItem1.addActionListener(ia);
myMenuItem1.setActionCommand("double");
myMenuItem2.addActionListener(ia);
myMenuItem2.setActionCommand("reset");
bAL.addActionListener(ia);
bAL.setActionCommand("left");
bAC.addActionListener(ia);
bAC.setActionCommand("center");
bAR.addActionListener(ia);
bAR.setActionCommand("right");
bResize.addActionListener(ia);
bResize.setActionCommand("resize");
}
private void ResizeImage(int Width, int Height)
{
myImage = myImage.getScaledInstance(Width, Height, Image.SCALE_SMOOTH);
myImageIcon.setImage(myImage);
myImageLabel.setIcon(myImageIcon);
txtWidth.setText(Integer.toString(Width));
txtHeight.setText(Integer.toString(Height));
setSize(Width + 150, Height + 150);
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command == "left") myImageLabel.setHorizontalAlignment(JLabel.LEFT);
else if(command == "center") myImageLabel.setHorizontalAlignment(JLabel.CENTER);
else if(command == "right") myImageLabel.setHorizontalAlignment(JLabel.RIGHT);
else if(command == "resize") ResizeImage(Integer.parseInt(txtWidth.getText()),
Integer.parseInt(txtHeight.getText()));
else if(command == "double") ResizeImage(myImageIcon.getIconWidth() * 2,
myImageIcon.getIconHeight() * 2);
else if(command == "reset") ResizeImage(origWidth, origHeight);
}
}
Use String#equals to compare String content. You are using the == operator which compares Object references.
However, as the buttons have differing functionality, better for each to have an individual ActionListener. This can be done using an anonymous ActionListener instance.
Side issue: The class member variable myImageLabel is not being assigned. Rather another variable
with the same name is initialized in the static main method. You need to move all the components instantiated in the main method into an instance method and also remove the JLabel local class declaration.
After moving code:
JLabel myImageLabel = new JLabel(myImageIcon, JLabel.CENTER);
should be
myImageLabel = new JLabel(myImageIcon, JLabel.CENTER);
Try this method:
What it does: it adds to the button itself, when clicked an method to be performed:
buttonName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//do what ever
}
});
//set bunds for the button itself, if not done otherwise, but for your layout.
These instance variables:
public JTextField txtWidth, txtHeight;
are never initialized but are referred to in your listener code. You have local variables of the same name that you're instantiating. Change this:
JTextField txtWidth = new JTextField(Integer.toString(origWidth));
JTextField txtHeight = new JTextField(Integer.toString(origHeight));
to this:
txtWidth = new JTextField(Integer.toString(origWidth));
txtHeight = new JTextField(Integer.toString(origHeight));
and similarly for your other instance variables.
Use the following code to get Image
ImageIcon myImageIcon = new ImageIcon("rodeo.jpg").getImage();
I want to make a JFrame to display a GUI like this: http://i.stack.imgur.com/2POFs.png
(im not allowed to embed pictures)
the blank spcaces are the same X and Y dimentions,
the buttons are the same X and Y dimentions,
JTextArea is half of the frame.
public static JFrame frame = new JFrame ("Launcher " + version);
public static GridBagConstraints c = new GridBagConstraints();
public static JTextArea news = new JTextArea();
public static JButton launchGame = new JButton("Launch Game");
public static JButton settings = new JButton("Settings");
public static JButton exitGame = new JButton("Exit");
public static void main(String[] args)
{
news.setEditable(false);
news.setBounds(0, 0, (screenSize.width - 500) / 2, screenSize.height - 400);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
frame.setLayout(new GridBagLayout());
frame.setBounds(300, 200, screenSize.width - 500, screenSize.height - 400);
c.fill = GridBagConstraints.VERTICAL;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
frame.add(news, c);
frame.setVisible(true);
c.fill = GridBagConstraints.EAST;
c.weightx = 0.5;
c.gridx = 1;
c.gridheight = 1;
frame.add(launchGame, c);
c.gridy = 1;
frame.add(settings, c);
c.gridy = 2;
frame.add(exitGame, c);
}
Is this what you want? I added/modified the following in your button constraints:
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 10, 0, 10); // 10 is the marginal
And here is the full code:
public static void main(String[] args)
{
news.setEditable(false);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
frame.setLayout(new GridBagLayout());
c.fill = GridBagConstraints.VERTICAL;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
frame.add(news, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 10, 10); // 10 is the marginal
c.weightx = 0.5;
c.gridx = 1;
c.gridheight = 1;
frame.add(launchGame, c);
c.gridy = 1;
frame.add(settings, c);
c.gridy = 2;
frame.add(exitGame, c);
frame.pack();
frame.setVisible(true);
}
Here is a similar layout using BoxLayout instead (easier to work with I think):
private static JComponent buildButtons() {
for (JButton button : Arrays.asList(launchGame, settings, exitGame)) {
button.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
}
Box b = Box.createVerticalBox();
b.add(Box.createVerticalStrut(10));
b.add(launchGame);
b.add(Box.createVerticalStrut(10));
b.add(settings);
b.add(Box.createVerticalStrut(10));
b.add(exitGame);
b.add(Box.createVerticalStrut(10));
return b;
}
static JComponent buildUI() {
Box b = Box.createHorizontalBox();
b.add(news);
b.add(Box.createHorizontalStrut(10));
b.add(buildButtons());
b.add(Box.createHorizontalStrut(10));
return b;
}
public static void main(String[] args)
{
news.setEditable(false);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
frame.add(buildUI());
frame.pack();
frame.setVisible(true);
}
First of all...
c.fill = GridBagConstraints.EAST;
Isn't what I think you want to do. I think the fill should be at least HORIZONTAL
Secondly...
You could use Insets to adjust the space between the components, something like
public class TestLayout {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new FormPane());
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected static class FormPane extends JPanel {
private JTextArea news = new JTextArea();
private JButton launchGame = new JButton("Launch Game");
private JButton settings = new JButton("Settings");
private JButton exitGame = new JButton("Exit");
public FormPane() {
setLayout(new GridBagLayout());
news.setEditable(false);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weightx = 0.25;
add(news, gbc);
gbc.insets = new Insets(0, 50, 0, 50);
gbc.gridheight = 1;
gbc.gridx++;
add(launchGame, gbc);
gbc.gridy = 1;
add(settings, gbc);
gbc.gridy = 2;
add(exitGame, gbc);
}
}
}
I might also be inclined to to place the buttons in there own container (like a JPanel) and maybe use a GridLayout to lay them out, then use the above suggestion to lay the text area and button container.
This isolates the individual layout needs without further complicating the layout...