I am making a simple game and I cant seem to get the line to center. I would like it all to be in a column and centered. I have this line of code that is not centering

JLabel numberOfChangesLabel = new JLabel("" + totalChanges);		
pane.add (new JPanel ().add(numberOfChangesLabel));

this should act like me creating another JPanel and then adding the component to that panel, then adding the component to the main panel. When I do create a new panel then add the component to the panel, then add the panel to the main panel it centers. Why doesnt that line work correctly.

Thanks for any help.

I have this line of code that is not centering

What layout manager are you using?

my main panel is using GridLayout. I have 7 rows and I would like the components in the center which is the reason I am using a new panel. Some rows also have multiple components that I would like to add.

Please make a simple small program that compiles and executes to show your problem.

really 288 posts and again and again with empty question, here is your example, please would be possible to demostate your hidden/secret problem on that

import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import javax.swing.*;
//http://stackoverflow.com/questions/2228735/how-do-i-fade-an-image-in-swing/2234020#2234020
public class AlphaTest extends JPanel implements ActionListener {

    private static final Font FONT = new Font("Serif", Font.PLAIN, 32);
    private static final String STRING = "Mothra alert!";
    private static final float DELTA = -0.1f;
    private static final Timer timer = new Timer(100, null);
    private static final long serialVersionUID = 1L;
    private float alpha = 1f;

    AlphaTest() {
        this.setPreferredSize(new Dimension(256, 96));
        this.setOpaque(true);
        this.setBackground(Color.black);
        timer.setInitialDelay(1000);
        timer.addActionListener(this);
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setFont(FONT);
        int xx = this.getWidth();
        int yy = this.getHeight();
        int w2 = g.getFontMetrics().stringWidth(STRING) / 2;
        int h2 = g.getFontMetrics().getDescent();
        g2d.fillRect(0, 0, xx, yy);
        g2d.setComposite(AlphaComposite.getInstance(
                AlphaComposite.SRC_IN, alpha));
        g2d.setPaint(Color.red);
        g2d.drawString(STRING, xx / 2 - w2, yy / 2 + h2);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        alpha += DELTA;
        if (alpha < 0) {
            alpha = 1;
            timer.restart();
        }
        repaint();
    }

    static public void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setLayout(new GridLayout(0, 1));
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new AlphaTest());
                f.add(new AlphaTest());
                f.add(new AlphaTest());
                f.add(new AlphaTest());
                f.add(new AlphaTest());
                f.add(new AlphaTest());
                f.add(new AlphaTest());
                f.pack();
                f.setVisible(true);
            }
        });
    }
}

here is my code:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;


public class Conv implements ActionListener{

	private JTextField characterChange, characterReplace;
	private char charChange;
	private JLabel numberOfChangesLabel;
	private JLabel currentWord, targetWord, startingWord;
	private String answerWord = "TestWord", originalWord, changedWord;
	private JLabel blank = new JLabel ("  ");
	private int totalChanges = 0;
	
	
	public Conv (){
		JFrame f = new JFrame ("Word Conversion Game");
		
		JPanel pane = new JPanel (new GridLayout (7,1));
		
			targetWord = new JLabel (answerWord);
		
		pane.add (targetWord);
		
			currentWord = new JLabel (changedWord);
		
		pane.add (currentWord);
		
		JPanel charChangePane = new JPanel();
			charChangePane.add(new JLabel ("Character: "));
			characterChange = new JTextField (1);
			charChangePane.add(characterChange);
			charChangePane.add (new JLabel ("Replacement: "));
			characterReplace = new JTextField (1);
			charChangePane.add (characterReplace);
		pane.add (charChangePane);
		
		JPanel p = new JPanel ();
			JButton change = new JButton ("Change");
		p.add (change);
		pane.add (p);
		
		pane.add (new JPanel().add (new JLabel ("Number of Changes: ")));
		
		numberOfChangesLabel = new JLabel("" + totalChanges);
		
		pane.add ((new JPanel ().add(numberOfChangesLabel)));
		
		JPanel resetPanel = new JPanel ();
			JButton reset = new JButton ("Reset");
			startingWord = new JLabel (originalWord);
			resetPanel.add (startingWord);
			resetPanel.add (reset);
		pane.add (resetPanel);	
		
			
		f.add(pane);
		f.pack();
		f.setVisible (true);
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		Conv c = new Conv ();
	}


	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}

it currently does nothing. I am just getting the layout

Can you explain what you want the GUI to look like?
What is wrong with it now?

1/ if is there just 7 JPanels, then you can set LayoutManager for each JPanel separatelly, by defalut is there FlowLayout


JPanel pane = new JPanel (new GridLayout (7,1));
targetWord = new JLabel (answerWord);
pane2.setLayout(new BorderLayout())
pane2.add (targetWord, BorderLayout.CENTER);

etc...

2/ otherwise better would be create separate class for every JPanels

3/ or look for GridBagLayout or MigLaoyut

I am not to good at using the grid bag layout which is why I am not using it. The MigLayout seems interesting. My plan was to cut down a line by creating a JPanel with a flow layout in the add statement.

the current layout is like this

TEXT...........
Text...........
.....GROUP.....
....BUTTON.....
TEXT...........
TEXT...........
..TEXT&BUTTON..

I would like it all to be centered.

.....TEXT.....
.....TEXT.....
.....GROUP....
....BUTTON....
.....TEXT.....
.....TEXT.....
..TXT&BUTTON..

My idea was to use the flow layout in each of the cells in the grid to center everything, but this means adding it to a panel so that it keeps its original size.

Member Avatar for hfx642

Try using...

targetWord = new JLabel (answerWord, JLabel.CENTER);

The JLabel.CENTER fixed everything. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.