Positioning with GridBagLayout - java

I've a positioning problem with the GridBagLayout :
I try to place in center (at the top) a label but with my code (for a reason which I didn't see), I've this :
I want that the label Test are at the top of my window and in center. Someone can explain me the reason of this bad positionnement ?
My program :
public class Accueil extends JFrame {
private JPanel home = new JPanel();
private GridBagConstraints grille = new GridBagConstraints();
private JLabel title = new JLabel("Test");
public Accueil() {
home.setLayout(new GridLayout());
init_grille();
init_title();
this.add(home);
this.setSize(600,600);
this.setTitle("Test One");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void init_grille() {
grille.fill = GridBagConstraints.BOTH;
grille.weightx = 2;
grille.weighty = 5;
grille.ipady=grille.anchor=GridBagConstraints.CENTER;;
}
private void init_title() {
grille.fill = GridBagConstraints.HORIZONTAL;
grille.gridx = 0;
grille.gridy = 0;
home.add(title,grille);
}
public static void main(String [] args) {
new Accueil();
}
}

This won't help:
home.setLayout(new GridLayout());
You probably want:
home.setLayout(new GridBagLayout());
Also, these changes should work:
private void init_title() {
grille.fill = GridBagConstraints.NONE;
grille.gridx = 0;
grille.gridy = 0;
grille.anchor = GridBagConstraints.NORTH;
home.add(title,grille);
}

Related

Drawing & Changing an Image within a JPanel (from another class)

So yeah, I'm trying to write a rock paper scissors program with images, but I'm having trouble at putting in the pictures. There seems to only be a small white square on the JPanel.
Here's the code for my Main Class:
public class Practice extends JPanel implements ActionListener {
// Images
final ImageIcon rockPic = new ImageIcon("D:\\JOVO\\RPS\\src\\rock.png");
final ImageIcon paperPic = new ImageIcon("D:\\JOVO\\RPS\\src\\paper.png");
// variables
String results = null;
Image pic = null;
//Image Panel
ImagePanel youPic = new ImagePanel();
public Practice() {
// FRAME
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RPS");
frame.setLayout(new BorderLayout());
frame.setVisible(true);
// SUPER JPANEL
setLayout(new GridBagLayout());
setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
frame.add(this);
// JPANELS - RPS title, JButton, PICTURES
JPanel rpsTitle = new JPanel();
c.fill = GridBagConstraints.CENTER;
c.gridy = 0;
c.gridx = 1;
rpsTitle.setBackground(Color.WHITE);
add(rpsTitle, c);
JPanel jbuts = new JPanel();
c.gridy = 3;
jbuts.setLayout(new BorderLayout());
add(jbuts, c);
// ImagePanels
c.gridy = 2;
c.gridx = 0;
add(youPic,c);
c.gridy = 0;
c.gridx = 1;
// JBUTTONS
JButton rock = new JButton(" Rock ");
JButton paper = new JButton(" Paper ");
JButton scissors = new JButton("Scissors");
jbuts.add(rock, BorderLayout.WEST);
jbuts.add(paper, BorderLayout.CENTER);
jbuts.add(scissors, BorderLayout.EAST);
paper.addActionListener(this);
JButton resultB = new JButton("RES");
c.gridy = 2;
c.weighty = 10;
add(resultB, c);
c.weighty = 0;
// FONTS
Font rps = new Font(null, Font.BOLD, 28);
Font labels = new Font(null, Font.ITALIC, 18);
// JLABELS
JLabel rpsTit = new JLabel("Rock, Paper, Scissors");
rpsTit.setFont(rps);
rpsTitle.add(rpsTit);
JLabel you = new JLabel("You: ");
you.setFont(labels);
JLabel com = new JLabel("Com: ");
com.setFont(labels);
c.gridy = 1;
c.gridx = 0;
add(you, c);
c.gridx = 2;
add(com, c);
// PICTURES
// comPic.setPic(rockPic);
// youPic.setPic(pic);
}
public String test(String name) {
// test the game
return results;
}
public static void main(String[] args) {
// main stuffs
Practice prac = new Practice();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Works");
ImageIcon pic = null;
pic = paperPic;
youPic.setPic(pic);
}
}
And my other class:
public class ImagePanel extends JPanel {
Image pic = null;
public ImagePanel() {
repaint();
}
public void setPic(ImageIcon pic) {
// set picture for painting
this.pic = pic.getImage();
System.out.println("Set Pic");
repaint();
}
public void paintComponent(Graphics g) {
// paint
super.paintComponent(g);
System.out.println("Painting");
g.drawImage(pic, 0, 0, this);
}
}
Thanks in advance! :)

JTextField Everything looks ok in Eclipse but won't compile

Can someone please tell me what's wrong with this code?
I need it to pop up a frame and fill the frame with certain field a namer field and an intake field and also display a button at the bottom of the grid.
Any help would be welcomed, Thanks!!
import java.awt.*;
import javax.swing.*;
public class FrameDemo
//To create the gui and show it.
{
public static void createAndShowGUI()
{
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(1,14);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow handler for user input on Empty Textfield?
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
//add job to event scheduler
//create and show GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is not how you use GridLayout:
frame.getContentPane().add(PL, first);
Instead you'd set the container's layout using the layout manager:
frame.getContentPane().setLayout(first);
and then add components to the container:
frame.getContentPane().add(PL);
frame.getContentPane().add(PLv);
frame.getContentPane().add(AD);
frame.getContentPane().add(ADv);
frame.getContentPane().add(AV);
frame.getContentPane().add(Avv);
frame.getContentPane().add(TS);
frame.getContentPane().add(TSv);
frame.getContentPane().add(MT);
frame.getContentPane().add(MTv);
// and so on for all the components.
You will want to read the tutorial on how to use GridLayout which you can find here: GridLayout Tutorial.
As an aside, note that this:
frame.getContentPane().add(PL);
can be shortened to this:
frame.add(PL);
Also you will want to study and learn Java naming conventions: class names begin with an upper case letter and all method and variables with lower case letters. Also avoid variable names like pl or plv, or ad or adv, and instead use names that are a little bit longer and have meaning, names that make your code self-commenting. So instead of AD, consider angularDisplacementField for the JTextfield's name.
Myself, I'd use a GridBagLayout and do something like:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.*;
public class GuiDemo extends JPanel {
// or better -- use an enum for this
public static final String[] FIELD_LABELS = {
"Pendulum Length", "Angular Displacement", "Angular Velocity",
"Time Steps", "Max Time", "Viscocity (0-1)"
};
private static final int TEXT_FIELD_COLUMNS = 10;
private static final int GAP = 3;
private static final Insets RIGHT_GAP_INSETS = new Insets(GAP, GAP, GAP, 3 * GAP);
private static final Insets BALANCED_INSETS = new Insets(GAP, GAP, GAP, GAP);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GuiDemo() {
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
int row = 0;
// to make sure that no focusAccelerator is re-used
Set<Character> focusAccelSet = new HashSet<>();
for (String fieldLabelLText : FIELD_LABELS) {
JLabel fieldLabel = new JLabel(fieldLabelLText);
JTextField textField = new JTextField(TEXT_FIELD_COLUMNS);
labelFieldPanel.add(fieldLabel, getGbc(row, 0));
labelFieldPanel.add(textField, getGbc(row, 1));
labelFieldMap.put(fieldLabelLText, textField);
for (char c : fieldLabelLText.toCharArray()) {
if (!focusAccelSet.contains(c)) {
textField.setFocusAccelerator(c);
fieldLabel.setDisplayedMnemonic(c);
focusAccelSet.add(c);
break;
}
}
row++;
}
JButton button = new JButton(new DrawGraphAction("Draw New Graph"));
labelFieldPanel.add(button, getGbc(row, 0, 2, 1));
setLayout(new BorderLayout(GAP, GAP));
add(labelFieldPanel, BorderLayout.CENTER);
}
private class DrawGraphAction extends AbstractAction {
public DrawGraphAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO calculation method
}
}
public static GridBagConstraints getGbc(int row, int column) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
if (column == 0) {
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = RIGHT_GAP_INSETS;
} else {
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = BALANCED_INSETS;
}
return gbc;
}
public static GridBagConstraints getGbc(int row, int column, int width, int height) {
GridBagConstraints gbc = getGbc(row, column);
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.insets = BALANCED_INSETS;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Gui Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GuiDemo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Vertical alignment of checkboxes

Could you help me understand how to set left vertical alignment to the checkboxes. I mean each checkbox on its own row.
Tried everything I could imagine and have come to the end of my wit.
public class DisplayFrame extends JFrame {
public DisplayFrame(ArrayList<String> contents){
DisplayPanel panel = new DisplayPanel(contents, whiteList);
add(panel);
}
private void displayAll(){
DisplayFrame frame = new DisplayFrame(contents, whiteList);
GridBagLayout gbl = new GridBagLayout();
frame.setLayout(gbl);
frame.setVisible(true);
...
}
public class DisplayPanel extends JPanel {
ArrayList<JCheckBox> cbArrayList = new ArrayList<JCheckBox>();
ArrayList<String> contents;
...
public DisplayPanel(ArrayList<String> contents){
...
createListOfCheckBoxes();
}
private void createListOfCheckBoxes() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = contents.size() + 1;
gbc.gridheight = contents.size() + 1;
for (int i = 0; i < contents.size(); i++){
gbc.gridx = 0;
gbc.gridy = i;
String configuration = contents.get(i);
JCheckBox currentCheckBox = new JCheckBox(configuration);
if (whiteList.contains(configuration)){
currentCheckBox.setSelected(true);
}
currentCheckBox.setVisible(true);
add(currentCheckBox, gbc);
}
}
"If I were able to proceed without GridBagLayout, that would suit me"
You can just use a BoxLayout. Box is a convenience class for BoxLayout. You can just do
Box box = Box.createVerticalBox();
for (int i = 0; i < contents.size(); i++){
String configuration = contents.get(i);
JCheckBox currentCheckBox = new JCheckBox(configuration);
if (whiteList.contains(configuration)){
currentCheckBox.setSelected(true);
}
box.add(currentCheckBox);
}
Since Box is a JComponent, you can just add the box to a container.
You can see more at How to Use BoxLayout
Simple Example
import javax.swing.*;
public class BoxDemo {
public static void main(String[] args) {
Box box = Box.createVerticalBox();
JCheckBox cbox1 = new JCheckBox("Check me once");
JCheckBox cbox2 = new JCheckBox("Check me twice");
JCheckBox cbox3 = new JCheckBox("Check me thrice");
box.add(cbox1);
box.add(cbox2);
box.add(cbox3);
JOptionPane.showMessageDialog(null, box);
}
}

Location set up with GridBagLayout is not going good & JTextField & JButton wont take affect

So I am working on this small program when I ran in to this problem.Its mostly about location set up with GridBagLayout it wont show me the text for the JLable.Another problem is that every ones in a will my progress that was working stops working and later comes back.Any idea what it is?I would also like some one too help me with the location problem I want to place the JTextField in the bottom left corner any help?I cant go around this problem and no info online to specifically help me.So maybe you can help me.Hers my code so far...
package Main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class code extends JFrame{
public static JTextField consol;
public static String title = "Metal-Lock:The Start";
public static Dimension size = new Dimension(650, 550);
public static JPanel panel;
public static JButton enter;
public static JLabel output;
public static void main(String args[]) {
code frame = new code();
}
public code() {
setTitle(title);
setSize(size);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// VISITOR LIST
CONSOL();
P1();
P2();
}
//******************************************************************************************************************************
public void CONSOL() {
consol = new JTextField(30);
consol.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
String input = consol.getText();
output.setText(input);
}});
final JButton enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
String input = consol.getText();
output.setText(input);
panel.add(consol);
add(panel);
panel.add(enter);
add(panel);
output = new JLabel();
panel.add(output);
add(panel);
}
});
}
//******************************************************************************************************************************
public void P1() {
}
//******************************************************************************************************************************
public static JLabel grid1;
public static JLabel grid2;
public static JLabel grid3;
public static JLabel grid4;
public static JLabel grid5;
public void P2() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints R = new GridBagConstraints();
JLabel grid1 = new JLabel ("Hello"); panel.add(grid1, R);
R.gridx = 0; R.gridy = 0;
JLabel grid2 = new JLabel ("Hello"); panel.add(grid2, R);
R.gridx = 0; R.gridy = 0;
JLabel grid3 = new JLabel ("Hello"); panel.add(grid3, R);
R.gridx = 0; R.gridy = 0;
JLabel grid4 = new JLabel ("Hello"); panel.add(grid4, R);
R.gridx = 0; R.gridy = 0;
JLabel grid5 = new JLabel ("Hello"); panel.add(grid5, R);
R.gridx = 0; R.gridy = 0;
}
}
Just went really quickly through your code.
Change these lines:
GridBagConstraints R = new GridBagConstraints();
R.gridx = 0; R.gridy = 0;
JLabel grid1 = new JLabel ("Hello");
//important to set these R values BEFORE you ad grid1.
panel.add(grid1, R);
Change this in all lines there...
You are adding 6 Labels all to the location gridx=0 and gridy=0, which is wrong. Imagine it like an excel tabel, you are inserting every label to field 1.
If you want to add fields do it like this
E.g.
x y
z
//a.gridx=0; a.gridy=0;
//y.gridx=1; y.gridy=0;
//z.gridx=0; z.gridy=1;
x coordinates are horizontal.
y are vertical starting from the top left corner.
Read this article, it's really good:
http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

