我有一个JButton
我想保留在 JTextField
的最右边,无论我如何缩放窗口。我知道BorderLayout.EAST
,但这似乎不起作用。这是我当前的代码( userText
是我的 JTextField
):
imageButton = new JButton("Attach an Image");
if(System.getProperty("os.name").equals("Mac OS X")){
imageButton.setLocation(455, 0);
imageButton.setSize(150, 30);
} else {
imageButton.setLocation(435, 0);
imageButton.setSize(150, 20);
}
imageButton.addActionListener(
//SOME FUNCTIONALITY CODE HERE
);
userText.add(imageButton);
我知道这段代码非常糟糕。如果我不转售任何东西,它就会产生这个(忽略消息是什么):
所以这看起来一切都很好(抱歉我剪得有点不好),但是当我转售它时......
这显然一点也不好看。当我改变userText.add(imageButton)
至userText.add(imageButton, BorderLayout.EAST)
该按钮只是停留在左上角。当我尝试将其添加到 JFrame
时,它只是 JTextArea
右侧的一个大按钮。 ,所以我不太确定该怎么办?
那么,如何让按钮停留在 JTextField
的右侧 我是否应该将按钮添加到 JTextField
或者我应该将它添加到其他组件中?
根据要求,这里是一个简单但完整的示例(抱歉缩进):
public class Test extends JFrame{
private JTextField userText;
private JButton imageButton;
private JTextArea chatWindow;
public Test(){
super("Test");
userText = new JTextField();
add(userText, BorderLayout.NORTH);
imageButton = new JButton("Problem Button");
if(System.getProperty("os.name").equals("Mac OS X")){
imageButton.setLocation(455, 0);
imageButton.setSize(150, 30);
}
else{
imageButton.setLocation(435, 0);
imageButton.setSize(150, 20);
}
userText.add(imageButton);
chatWindow = new JTextArea();
setSize(600, 300);
setVisible(true);
}
public static void main(String[] args) {
Test test = new Test();
}
}
最佳答案
只需使用 JPanel
作为按钮。将此面板布局设置为 FlowLayout 并将其对齐方式设置为 RIGHT。然后将其添加到框架的北位置。
这里是一个示例代码:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FrameTest extends JFrame {
private JTextField userText;
private JButton imageButton;
private JTextArea chatWindow;
public FrameTest() {
super("Test");
userText = new JTextField();
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(userText, BorderLayout.CENTER);
imageButton = new JButton("Problem Button");
if (System.getProperty("os.name").equals("Mac OS X")) {
imageButton.setLocation(455, 0);
imageButton.setSize(150, 30);
}
else {
imageButton.setLocation(435, 0);
imageButton.setSize(150, 20);
}
topPanel.add(imageButton, BorderLayout.EAST);
add(topPanel, BorderLayout.NORTH);
chatWindow = new JTextArea();
setSize(600, 300);
setVisible(true);
}
public static void main(String[] args) {
FrameTest test = new FrameTest();
}
}
关于java - 让 JButton 位于 JTextField 的一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189293/