如何在我的Java游戏菜单中居中按钮

huangapple go评论87阅读模式
英文:

How to center buttons in my java game menu

问题

基本上,我以前从未在Java中使用过Windows,我需要帮助将事物居中。我尝试了很多方法,但无论如何,我都无法将我的按钮居中在Java菜单上。

这是我的主类:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;

public class window extends JPanel {

    private static final long serialVersionUID = 1L;
    private BufferedImage canvas;

    public window(int width, int height) {
        canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    }

    public Dimension getPreferredSize() {
        return new Dimension(canvas.getWidth(), canvas.getHeight());
    }
    
    public void paint(Graphics g){ 
        // 这里是绘制图像的部分,已被注释掉
    }

    public static void main(String[] args) throws ClassNotFoundException, IOException {
        int width = 640;
        int height = 480;
        JFrame frame = new JFrame("Example Frame");

        window panel = new window(width, height);
        
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setResizable(false);
        
        JPanel buttons = new JPanel();
        
        BoxLayout boxlayout = new BoxLayout(buttons, BoxLayout.Y_AXIS);
        buttons.setLayout(boxlayout);
        
        buttons.setBorder(new EmptyBorder(new Insets(150, 200, 150, 200)));
        JLabel bottomLabel = new JLabel("GAME NAME HERE", SwingConstants.CENTER);
        buttons.add(bottomLabel);
        JButton jb1 = new JButton("Button 1");
        JButton jb2 = new JButton("Button 2");
        JButton jb3 = new JButton("Button 3");
        jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
        jb2.setAlignmentX(SwingConstants.CENTER);
        jb3.setAlignmentX(SwingConstants.CENTER);
        buttons.add(Box.createRigidArea(new Dimension(0, 10)));
        buttons.add(jb1); 
        buttons.add(Box.createRigidArea(new Dimension(0, 10)));
        buttons.add(jb2);
        buttons.add(Box.createRigidArea(new Dimension(0, 10)));
        buttons.add(jb3);
        
        frame.add(buttons);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // 下面是一些其他方法的调用,已被注释掉
    }
    
    // 下面是其他方法的定义,已被注释掉
}

您的问题是当我运行它时,发生了以下情况:

如何在我的Java游戏菜单中居中按钮

所以,按钮和/或测试都没有居中。我不明白为什么。

如何在我的Java游戏菜单中居中按钮

我的问题是,按钮应该在图像上的红线附近,但无论我做什么,我都无法让它正常工作。

我尝试使用SwingConstants.CENTER来居中它,但这不起作用,所以我还尝试了Component.CENTER_ALIGNMENT,但结果完全相同。我发现将代码更改为以下方式,多次尝试不同的方法:

jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);

这样做会得到这样的结果:

如何在我的Java游戏菜单中居中按钮

所以基本上,这使得与我更改的那个不同的两个按钮被正确居中,但我更改的那个不是。所有这些图像和内容可能都是不必要的,但我希望我已经传达了我需要帮助的内容!谢谢 =)

英文:

So, basically, I've never really worked with windows in java, and I need help centering things. I tried a bunch of things, but no matter what, I can't center my buttons on my java menu.

