我试图水平居中包含内联HTML的JLabel,但我似乎无法让它工作。我试过手动居中,但没有运气。
这就是我的样子:
全班代码:
import java.awt.Button;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Client extends JFrame{
private final String url = "http://example.com/";
public Client() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 225);
setResizable(false);
setLocationRelativeTo(null);
addComponents(mainPanel);
add(mainPanel);
setTitle(null);
setVisible(true);
}
public void addComponents(JPanel pane) {
Button btn1 = new Button("1");
btn1.setSize(200, 50);
btn1.setFocusable(false);
pane.add(btn1);
Button btn2 = new Button("2");
btn2.setSize(200, 50);
btn2.setFocusable(false);
pane.add(btn2);
Button btn3 = new Button("3");
btn3.setSize(200, 50);
btn3.setFocusable(false);
pane.add(btn3);
JLabel lblWebsite = new JLabel("<html><a href=\"" + url + "\">Visit lblAbout1</a></html>", BoxLayout.X_AXIS);
lblWebsite.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblWebsite.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
pane.add(lblWebsite);
}
}
答案 0 :(得分:0)
尝试使用JComponent#setAlignmentX()方法
将锚点封闭在与中心对齐的div
内。
JLabel lblWebsite = new JLabel("<html><div align='center'><a href=\"" + url + "\">Visit lblAbout1</a></div></html>", BoxLayout.X_AXIS);
lblWebsite.setAlignmentX(Component.CENTER_ALIGNMENT);
快照: