Google
 
Web itpro-blogger.blogspot.com
火曜日, 10月 17, 2006

[Java]メモ3

▼質問
ButtonGroupで作成したボタングループを、プログラムから選択させたい時はどうやるんだい?

▼回答
2つのラジオボタンを選択されていない状態で生成してから、ラジオボタン2を選択された状態にする。

ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton radioButton1 = new JRadioButton( "ラジオボタン1", false );
JRadioButton radioButton1 = new JRadioButton( "ラジオボタン2", false );
buttonGroup.add( radioButton1 );
buttonGroup.add( radioButton2 );
buttonGroup.setSelected( radioButton2.getModel(), true );

▼質問
選択されたラジオボタンをすべて解除するにはどうしたらいいの?

▼回答
ButtonGroupを作成し直す?!しかないのかな・・・?
removeしてaddする。。。。

removeしてaddするだけでは駄目のようだ。
setSelectedメソッドでfalseをセットしてやらないと解除できないみたい。

ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton[] radioButton = new JRadioButton[2];

~略~

for ( int i = 0 ; i < radioButton.length ; i++ ) {
if ( radioButton[i].isSelected() ) {
buttonGroup.remove( radioButton[i] );
radioButton[i].setSelected( false );
buttonGroup.add( radioButton[i] );
}
}

▼質問
テキストフィールドの入力文字数をバイト長で制限したいんだけどどうやればいいの?

▼回答
public class LimitedJTextField extends javax.swing.JTextField {

public LimitedJTextField( int limit ) {
this.setDocument( new ByteLengthLimitedDocument( limit ) );
}

static class ByteLengthLimitedDocument extends javax.swing.text.PlainDocument {

private int limit;

public ByteLengthLimitedDocument( int limit ) {
this.limit = limit;
}

public void insertString( int offs, String str, AttributeSet a ) throws BadLocationException {

if ( str == null ) return;

String text = this.getText( 0, getLength() );
byte[] bytes = text.getBytes();

if ( bytes.length >= limit ) return;

super.insertString( offs, str, a );

}
}

}

■参考サイト
http://java-house.jp/ml/archive/j-h-b/020938.html

▼質問
同じような処理でクラスを分けなくて済む方法はないのかな?

クラスのタイプを判断して処理を分けたいんだ。

▼回答
getClassメソッドを使えばできるよ!

cとdはparentを継承して作成されている。
Object parent;
Object c;
Object d;
public void setParent(Object obj) {
parent = obj;
if ( parent.getClass().equals( c ) ) {
c = (c)obj;
}
else if ( parent.getClass().equals( d ) ) {
d = (d)obj;
}
}

■参考サイト
http://www.asahi-net.or.jp/~dp8t-asm/java/tips/HowToGetClass.html






Comments: コメントを投稿

<< Home

This page is powered by Blogger. Isn't yours?