ボタンに .jpg 画像があります。また、画像の上にテキストを配置したいと考えています。そのために次の構文を使用します。
JButton btn = new JButton(label,icon);
しかし、ボタンにテキストが表示されません (画像のみ)。私は何を間違っていますか?
テキストとアイコンが表示されない理由がわかりません。デフォルトでは、テキストはアイコンの右側に描画されます。
使用するアイコンの上にテキストを表示するには:
JButton button = new JButton(...);
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);
任意のスイング コンポーネントで好きなようにプレイしたい場合は、paint() メソッドをうまくオーバーライドできます。このように、好きなことを何でもできます。
package test;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonTest {
public static void main(String[] args){
new ButtonTest().test();
}
public void test(){
JFrame frame = new JFrame("Biohazard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pnl = new JPanel();
pnl.add(new MyButton());
frame.add(pnl);
frame.setSize(600, 600);
frame.setVisible(true);
}
class MyButton extends JButton{
public void paint(Graphics g){
//anything you want
}
}
}
JButton button = new JButton(text,icon);
button.setVerticalTextPosition(SwingConstants.TOP);
button.setHorizontalTextPosition(SwingConstants.CENTER);
これは私にとってはうまくいきました。
画像の上にテキストを重ねようとしていますか、それとも単にテキストを画像の外側に配置しようとしていますか? 画像の外側にテキストを配置するのは簡単で、@camickr が述べたようにデフォルトの動作です。テキストを一番上に移動するには:
ImageIcon icon = new ImageIcon(pathToicon);
JButton myButton = new JButton("Press me!", icon);
myButton.setVerticalTextPosition(SwingContstants.TOP);
また、.gif、.jpg、および .png のみであることに注意してください。ImageIcon によって処理されます
デフォルトでは、スイング ボタンの水平方向のテキスト位置はSwingConstants.TRAILING
であり、アイコンの後にテキストが描画されます (チェックボックスまたはラジオ ボタンを考えてください)。テキストをアイコンの中央に配置する場合は、ボタンの水平方向のテキスト位置を設定するだけです:
JButton button = new JButton(label, icon);
button.setHorizontalTextPosition(SwingConstants.CENTER);