我的JPanel所有设置都有一个工作的JFrame GUI。我正在尝试组合我已经设置和工作的两个不同的代码。第一个代码是JPanel中的文本转换器toUpperCase,第二个代码是Prime Factor(非素数)代码。我一直试图让JPanel为用户输入的任何数字提供Prime Factor的输出。这就是我的......
JPanel代码
public class Prime extends JPanel {
private JLabel formattedText;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Prime());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
public Prime(){
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(640,100));
JLabel label = new JLabel("Enter a number to check for it's prime number(s).");
JTextField field = new JTextField("0");
field.addActionListener(new FieldListener());
add(label);
add(field);
add(panel);
panel = new JPanel(); panel.setPreferredSize(new Dimension(640,380));
formattedText = new JLabel();
panel.add(formattedText);
add(panel);
}
private class FieldListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
JTextField field = (JTextField)event.getSource();
formattedText.setText(field.getText().toUpperCase()); // I know this is wrong... I can't figure out what to change here to get it to pull the code below.
}
}
public class PrimeFactors {
}
}
这里是Prime Factor代码
public class Temp {
static int primeCheck = 1;
public static void main(String[] args) {
System.out.println("Enter a number whose Prime factors are desired: ");
Scanner numS = new Scanner(System.in);
int numPriFac = 0;
if (numS.hasNextInt()) {
numPriFac = numS.nextInt();
}
System.out.println("All the Prime Factors of the entered number are:");
for (int tap = 1; tap <= numPriFac; tap++) {
if (numPriFac % tap == 0) {
for (int primeTest = 2; primeTest < tap; primeTest++) {
if (tap % primeTest == 0) {
primeCheck = 1;
break;
} else {
primeCheck = 0;
}
}
if (primeCheck == 0 || tap == 2) {
System.out.print(tap + " ");
}
}
}
}
}
底部的最后一个PrimeFactors代码只是在我试图让它独立工作时遗留下来的东西。非常感谢任何帮助!!!
答案 0 :(得分:0)
第1步:更改第
行 public static void main(String[] args) {
类似
public static String primeFactors(int number) {
并使该方法使用提供的参数number
,而不是要求输入。
第2步:在primeFactors
中创建StringBuilder,并将对System.out.print
的所有来电更改为对stringBuilder.append()
第3步:将stringBuilder.toString()
设为primeFactors
第4步:更改行
formattedText.setText(field.getText().toUpperCase());
到
formattedText.setText(Temp.primeFactors(Integer.parseInt(field.getText())));
我会留下错误处理并输入安全保护。