問題描述
有沒有辦法可以選擇轉(zhuǎn)到上一個消息對話框或下一個?我有一個程序,在完成所有輸入和數(shù)學計算后,會出現(xiàn)一個消息對話框,其中包含Person 1"的信息,然后按確定"并出現(xiàn)Person 2"的信息.如果有一個選項可以在不同的對話框之間導航,那就太好了.這是打印消息的程序部分.
Is there a way to have an option to go the a previous message dialog box or a next one? I have a program where after all the input and math calculations is done, a message dialog box appears with the information for "Person 1" then you press ok and the one for "Person 2" appears. It would be nice if there could be an option to be able to navigate between the different dialog boxes. Here is the part of the program that prints the messages.
for (i = 0; i < NumEmployees; i++)
{
JOptionPane.showMessageDialog(null,
"Employee: " + names[i] + "
" +
"ID: " + data[i][0] + "
" +
"Hours worked: " + (data[i][1] + data[i][2]) + "
" +
"Overtime: " + data[i][2] + "hours" + "
" +
"Amount earned: " + payment[i]);
}
推薦答案
使用 Action
將功能和狀態(tài)從組件中分離出來."在下面的示例中,操作將 index
和 update()
從 List
更改為 JLabel
.您的應(yīng)用程序可能會從 List<Employee>
更新 JTextArea
.
Use Action
"to separate functionality and state from a component." In the example below, the actions change the index
and update()
a JLabel
from a List<String>
. Your application might update a JTextArea
from a List<Employee>
.
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 http://stackoverflow.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();
}
});
}
}
這篇關(guān)于java中的GUI“轉(zhuǎn)到上一個/下一個"選項?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!