所以,我有一個類,其中有一個單選按鈕。然後在第二節課中,我擴展了第一課,並創建了3個「if」語句,這些語句將根據單選按鈕的輸出創建一個小程序。在那些「if」語句中,它表示變量無法解析。我如何解決這些問題?請告訴我在我的代碼中是否有其他錯誤。感謝一百萬,:D。不能從另一個類訪問變量
謝謝,任何幫助將有極大的幫助。
// The First Class Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
public RadioButton() {
// Create the radio buttons
JRadioButton displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setSelected(true);
//Displacement Button, set to automatically be clicked
JRadioButton accel = new JRadioButton("Acceleration");
accel.setMnemonic(KeyEvent.VK_A);
accel.setActionCommand("acceleration");
//Acceleration Button
JRadioButton time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(accel);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
accel.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(accel);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand()
+ ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
我的第二課堂,與if語句
import java.lang.Object;
import java.awt.Graphics;
public class RadioButtonMain extends RadioButton {
public static void main(String [ ] args) {
if (displacement.isSelected())
{
//Option 1 for applet
}
if (accel.isSelected()) {
//Option 2 for applet
}
else {
//Option 3 for applet
}
}
}
如果沒有RadioButton類的對象,不能訪問位移。你必須爲這個類創建一個對象,然後只有你可以訪問它。還要注意,public static void main()是當時程序的入口點,你的編譯器不知道任何關於位移的東西。 –