Why does GridBagLayout provide strange result?

I want the various components to spread out and fill the entire window.
Have you tried anything else? Yes, I tried GridLayout but then the buttons look huge. I also tried pack() which made the window small instead. The window should be 750x750 :)
What I was trying is this:
These 4 buttons on the top as a thin strip
The scroll pane with JPanels inside which will contain all the video conversion tasks. This takes up the maximum space
A JPanel at the bottom containing a JProgressBar as a thin strip.
But something seems to have messed up somewhere. Please help me solve this
SSCCE
import java.awt.*;
import javax.swing.*;
import com.explodingpixels.macwidgets.*;
public class HudTest {
public static void main(String[] args) {
HudWindow hud = new HudWindow("Window");
hud.getJDialog().setSize(750, 750);
hud.getJDialog().setLocationRelativeTo(null);
hud.getJDialog().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addVideo = HudWidgetFactory.createHudButton("Add New Video");
JButton removeVideo = HudWidgetFactory.createHudButton("Remove Video");
JButton startAll = HudWidgetFactory.createHudButton("Start All Tasks");
JButton stopAll = HudWidgetFactory.createHudButton("Stop All Tasks");
buttonPanel.add(addVideo);
buttonPanel.add(startAll);
buttonPanel.add(removeVideo);
buttonPanel.add(stopAll);
JPanel taskPanel = new JPanel(new GridLayout(0,1));
JScrollPane taskScrollPane = new JScrollPane(taskPanel);
IAppWidgetFactory.makeIAppScrollPane(taskScrollPane);
for(int i=0;i<10;i++){
ColorPanel c = new ColorPanel();
c.setPreferredSize(new Dimension(750,100));
taskPanel.add(c);
}
JPanel progressBarPanel = new JPanel();
JComponent component = (JComponent) hud.getContentPane();
component.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Insets in = new Insets(2,2,2,2);
gbc.insets = in;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
component.add(buttonPanel,gbc);
gbc.gridy += 1;
gbc.gridheight = 17;
component.add(taskScrollPane,gbc);
gbc.gridy += 17;
gbc.gridheight = 2;
component.add(progressBarPanel,gbc);
hud.getJDialog().setVisible(true);
}
}
Use this
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridbagConstraints.BOTH
Why not simply place three JPanels on top of one JPanel with BorderLayout as Layout Manager, where the middle JPanel with all custom panels with their respective sizes can be accommodated inside a JScrollPane, as shown in the below example :
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 5/17/13
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerBase
{
private JPanel contentPane;
private JPanel buttonPanel;
private JPanel centerPanel;
private CustomPanel[] colourPanel;
private JPanel progressPanel;
private JButton addVideoButton;
private JButton removeVideoButton;
private JButton startAllButton;
private JButton stopAllButton;
private JProgressBar progressBar;
private Random random;
public PlayerBase()
{
colourPanel = new CustomPanel[10];
random = new Random();
}
private void displayGUI()
{
JFrame playerWindow = new JFrame("Player Window");
playerWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
addVideoButton = new JButton("Add New Video");
removeVideoButton = new JButton("Remove Video");
startAllButton = new JButton("Start all tasks");
stopAllButton = new JButton("Stop all tasks");
buttonPanel.add(addVideoButton);
buttonPanel.add(removeVideoButton);
buttonPanel.add(startAllButton);
buttonPanel.add(stopAllButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scroller = new JScrollPane();
centerPanel = new JPanel(new GridLayout(0, 1, 2, 2));
for (int i = 0; i < colourPanel.length; i++)
{
colourPanel[i] = new CustomPanel(new Color(
random.nextInt(255), random.nextInt(255)
, random.nextInt(255)));
centerPanel.add(colourPanel[i]);
}
scroller.setViewportView(centerPanel);
contentPane.add(scroller, BorderLayout.CENTER);
progressPanel = new JPanel(new BorderLayout(5, 5));
progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
progressPanel.add(progressBar);
contentPane.add(progressPanel, BorderLayout.PAGE_END);
playerWindow.setContentPane(contentPane);
playerWindow.pack();
//playerWindow.setSize(750, 750);
playerWindow.setLocationByPlatform(true);
playerWindow.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new PlayerBase().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
public CustomPanel(Color backGroundColour)
{
setOpaque(true);
setBackground(backGroundColour);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(750, 100));
}
}
OUTPUT :

Categories