我需要使用JOptionPane来读取2个用户输入的数字,然后显示这两个数字的总和和产品,我无法理解如何为这个程序制作方框。
答案 0 :(得分:0)
有两种方法可以做到这一点:
JOptionPane
JOptionPane
为您构建面板这是两个例子:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class OptionPanePanel
{
private static void createAndShowUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
// Build a custom panel
JPanel panel = new JPanel( new GridLayout(2, 2) );
panel.setBackground(Color.RED);
panel.add( new JLabel("First Name") );
JTextField firstName = new JTextField(10);
// firstName.addAncestorListener( new RequestFocusListener(false) );
panel.add( firstName );
panel.add( new JLabel("Last Name") );
JTextField lastName = new JTextField(10);
panel.add( lastName );
int result = JOptionPane.showConfirmDialog(
frame, // use your JFrame here
panel,
"Use a Panel",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if(result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
// Let Option Pane build the panel for you
JTextField firstName2 = new JTextField(10);
// firstName2.addAncestorListener( new RequestFocusListener() );
Object[] msg = {"First Name:", firstName2, "Last Name:", lastName};
result = JOptionPane.showConfirmDialog(
frame,
msg,
"Use default layout",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
注意:
当你运行上面的代码时,焦点将放在JOptionPane上的按钮上。
如果您希望焦点位于文本字段上,则需要使用Request Focus Listener(下载类之后),如示例中所示。