Joh*_*Joe 2 java user-interface swing
为button Back和button Delete,我setBounds到(130,120,195,30) ; 和(10,190,195,30); ,但他们仍然没有走到谷底.
这有什么不对?
public deleteAdmin(int num)
{
super("Delete Admin");
setBounds(100, 200, 340, 229);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel = new JPanel();
panel.setBounds(35, 19, 242, 146);
contentPane.add(panel);
JButton button = new JButton("Back");
button.setBounds(130, 120, 195,30);
panel.add(button);
JButton bckButton = new JButton("Delete");
bckButton.setBounds(10, 190, 195,30);
panel.add(bckButton);
adminAPI admin = new adminAPI();
List<String>allName = null;
try {
allName= admin.displayName();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(allName);
Object [] o1=allName.toArray();
JCheckBox[] checkBoxList = new JCheckBox[num];
System.out.println(allName);
//JLabel[] names = new JLabel[num];
for(int i = 0; i < num; i++) {
checkBoxList[i] = new JCheckBox(""+o1[i]);
System.out.println(o1[i]);
contentPane.add(checkBoxList[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
快速简单和错误的答案是,您正在调用尝试将精确的组件放置到使用布局管理器的容器中,这仅在组件使用null布局时才有效,但这又不是一个好的解决方案,因为这会导致严格GUI非常难以增强,升级和调试.
你的主要问题是你setBounds(...)首先尝试使用它.更好的方法是学习使用布局管理器并以智能方式使用它们,以便轻松高效地将组件放置在您想要的位置.通常你会想要嵌套JPanels,每个JPanels都使用自己的布局管理器来帮助放置好东西.
比如这个gui:
是用这段代码创建的:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class DeleteAdmin2 extends JPanel {
private List<JCheckBox> checkBoxes = new ArrayList<>();
public DeleteAdmin2() {
JPanel topPanel = new JPanel(new GridLayout(1, 0, 5, 5));
topPanel.add(new JButton("Back"));
topPanel.add(new JButton("Delete"));
String[] texts = { "A1", "B1", "C1", "D1", "E1", "A2", "B2", "C2", "D2", "E2" };
JPanel checkBoxPanel = new JPanel(new GridLayout(0, 5, 5, 5));
for (String text : texts) {
JCheckBox checkBox = new JCheckBox(text);
checkBoxes.add(checkBox);
checkBoxPanel.add(checkBox);
}
setLayout(new BorderLayout(5, 5));
add(topPanel, BorderLayout.PAGE_START);
add(checkBoxPanel, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Delete Admin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DeleteAdmin2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
Run Code Online (Sandbox Code Playgroud)
一些方面的建议:
"Need help in GUI"告诉我们什么都不能帮助我们理解什么是错的.而是使用类似的东西:"JButtons没有在GUI中正确放置"或类似的东西.这样做有助于提高您的问题的眼球,从而获得更快更好的答案.