Java言語のSwingコーポネント「JToggleButton」で選択後の背景色を変更する方法

このQ&Aのポイント
  • Java言語のSwingコーポネント「JToggleButton」では、選択後のボタンの背景色を変更する方法について質問があります。
  • 選択前のボタンの背景色はsetBackGroundメソッドで変更できますが、ボタンを押すと色が元に戻ってしまいます。
  • コンストラクタ内や他のクラスからsetBackGroundメソッドを実行しても、選択されていない状態では背景色が変わりません。
回答を見る
  • ベストアンサー

Java言語のSwingコーポネント「JToggleButton」につ

Java言語のSwingコーポネント「JToggleButton」について質問です。 選択後のボタンの背景はどうすれば変更できるでしょうか? 選択前のボタンはsetBackGroundで変更できるのですが、ボタンを押すと色が元に戻ってしまいます。 コンストラクタ内でも他のクラスからでも、また選択されていない状態でsetBackGroundを実行しても変わりません。 以下ソースコード public コンストラクタ(){ this.setBackground(Color.YELLOW);//これでも無理 this.setSelected(true); this.setBackground(Color.YELLOW);//これでも無理 this.setIcon(icon); }

  • Java
  • 回答数1
  • ありがとう数4

質問者が選んだベストアンサー

  • ベストアンサー
  • tom11
  • ベストアンサー率53% (134/251)
回答No.1

逃げ道として、アイコンの駆使なんてどうかな??? 図のような程度までは、逃げられるみたいですよ。

yone6379
質問者

お礼

それでうまくいきそうです。 ありがとうございました。

関連するQ&A

  • javaのプログラムについての質問です。

    javaのプログラムについての質問です。 javaについて、あまり詳しくないので質問させていただきます。 ボタンを押して円などの色を変えるプログラムで、2色を変える(黄→赤)if文は public void actionPerformed(ActionEvent e) { if (bool) { setBackground(Color.yellow); this.bool = false; } else { setBackground(Color.red); this.bool = true; の様にfalseとtrueを使えばできるのですが、もし3、4色の場合はif文の中をどうしたら良いですか? できれば、ボタンを押すたびに黄→赤→黒→黄…など3~4色のループするようにしたいです。 いろいろ考えたのですが、うまくいきません。どなたか教えて下さい。

    • ベストアンサー
    • Java
  • swing初心者です

    swingを使って簡単なアプレットを作ったのですが、ボタンの表示のタイミングが妙です。ボタンが起動時に表示されず、マウスオーバーして初めて表示されます。 import java.awt.*; import javax.swing.*; public class Test extends JApplet implements Runnable{ public void init(){ getContentPane().add(new JButton("START")); new Thread(this).start(); } public void run(){ try{ while(true){ Thread.sleep(10); } catch(InterruptedException ie){ ie.printStackTrace(); } } } これはどうしてなのでしょうか。初歩的な質問かもしれませんが、どうかご教授お願いいたします。 環境 WindowsXP SP2, java1.5.0_07

    • ベストアンサー
    • Java
  • JavaのSwingのレイアウト

    Swingを学習中ですが、うまくレイアウトできません。 添付した画像のようなレイアウトにしたいです。 作ってみたものは以下です。 import java.awt.BorderLayout; import java.awt.Color; import javax.swing.*; public class LayoutTest { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); JTextField searchFiled = new JTextField("テキスト"); String[] comboboxString = {"C", "C++", "Java"}; JComboBox comboBox = new JComboBox(comboboxString); JButton button = new JButton("ボタン"); panel.add(comboBox, BorderLayout.EAST); panel.add(searchFiled, BorderLayout.CENTER); panel.add(button, BorderLayout.WEST); frame.add(panel, BorderLayout.PAGE_START); JPanel redPanel = new JPanel(); redPanel.setBackground(Color.RED); frame.add(redPanel); frame.setSize(700, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); } }

    • ベストアンサー
    • Java
  • Swingについての質問です

    Swingについての質問です  まだJava初心者です^^。とんでもない質問でしたらすいません。  Swingの中の、JFrameを使って、ある図形を描画するという場面です。描画はできたのですが、コンピュータの画面から図形がはみ出してしまって、全体を見る事ができません。そこで、スクロールバーを表示したいと思っているのですが、その方法はどうすれば良いのでしょうか?  下に、普段私が使っている、一本の線を描画するサンプルを書いておきます。 import java.awt.*; import javax.swing.*; public class Sample extend JPanel { public static void main(String[] args){ JFrame frame = new JFrame("Sample"); TestFrame tf = new TestFrame(); frame.add(tf); frame.getComponents().add(tf); frame.setSize(120, 120); //ウインドウサイズを120×120に指定 frame.setBackground(Color.WHITE); frame.setVisible(true); } } class TestFrame extends JPanel{ void paintComponent(Graphics g){ g.drawLine(10, 10, 100, 100); //(10, 10)から(100, 100)に線を描画 } }  もちろんこの場合はスクロールバーは必要ないですが、このような場合でもウインドウサイズを50×50のような小さいサイズにしてしまったときだけスクロールバーが現れるようにできたらもっと嬉しいです。  回答宜しくお願いします。

    • ベストアンサー
    • Java
  • javaのsetColor、setBackgroundについて

    プログラミング初心者で、困っています。教えてください。Javaで g.setColor(Color.red); というサンプルに良くあるコードをコンパイルしてもエラーになってしまいます。 import java.applet.Applet; import java.awt.Graphics; public class First2 extends Applet{ public void init() { setBackground(Color.yellow); } } をコンパイルすると C:\myJ\test1>javac First2.java .\Color.java:7: ')' がありません。 g.setColor(Color red); ^ First2.java:6: シンボルを見つけられません。 シンボル: 変数 yellow 場所 : Color の クラス setBackground(Color.yellow); ^ .\Color.java:6: java.awt.Graphics は abstract です。インスタンスを生成することは できません。 Graphics g = new Graphics(); ^ .\Color.java:7: シンボルを見つけられません。 シンボル: 変数 Color 場所 : Color の クラス g.setColor(Color red); ^ エラー 4 個 となってしまうんです。 ネット上のいろんなサイトでは問題なく動作するように 書かれていますが、なぜエラーになるんでしょう? どうしたら解決できますか?ご指南下さい。 ちなみにjavaのversion は 1.6 です。

    • ベストアンサー
    • Java
  • JavaのSwingで別のフォームを閉じる方法

    こんにちは。 JavaのSwingにおいて,以下のようなプログラムがあるとします。 その場合,A.javaでボタンを押すと,B.javaのフォームが閉じるようにしたいのですがどのようにしたらいいのでしょうか?よろしくお願いします。 ****A.java**** import ☆省略☆; public class A extends JFrame implements ActionListener{ //ボタン JButton end; public A(){ //フレームの設定 setVisible(true); setTitle("テスト"); //コンテナの設定 con = getContentPane(); //ボタン end = new JButton(" 終了 "); end.addActionListener(this); end.setActionCommand("end"); con.add(end); pack(); } public void actionPerformed(ActionEvent e){ String m = e.getActionCommand(); if(m == "end"){ ※ここに書くべき処理 } } } ****B.java**** import ☆省略☆; public class B extends JFrame{ //コンテナ Container con; public Answer(){ //フレームの設定 setVisible(true); setTitle("B"); //コンテナに関わる設定 con = getContentPane(); } }

  • 別ウインドウに画像と文字を表示しない

     こんにちは。  ボタンをクリックすると、別ウインドウが開いて、画像と文字が表示される アプレットを作りたいのですが、別ウインドウは開きますが、画像と文字は 表示されません。  何度考えても、全く原因が分かりません。  皆さんのご教示宜しくお願いします。 ================================================================================ public class ImageTest extends Applet implements ActionListener { Image img1 , img2 ; JLabel jb1 ; int lblnum ; MyPanel1 mp1 ; Graphics g ; public void init() { img1 = getImage( getDocumentBase() , "star1.jpg" ) ; this.setBackground( Color.yellow ) ; this.setLayout( null ) ; JPanel jp1 = new JPanel() ; jp1.setSize( 1500 , 850 ) ; jp1.setLayout( null ) ; jp1.setBackground( Color.yellow ) ; JPanel jp2 = new JPanel() ; jp2.setBackground( Color.magenta ) ; this.add( jp1 ) ; this.add( jp2 ) ; JLabel jl1 = new JLabel( new ImageIcon( "star1.gif" ) ) ; jl1.setSize( 150 , 150 ) ; jl1.setLocation( 50 , 50 ) ; jp1.add( jl1 ) ; JButton jb1 = new JButton( "star" ) ; jb1.setMargin(new Insets( 1 , 1 , 1 , 1 ) ) ; jb1.setBorderPainted( false ) ; jb1.setForeground( Color.red ) ; jb1.setBackground( Color.yellow ) ; jb1.setLocation( 75 , 210 ) ; jb1.setSize( 100 , 50 ) ; jb1.setFont( new Font( "SansSerif" , Font.ITALIC , 20 ) ) ; jb1.addActionListener( this ) ; jp1.add( jb1 ) ; } public void actionPerformed( ActionEvent e ) { Object source = e.getSource() ; if( source == jb1 ) lblnum = 1 ; MyPanel1 mp1 = new MyPanel1( lblnum , img1 ) ; mp1.setVisible( true ); repaint(); } class MyPanel1 extends Frame { int k ; String str ; Image img ; public MyPanel1( int k , Image img ) { this.k = k ; this.img = img ; setSize( 500 , 500 ) ; setBackground( Color.magenta ) ; setLocation( 300 , 300 ) ; } public void init( ) { switch( k ) { case 1: str = "test" ; break ; } setVisible( false ) ; } public void paint( Graphics g ) { g.drawImage( img , 0 , 0 , 30 , 30 , this ) ; g.drawString( str , 150 , 150 ) ; } } } ================================================================================

    • ベストアンサー
    • Java
  • DocumentListenerについて

    DocumentListenerについて 以下のソースのinsertUpdateメソッド内のsetText()でエラーになります。 actionPerformedの場合はエラーになりませんでした。 ご存じの方がおられましたら教えてください。 public class test_1 extends Frame { public static void main(String[] args) { new test_1().setVisible(true); } String name; JTextField a = new JTextField(); JLabel b = new JLabel("Ctl + C", JLabel.CENTER); JButton b1 = new JButton(); ClosingListener c = new ClosingListener(); public test_1() throws HeadlessException { super(); this.setTitle("日時の/と:を取り除く"); this.setSize(400, 150); this.addWindowListener(c); a.setFont(new Font("", Font.BOLD, 30)); a.setFocusable(true); a.putClientProperty("caretAspectRatio", Float.valueOf(0.3F)); a.setForeground(Color.cyan); a.setBackground(Color.yellow); a.getDocument().addDocumentListener(new MyListener()); b.setBackground(Color.white); b.setFont(new Font("", Font.BOLD, 30)); b.setPreferredSize(new Dimension(150, 150)); this.add(a, BorderLayout.CENTER); this.add(b, BorderLayout.WEST); } class ClosingListener extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } class MyListener implements DocumentListener {//123/123:123 public void changedUpdate(DocumentEvent de) { } public void insertUpdate(DocumentEvent de) { name = a.getText(); name = name.replaceAll("/", "_"); name = name.replaceAll(":", "_"); System.out.println("name==" + name); a.setText(name);//エラー /* Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1323) at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:644) at javax.swing.text.JTextComponent.setText(JTextComponent.java:1693) at test_1$MyListener.insertUpdate(test_1.java:68) */ a.requestFocusInWindow(); a.selectAll(); a.cut();//切り取りはできているが、テキストフィールドの文字列は消えない。 } public void removeUpdate(DocumentEvent de) { } } }

    • ベストアンサー
    • Java
  • Java swing RTFファイル 文字化けする

    Java初心者です。 今、下記のようなプログラムを作成しました。 import java.awt.*; import java.io.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.rtf.*; class RTFView extends JFrame { public RTFView() { setTitle( "RTF Text Application" ); setSize(1200, 720); setBackground( Color.gray ); getContentPane().setLayout( new BorderLayout() ); JPanel topPanel = new JPanel(); topPanel.setLayout( new BorderLayout() ); getContentPane().add( topPanel, BorderLayout.CENTER ); // Create an RTF editor window RTFEditorKit rtf = new RTFEditorKit(); JEditorPane editor = new JEditorPane(); editor.setEditorKit( rtf ); editor.setBackground( Color.white ); // This text could be big so add a scroll pane JScrollPane scroller = new JScrollPane(); scroller.getViewport().add( editor ); topPanel.add( scroller, BorderLayout.CENTER ); // Load an RTF file into the editor try { FileInputStream fi = new FileInputStream( "test.rtf" ); rtf.read( fi, editor.getDocument(), 0 ); } catch( FileNotFoundException e ) { //ファイルがない場合 cmd 上に(" ")内が表示される System.out.println( "File not found" ); JEditorPane ep1 = new JEditorPane(); } catch( IOException e ) { System.out.println( "I/O error" ); } catch( BadLocationException e ) { } } public static void main( String args[] ) { // Create an instance of the test application RTFView mainFrame = new RTFView(); mainFrame.setVisible( true ); } } コンパイル後、test.rtfを読み込むものにしましたが、 読込後、日本語が文字化けしてしまっています。 どのように対処すればよいのでしょうか? 検索してもなかなか見つからないので質問させていただきました。 ご回答の程よろしくお願いいたします。

  • JButtonの画像をactionPerformedメソッド内で再描画

    JButtonの画像をactionPerformedメソッド内で再描画したい。 以下のソースのようにして、再描画したいのです。 setIconメソッドではなく、 JButtonに対して描画したものに対して再描画したいです。 Graphics2DクラスについてJAVA APIで調べましたが、 仕組の理解に至りませんでした。 仕組みと方法を教えて頂きたいです。 よろしくお願いいたします。 import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; public class test extends JFrame implements ActionListener{ JButton b= new JButton(); public static void main(String a[]) { new test(); } public test() { super(); this.setSize(100,100); b.addActionListener(this); b.add(new Zoom(new ImageIcon("img1.jpg"),0,0,50,50)); this.add(b); this.setVisible(true); } class Zoom extends JComponent { private static final long serialVersionUID = 1L; private ImageIcon icon = null; private int x = 0; private int y = 0; private int h = 0; private int w = 0; private double scale = 1.0d; public Zoom(ImageIcon icon, int x, int y, int w, int h) { super(); this.icon = icon; this.x = x; this.y = y; this.w = w; this.h = h; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.scale(scale, scale); ////////////////////////////////// //画僧を再描画したい。 //g2.clearRect(0, 0, 80, 80);//× g2.drawImage(icon.getImage(), x, y, w, h, this); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==b){ System.out.print("ok"); //this.repaint();//× //b.repaint();//× b.add(new Zoom(new ImageIcon("img2.jpg"),0,0,50,50));//(再描画できない) //b.setIcon(new ImageIcon("img2.jpg"));//ok(再描画出来る) } } }

    • ベストアンサー
    • Java

専門家に質問してみよう