我正在做我的学校项目。我的目标是做一个钢琴游戏。该程序运行良好,但是当我遇到问题时,我的工作停止了。我想把我从推送特定 JButton 中获得的整数放入数组中。例如,如果我按 JButton 3、JButton 4 和 JButton 1,我将进入我的数组 [3,4,1]。请帮助我。此致敬意。这是我的代码:
import javax.swing.*;
import javax.sound.sampled.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.Color;
class vse_v_enem extends JFrame implements ActionListener
{
public static void main(String [] arg){
new vse_v_enem();
}
public vse_v_enem(){
initSounds();
}
protected void initSounds(){
sounds();
zacetek();
}
public void sounds(){
for(int i=1;i<=13;i++)
try{
audioIn[i] = AudioSystem.getAudioInputStream(vse_v_enem.class.getResource("zvoki/"+i+".wav"));
//System.out.println("zvoki/"+i+".wav.wav");
} catch(javax.sound.sampled.UnsupportedAudioFileException e){
} catch(Exception e){
System.out.println("Hm.... something went wrong");
}
}
public void zacetek (){
JFrame okvir = new JFrame("Klaviaturska zabava");
okvir.setBounds(500,400,416,214);
JLayeredPane panel = new JLayeredPane();
okvir.add(panel);
//int f[] = igra();
/**naredi crne tipke*/
int crnih = 5;
int sirina = 30;
int visina = 113;
for(int i = 0; i<crnih;i++){
JButton b = new JButton(""+(i+1));
b.setFont(b.getFont().deriveFont((float)11));
b.setForeground(Color.WHITE);
b.setBackground(Color.BLACK);
b.setSize(sirina,visina);
b.setLocation(i*50 + (sirina*3)-5,0);
b.addActionListener(this);
panel.add(b,1,-1);
}
/** naredi bele tipke*/
int belih = 8;
int sirina1 = 50;
int visina1 = 176;
for (int i = 6; i<belih+6; i++){
JButton b = new JButton(""+i);
b.setBackground(Color.WHITE);
b.setLocation((i-6)*sirina1,0);
b.setSize(sirina1,visina1);
b.addActionListener(this);
panel.add(b,0,-1);
}
okvir.setVisible(true);
}
public void predvajajZvBesedilo(AudioInputStream audioIn){
sounds();
try {
clip = AudioSystem.getClip();
clip.open(audioIn);
} catch(Exception e) {};
clip.setFramePosition(0);
clip.start();
}
public void tabela(int tab){
}
public void actionPerformed(ActionEvent e){
JButton tempButton = (JButton)e.getSource();
System.out.print( tempButton.getText() + " " );
int clipNr = Integer.valueOf(tempButton.getText());
//tabela(tab[clipNr]);
predvajajZvBesedilo( audioIn[clipNr]);
}
public int[] igra(){
int t [] = {4,5,8,6};
System.out.print("[ ");
for(int i = 0; i < t.length; i++){
//t[i] = (int)(Math.random()*13+1);
System.out.print(t[i]+" ");
}
System.out.print("] ");
System.out.println();
System.out.println();
return t;
}
public void delay (int i){
try {
Thread.sleep(i*1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
private JFrame okvir = null;
private Clip clip = null;
int [] tab = new int [igra().length];
AudioInputStream audioIn[] = new AudioInputStream[14];
}
将JButton
添加到您的JFrame
中。然后在addActionListener
方法的帮助下将ActionListener
添加到您的按钮中。在ActionListener
的方法actionPerformed
中,您需要确定按下的按钮,就像下一个方式一样按下if(e.getSource() == button1) array[i] = 1;
e
是ActionEvent参数。对所有按钮使用一个侦听器,这是您的框架.我认为这对你有帮助。