有没有办法选择上一个消息对话框或下一个消息对话框?我有一个程序,在完成所有输入和数学计算后,会出现一个消息对话框,其中包含“人员1”的信息,然后按下确定,出现“人员2”的信息.如果可以选择能够在不同的对话框之间导航,那将是很好的.这是打印消息的程序的一部分.
for (i = 0; i < NumEmployees; i++)
{
JOptionPane.showMessageDialog(null,
"Employee: " + names[i] + "\n" +
"ID: " + data[i][0] + "\n" +
"Hours worked: " + (data[i][1] + data[i][2]) + "\n" +
"Overtime: " + data[i][2] + "hours" + "\n" +
"Amount earned: " + payment[i]);
}
解决方法:
使用Action
“将功能和状态与组件分开.”在下面的示例中,操作更改索引并从List< String>更新()JLabel.您的应用程序可能会从列表< Employee>更新JTextArea.
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* @see https://*.com/a/20116944/230513
*/
public class PrevNext {
private final List<String> list = new ArrayList<>(
Arrays.asList("Alpher", "Bethe", "Gamow", "Dirac", "Einstein"));
private int index = list.indexOf("Einstein");
private final JLabel label = new JLabel(list.get(index), JLabel.CENTER);
private void display() {
JFrame f = new JFrame("PrevNext");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JButton(new AbstractAction("<Prev") {
@Override
public void actionPerformed(ActionEvent e) {
if (--index < 0) {
index = list.size() - 1;
}
update();
}
}), BorderLayout.LINE_START);
f.add(label);
f.add(new JButton(new AbstractAction("Next>") {
@Override
public void actionPerformed(ActionEvent e) {
if (++index == list.size()) {
index = 0;
}
update();
}
}), BorderLayout.LINE_END);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private void update() {
label.setText(list.get(index));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new PrevNext().display();
}
});
}
}