我编写了这段代码,但在使其从右向左对齐时遇到问题。 我尝试了几种方法,但没有一种有效。 我知道这可以通过调整坐标来完成,但我想要一种不需要对每个单词都这样做的方法。我应该如何正确地做到这一点?
代码:
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class GUI {
//messages
public static final String ConnectC_MSG = "התחבר" ;
public static final String DisconnectC_MSG = "התנתק" ;
public static final String ServerLBL_MSG = "שרת יעד:" ;
public static final String UsernameLBL_MSG = ":שם משתמש";
public static final String PasswordLBL_MSG = ":סיסמא" ;
public static final String PortLBL_MSG = ":פתחה" ;
//sizes
public static final int SreverTxtfield_Width = 10;
public static final int UsernameTxtfield_width = 10;
public static final int PasswordTxtfield_width = 10;
public static final int PortTxtfield_width = 5 ;
public static final int WINDOW_WIDTH = 800;
public static final int WINDOW_HEIGHT = 200;
static JFrame frame1;
static Container pane;
static JButton btnConnect = new JButton(ConnectC_MSG),
btiDiscinnect = new JButton(DisconnectC_MSG);
static JLabel lblServer = new JLabel(ServerLBL_MSG),
lblUsername = new JLabel(UsernameLBL_MSG),
lblPassword = new JLabel(PasswordLBL_MSG),
lblPort = new JLabel(PortLBL_MSG);
static JTextField txtServer = new JTextField(SreverTxtfield_Width),
txtUsername = new JTextField(UsernameTxtfield_width),
txtPort = new JTextField(PortTxtfield_width);
static JPasswordField txtPassword = new JPasswordField(PasswordTxtfield_width);
static Insets insets;
public static void main(String[] args) {
frame1 = new JFrame ("הדגמה");
frame1.setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
frame1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
pane = frame1.getContentPane();
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
insets = pane.getInsets();
pane.setLayout(null);
pane.add(lblServer);
pane.add(lblUsername);
pane.add(lblPassword);
pane.add(lblPort);
pane.add(txtServer);
pane.add(txtUsername);
pane.add(txtPassword);
pane.add(txtPort);
lblServer.setBounds((int)(insets.right),insets.top,
lblServer.getPreferredSize().width, lblServer.getPreferredSize().height);
txtServer.setBounds(lblServer.getX()+lblServer.getWidth(), lblServer.getY()+lblServer.getHeight(),
txtServer.getPreferredSize().width, txtServer.getPreferredSize().height);
frame1.setVisible(true);
}
}
最佳答案
尝试如下:
JPanel panel = new JPanel( new FlowLayout(FlowLayout.RIGHT) );
panel.add(...);
panel.add(...);
...
frame.add(panel, BorderLayout.NORTH);
并且组件将与车架的骑行侧对齐。
此外,删除所有静态变量。这不是编写类的方法。
阅读 Swing 教程中关于 How to Use Flow Layout 的部分了解更多信息和示例。如果将向您展示一种更好的方法来构造您的类,而无需所有静态内容。
关于java - 如何在 JFrame/java 中从右到左对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898909/