如何将图像图标设置为JButton?

时间:2015-10-22 12:20:05

标签: java swing netbeans jbutton embedded-resource

我想将图像图标设置为JButton,这是我尝试过的代码:

public class Calculator {

    public static JFrame f;

    Calculator() throws IOException{

        JButton b;

        f = new JFrame();
        Image play = ImageIO.read(getClass().getResource("images/play.png"));
        b = new JButton(new ImageIcon(play));

        b.setBounds(250,250,75,20);

        f.add(b);
        f.setSize(500,500);
        f.setLayout(null);
        f.setVisible(true);
    }

    public static void main(String[] args) throws IOException {

        new Calculator();
    }
}

程序正常运行且没有错误,但图像没有出现。

我认为图片网址错误。

我正在使用netbeans,所以我在源包目录中创建了一个名为images的文件夹。

2 个答案:

答案 0 :(得分:1)

可以通过在资源路径前加斜杠来解决此问题:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" ></uses-permission>
<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" ></uses-permission>

这表示import java.io.File; import java.io.IOException; import java.sql.SQLOutput; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.MediaRecorder; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StrictMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.text.SimpleDateFormat; import java.util.List; public class MainActivity extends Activity { public double longi1 = 0.0; public double lati1 = 0.0; public LocationListener locationListener ; public TextView Longi1; public TextView Lati1; Button b1; int cekbutton; public String filename=""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); Date now = new Date(); String fileName = formatter.format(now); private static final String AUDIO_RECORDER_FILE_EXT_AMR = ".amr"; private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder"; private MediaRecorder recorder = null; private int currentFormat = 0; private int output_formats[] = {MediaRecorder.OutputFormat.RAW_AMR}; private String file_exts[] = {AUDIO_RECORDER_FILE_EXT_AMR}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(Build.VERSION.SDK_INT > 9){ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } b1 = (Button) findViewById(R.id.button); getlongilatifile(); b1.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ if(cekbutton==0) { cekbutton=1; b1.setText("STOP"); startRecording(); } else if(cekbutton==1) { stopRecording(); Intent i = new Intent(MainActivity.this,halaman2.class); i.putExtra("nama", filename); startActivity(i); } } }); } public void getlongilatifile(){ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String bestProvider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(bestProvider); Longi1= (TextView) findViewById(R.id.textView1); Lati1= (TextView) findViewById(R.id.textView); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub longi1 = location.getLongitude(); lati1 = location.getLatitude(); Longi1.setText(longi1+""); Lati1.setText(lati1+""); try { DefaultHttpClient hc=new DefaultHttpClient(); ResponseHandler<String> res=new BasicResponseHandler(); HttpPost postMethod = new HttpPost("http://10.0.2.2:8080/send_malem_3.php"); System.out.printf("test setelah nyambung"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("nama", fileName+".amr")); postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response2 = hc.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { Toast.makeText(getBaseContext(), "Gagal 2", Toast.LENGTH_SHORT).show(); // TODO Auto-generated catch block e.printStackTrace(); } } }); } private void startRecording(){ recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(output_formats[currentFormat]); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); getFilename(); recorder.setOutputFile(filename); recorder.setOnErrorListener(errorListener); recorder.setOnInfoListener(infoListener); try { recorder.prepare(); recorder.start(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void getFilename(){ String filepath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filepath,AUDIO_RECORDER_FOLDER); if(!file.exists()){ file.mkdirs(); } filename = (file.getAbsolutePath() + "/" + fileName + file_exts[currentFormat]); } private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() { @Override public void onError(MediaRecorder mr, int what, int extra) { AppLog.logString("Error: " + what + ", " + extra); } }; private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() { @Override public void onInfo(MediaRecorder mr, int what, int extra) { AppLog.logString("Warning: " + what + ", " + extra); } }; private void stopRecording(){ if(null != recorder){ recorder.stop(); recorder.reset(); recorder.release(); recorder = null; } } 文件夹位于所有资源的根位置,而不是相对于当前类位置。

积分部分转到Andrew Thompson的评论。

答案 1 :(得分:0)

尝试使用b.setIcon(new ImageIcon(getClass().getResource("images/play.png")));