[英]How do I place more than one JComponent on the same “line” on a confirm JOptionPane?
這是我的代碼:
public class PaymentDialog {
public static int show(Double value) {
JLabel total = new JLabel("Total: ");
JLabel totalValue = new JLabel(value.toString());
JLabel input = new JLabel("Entrada: ");
JTextField inputField = new JTextField();
JLabel change = new JLabel("Troco: ");
JLabel changeValue = new JLabel("1234");
JComponent[] components = new JComponent[] {
total,
totalValue,
input,
inputField,
change,
changeValue
};
int result = JOptionPane.showConfirmDialog(null, components, "Pagamento", JOptionPane.OK_CANCEL_OPTION);
return result;
}
}
這是它的圖像:
如您所見,每個組成部分占據一整行,這是殘酷的。 標簽應位於其相應組件的后面,而不是其上方。
如何自定義此布局行為? 如果不可能,如何創建允許我執行此操作的自定義JDialog? (因為我不想創建一個JFrame來正確自定義布局,因為這不是同一件事)。
您可以將任何組件添加到選項窗格。 因此,您可以創建自己的面板並使用任何布局並添加所需的任何組件。
一個問題是文本字段沒有焦點。 焦點將位於選項窗格的按鈕上。
如果要集中在文本字段上,請簽出Dialog Focus中的RequestFocusListener
。 當顯示選項窗格時,這將允許您控制面板上的哪個組件獲得焦點。
它還包含用於創建帶有GridLayout的面板以顯示在選項窗格上的示例代碼。
我將代碼發布給未來的人類:
public class PaymentDialog {
public static int show(Double value) {
JPanel componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(3, 2));
JLabel total = new JLabel("Total: ");
JLabel totalValue = new JLabel(value.toString());
JLabel input = new JLabel("Entrada: ");
JTextField inputField = new JTextField();
JLabel change = new JLabel("Troco: ");
JLabel changeValue = new JLabel("1234");
componentPanel.add(total);
componentPanel.add(totalValue);
componentPanel.add(input);
componentPanel.add(inputField);
componentPanel.add(change);
componentPanel.add(changeValue);
int result = JOptionPane.showConfirmDialog(null, new JComponent[]{componentPanel}, "Pagamento", JOptionPane.OK_CANCEL_OPTION);
return result;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.