Here's my main class:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class window extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage canvas;
public window(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
public Dimension getPreferredSize() {
return new Dimension(canvas.getWidth(), canvas.getHeight());
}
public void paint(Graphics g){ 
//		    double CanvasTileHeight = (canvas.getHeight()/16)+1;
//		    double CanvasTileWidth = (canvas.getWidth()/16)+1;
//		    
//		    OpenSimplexNoise noise = new OpenSimplexNoise();
//		    
//		    for(int j=0;j<CanvasTileWidth;j++) {
//		    	double NoiseForCurrentLoopPos;
//		    	if (((noise.eval(j,2)+1)*2)+16 < CanvasTileHeight) {
//		    		NoiseForCurrentLoopPos = ((noise.eval(j,2)+1)*2)+16;
//		    	} else {
//		    		NoiseForCurrentLoopPos = CanvasTileHeight;
//		    	}
//		    	for(int i=(int) CanvasTileHeight;i>NoiseForCurrentLoopPos;i--) {
//		    			Image sand = Toolkit.getDefaultToolkit().getImage("src/images/misc/sand.png");
//		    			g.drawImage(sand, j*16, i*16, this);		    		
//		    	}
//		    }
//		    
//		    Image image = Toolkit.getDefaultToolkit().getImage("src/images/misc/Player_Placeholder1.png");
//		    
//		 ImageObserver paintingChild = null;
//		 g.drawImage(image, canvas.getWidth()/2-image.getWidth(paintingChild)/2, canvas.getHeight()/2-image.getHeight(paintingChild)/2, this);
//		    
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
int width = 640;
int height = 480;
JFrame frame = new JFrame("Example Frame");
window panel = new window(width, height);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
JPanel buttons = new JPanel();
BoxLayout boxlayout = new BoxLayout(buttons, BoxLayout.Y_AXIS);
buttons.setLayout(boxlayout);
buttons.setBorder(new EmptyBorder(new Insets(150, 200, 150, 200)));
JLabel bottomLabel = new JLabel("GAME NAME HERE", SwingConstants.CENTER);
buttons.add(bottomLabel);
JButton jb1 = new JButton("Button 1");
JButton jb2 = new JButton("Button 2");
JButton jb3 = new JButton("Button 3");
jb1.setAlignmentX(SwingConstants.CENTER);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb1); 
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb2);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb3);
frame.add(buttons);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        loadtest();
//        System.out.println(Arrays.toString(((String) test1).split(",")));
//        
//        savetest();
dirtest();
}
public static void savetest() {
String TestArray[] = {"hi87er629087029648276540982", "hi2", "hi3", "hi4", "Not gonna keep going on like this lol"};
String Test = TestArray[0];
String world = "testworld101022";
for (int k = 0; k < TestArray.length-1; k++) {
Test = Test + "," + TestArray[k+1];
}
new File("src\\saves\\" + world).mkdir();
try(FileOutputStream f = new FileOutputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectOutput s = new ObjectOutputStream(f)) {
s.writeObject(Test);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
static Object test1 = null;
public static void loadtest() {
String world = "testworld101022";
try(FileInputStream in = new FileInputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectInputStream s = new ObjectInputStream(in)) {
test1 = s.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} 
}
public static void dirtest() {
File dir = new File("src\\saves");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("No saves yet!");
} else {
for (int i = 0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}

My problem is when I run it, this is what happens:

如何在我的Java游戏菜单中居中按钮

So, the buttons and/or test are not centered. I don't understand why.

如何在我的Java游戏菜单中居中按钮

My problem is, the buttons should be about where the red line on the image is, but no matter what I do, I can't get it to work.

I tried centering it with SwingConstants.CENTER, but that diden't work, so I also tried Component.CENTER_ALIGNMENT, but that did the exact same thing. I found that doing multiple different things like changing the code to

jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);

makes it like this:

如何在我的Java游戏菜单中居中按钮

so basically it makes it so the 2 that are different from the one I changed are correctly centered, but the one I changed it not. All the images and stuff are probably unnecessary, but I hope I got across what I need help with! thanks =)

答案1

得分: 1

You can use BoxLayout to do that, take a look at the following code:

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.util.Arrays;

public class Main
{
    public static void main(final String[] args)
    {
        final JLabel label = new JLabel("GAME NAME HERE");
        final JButton button1 = new JButton("Button 1");
        final JButton button2 = new JButton("Button 2");
        final JButton button3 = new JButton("Button 3");

        final JPanel centerPanel = createCenterVerticalPanel(5, label, button1, button2, button3);

        final JFrame frame = new JFrame();
        frame.add(centerPanel);
        frame.setVisible(true);
        frame.pack();
    }

    private static JPanel createCenterVerticalPanel(final int spaceBetweenComponents, final JComponent... components)
    {
        final JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        Arrays.stream(components).forEach(component -> {
            component.setAlignmentX(JPanel.CENTER_ALIGNMENT);
            panel.add(component);
            panel.add(Box.createRigidArea(new Dimension(0, spaceBetweenComponents)));
        });

        return panel;
    }
}

If you also want to center a panel vertically in a frame, just use frame.setLayout(new GridBagLayout()). Cheers!

英文:

如何在我的Java游戏菜单中居中按钮You can use BoxLayout to do that, take a look at the following code:

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.util.Arrays;
public class Main
{
public static void main(final String[] args)
{
final JLabel label = new JLabel("GAME NAME HERE");
final JButton button1 = new JButton("Button 1");
final JButton button2 = new JButton("Button 2");
final JButton button3 = new JButton("Button 3");
final JPanel centerPanel = createCenterVerticalPanel(5, label, button1, button2, button3);
final JFrame frame = new JFrame();
frame.add(centerPanel);
frame.setVisible(true);
frame.pack();
}
private static JPanel createCenterVerticalPanel(final int spaceBetweenComponents, final JComponent... components)
{
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Arrays.stream(components).forEach(component -> {
component.setAlignmentX(JPanel.CENTER_ALIGNMENT);
panel.add(component);
panel.add(Box.createRigidArea(new Dimension(0, spaceBetweenComponents)));
});
return panel;
}
}

If you also want to center a panel vertically in a frame, just use frame.setLayout(new GridBagLayout()). Cheers!

huangapple
  • 本文由 发表于 2020年7月22日 04:02:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63022236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定