因此,我正在创建一个项目,它是Java的框架,但我遇到了一些对齐问题。当我运行我的代码时,显示“帮助页”的居中顶部文本被推到左边,而帮助字符串则向下移动一点,但也被推到右边。我的目标是以顶部的文本为中心,并与下面的其他文本划线,也是居中的。我试过使用多个面板,但仍然没有起作用,我猜是字体大小不匹配,我不知道。任何帮助都是非常感谢的!
private void helpGUI() {
clearGUI();
helpStr = "<html><br>This is the help page where the user can come for help<html/>";
label = new JLabel("<html><u>Help Page</u></html>");
label.setFont(new Font("Times", Font.PLAIN, 24));
helpTxt = new JLabel(helpStr);
helpTxt.setFont(new Font("Times", Font.PLAIN, 16));
panel.add(label);
panel.add(helpTxt);
panel.setAlignmentX(CENTER_ALIGNMENT);
button = new JButton("Previous");
bttnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bttnPanel.add(button);
frame.add(panel);
class previousButton implements ActionListener {
public void actionPerformed (ActionEvent e) {
GUIPG1(name);
}
}
button.addActionListener(new previousButton());
}
发布于 2022-01-31 09:48:22
这实际上取决于您试图实现的目标(例如,JPanel应该包含哪些其他组件)。就这两个标签吗?您还可以在代码中显示一个按钮。这应该加在哪里?)。无论如何,对于顶部有两个文本的特定面板,您可以使用BoxLayout
垂直添加JLabels
,并使用setAlignmentX()
设置文本的水平对齐方式。例子如下:
编辑:(关于文本的基础和对中),您可以在下面的示例中使用以下内容:
titleLbl = new JLabel("<html><u>Help Page</u></html>", SwingConstants.CENTER);
titleLbl.setFont(new Font("Times New Roman", Font.PLAIN, 24));
titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
App.java
import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
import java.util.*;
public class App {
private void addComponentsToPane(Container pane) {
JLabel titleLbl = new JLabel("Help Page");
// add text attributes (i.e., underline, font family, font size, etc)
Font font = titleLbl.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
attributes.put(TextAttribute.FAMILY, "Times New Roman");
attributes.put(TextAttribute.SIZE, 24);
titleLbl.setFont(font.deriveFont(attributes));
titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
JLabel infoLbl = new JLabel("This is the help page where the user can come for help");
infoLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT);
infoLbl.setFont(new Font("Times New Roman", Font.PLAIN, 16));
Box box = new Box(BoxLayout.Y_AXIS);
box.add(titleLbl);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(infoLbl);
pane.add(box, BorderLayout.NORTH);
}
private void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.setSize(640, 480);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new App().createAndShowGUI();
}
});
}
}
https://stackoverflow.com/questions/70920161
复制相似问题