how to change the background color of Buttons in a JPanel?


hey

I know how to change the background color for buttons.

but if you 50 button in a panel and you want all of them to have same color. it's really hard to write code for 50 button or 200 button a panel to chage thier color.

is there a way to change all with very simple code.


Jbutton1.setbackground(Color.red)
...........
Jbutton50.setBackground(color.red)

Posted On: Wednesday 17th of October 2012 06:09:25 AM Total Views:  119
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




How can I change DefaultCellEditor#setClickCountToStart(int) for DefaultTreeCellEditor

because TreeCellEditor is availble only at 3rd. mouse click my SSCCE demonstrate a.m. issue import java.awt.BorderLayout; import javax.swing.*; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellEditor; public class TreeEdit { public static void main(String args[]) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Object array[] = {Boolean.TRUE, Boolean.FALSE, ""}; JTree tree = new JTree(array); tree.setEditable(true); tree.setRootVisible(true); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); String elements[] = {"A", "B", "C", "D"}; JComboBox comboBox = new JComboBox(elements); comboBox.setEditable(true); TreeCellEditor comboEditor = new DefaultCellEditor(comboBox); TreeCellEditor editor = new DefaultTreeCellEditor(tree, renderer, comboEditor); tree.setCellEditor(editor); JScrollPane scrollPane = new JScrollPane(tree); frame.add(scrollPane, BorderLayout.CENTER); frame.setSize(300, 150); frame.setVisible(true); } }
VIEWS ON THIS POST

106

Posted on:

Saturday 22nd September 2012
View Replies!

how to change third level sub menu item position?

I have a popup menu up to four level. Let's say : Aaaaaaa->Bbbbbbb->Ccccccc->Ddddddd When mouse is right clicked at right bottom of the screen Popup menu is shown. If I move mouse on Aaaaaaa since no place for second level, Bbbbbbb is shown at left of Aaaaaaa, then if I move mouse on Bbbbbbb then Ccccccc appears at right of Bbbbbbb. Problem is here, I want Ccccccc is displayed left of Bbbbbbb and Ddddddd is at left of Ccccccc. sub menus should opened towards left. Note: This of course should be reverse when I right click at left bottom of screen. This time I want all submenus will be opened at right of it's parent.
VIEWS ON THIS POST

167

Posted on:

Monday 24th September 2012
View Replies!

Create and dynamically change buttons in jtable column

I am having a lot of problems fully grasping tablecellrenderer and tablecelleditor. I have researched a lot, looked in a lot of forums, but still can't solve my problem. Without posting an sscce (because my code is probably very incorrect), how would I do the following: Create a jtable with a column that has ButtonX in it. Then when another column in a specific row gets a certain value, ButtonX will change to ButtonY, but other rows will remain what they are already. In the following example, all rows started with ButtonX, but when Progress changed from Uploading to Complete, ButtonX became ButtonY. Row Name Progress Abort/Complete 0 File 1 Complete ButtonY 1 File 2 Complete ButtonY 2 File 3 Uploading ButtonX The buttons need to update accordingly if a row is deleted. For example if row 0 is deleted, it should look like: Row Name Progress Abort/Complete 0 File 2 Complete ButtonY 1 File 3 Uploading ButtonX
VIEWS ON THIS POST

274

Posted on:

Monday 24th September 2012
View Replies!

Trying to get a square change color on button click

EDIT: Obviously a beginners question! Probably in the wrong forum, please feel free to move mods! Apologies! I thought I'd help myself understanding the GUI and ActionListener proces a bit better by sussing out how to do something simple like putting a button and a rectangle on a screen and then having it change color from blue to red on buttonclick. Appears I've ended up in a swamp and everytime I move I get sucked farther in. I soon found out I have no clue how to easily change the color of something when clicking a button so I thought I'd fake it first by simply running a different color panel on mouseclick. And that failed miserably too! Trying to use the boolean swoosh in two different classes is not the way to go. So a little help, hint or push in the right direction would be greatly appreciated! import javax.swing.*; import java.awt.*; import java.awt.event.*; public class KnopOefen implements ActionListener { JFrame frame; public static void main(String[] args) { boolean swoosh = true; KnopOefen knop = new KnopOefen(); knop.go(); } public void go() { frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Click to make the square red!"); button.addActionListener(this); Rectangle recty = new Rectangle(); frame.getContentPane().add(BorderLayout.SOUTH, button); frame.getContentPane().add(BorderLayout.CENTER, recty); frame.setSize(300,300); frame.setVisible(true); } public void actionPerformed(ActionEvent event) { boolean swoosh = false; KnopOefen knip = new KnopOefen(); knip.go(); } }
VIEWS ON THIS POST

172

Posted on:

Wednesday 26th September 2012
View Replies!

Clean way to change between mutlible pictures

, I want to make a game, but before even attempting that I want to get some of the basics of it down and generally have a rather ok\clean code to work from. What I am basically trying to have is a picture that shows like a world-map, and when you click on some part of the world-map your taken to a new picture showing a bit more detailed information of the area(and so on depending on amount of areas). The way I'm doing this is to get the x\y coordination from the mouse, and then change the picture to another picture if it is within the coordination, however this would mean I'd need unthinkable amount of if\else statements, especially considering different conditions and states(which is fine, but it seems way too unorganized). I did try to create a class for each location, however when I did that I didn't manage to neither go back or change to another location(which was another class itself). So I'm just wondering, is there any cleaner ways to do this then having either a million of functions for each location within 1 class Or having it all spammed down with lots of if\else's and\or functions in the main class *The code of the latest attempt* import java.awt.*; import java.awt.event.*; import java.net.*; public class GameTest extends Frame implements MouseListener { private Image img; private boolean gotoworld = false; // to check if outside of world map public GameTest() { addMouseListener(this); // start at the world map URL myurl = this.getClass().getResource("images/Map-1.png"); Toolkit tk = this.getToolkit(); img = tk.getImage(myurl); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){System.exit(0);}}); } @Override public void paint(Graphics g) { g.drawImage(img,0,10,this); } @Override public void mousePressed(MouseEvent e) { // go back to the world map if(gotoworld == true) { if((e.getX() >= 7) & (e.getX() = 5) & (e.getY() = 43) & (e.getX() = 152) & (e.getY()
VIEWS ON THIS POST

103

Posted on:

Wednesday 26th September 2012
View Replies!

JList model elements pre exist, updating of vector does not change model

so a few entries already exist in the jList. however, once the vector "caller" gets updated the values are not updated in the jList. Please help! thanks! public void split1(Vector v1) { this.caller = v1; left = new JPanel(); left.setLayout(new BorderLayout()); DefaultListModel model = new DefaultListModel(); customerList = new JList(model); scroll = new JScrollPane(customerList); scroll.setPreferredSize(new Dimension(150, 500)); left.add(scroll); String[] entries = {"one", "two", "three"}; for (int i = 0; i < entries.length; i++) { model.addElement(entries[i]); } if (caller != null) { String hell = caller.get(0) + " " + caller.get(1); validate(); int index = customerList.getSelectedIndex(); // get selected index if (index == -1) { // no selection, so insert at beginning index = 0; } else { // add after the selected item index++; } model.addElement(hell); customerList.setSelectedIndex(index); customerList.ensureIndexIsVisible(index); customerList.repaint(); scroll.revalidate(); scroll.repaint(); } }
VIEWS ON THIS POST

125

Posted on:

Wednesday 26th September 2012
View Replies!

JCheckboxMenuItem won't change selection color

guy, Am I doing something wrong or what I want to change the color for the selection background of the JCheckboxMenuItem and it doesn't change at all. This is what I have, what am i doing wrong UIManager.put( "CheckBoxMenuItem.acceleratorForeground", Crawler.color_black); UIManager.put( "CheckBoxMenuItem.acceleratorSelectionForeground", Crawler.color_black); UIManager.put( "CheckBoxMenuItem.background", Crawler.color_white); UIManager.put( "CheckBoxMenuItem.border",BorderFactory.createLineBorder(Crawler.color_white, 1)); UIManager.put( "CheckBoxMenuItem.disabledBackground", Crawler.color_white); UIManager.put( "CheckBoxMenuItem.disabledForeground", Crawler.color_white); UIManager.put( "CheckBoxMenuItem.foreground", Crawler.color_black); UIManager.put( "CheckBoxMenuItem.selectionBackground", Crawler.color_blue); UIManager.put( "CheckBoxMenuItem.selectionForeground", Crawler.color_black);
VIEWS ON THIS POST

87

Posted on:

Wednesday 26th September 2012
View Replies!

change back text of button with help of Thread.sleep()

hi, i want my button text to change automatically after 1 second to the default text which i have given. i have used thread but its not working help me. public void actionPerformed(ActionEvent arg) { frame.repaint(); if(b1.getText().equals("click to change color")) // this is my default text in the button { b1.setText("color changed"); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } b1.setText("click to change color"); //i want this text to appear automatically after a second in the button without clicking it } else{ b1.setText("click to change color"); }
VIEWS ON THIS POST

136

Posted on:

Thursday 27th September 2012
View Replies!

how to change the 'check' in a JCheckbox

Hi - I'm wondering if anyone has tried this before. What I'm trying to code is to have a checkbox in my JTable row but instead of putting a 'check' in the checkbox, I want to change the color of the checkbox when it's checked and leave the background of the checkbox text normal. I've tried in my TableCellRenderer class to change the background of the checkbox, but it changes the color of the entire cell not just the checkbox. I'm hoping this is something easy but as I've never coded in Swing before, I'm at a loss as to how to do it. I attached a pic of what I'm trying to do maybe try using a button instead many
VIEWS ON THIS POST

76

Posted on:

Saturday 29th September 2012
View Replies!

How can I change a .jpg icon image of an icon for a jLabel using Eclipse IDE?

I had done it successfully using Netbeans in this example: http://www.coderanch.com/t/565811/GUI/java/Newbie-just-trying-change-icon But now, I switched to Eclipse (using the WindowBuilder Pro plugin). It generates a method stub, which I filled with JLabel lblJlabela = null; lblJlabela.setIcon(new ImageIcon("J:\\Eclipse Folder\\Eclipse1GUI\\Photos\\Viper3.jpg")); I had to add the first line of that because it was telling me that lblJlabela was "unresolved"...it auto-suggested that I do that. But here's the whole program. import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class FlashGUI { String[] CarorBike = null; JLabel[] labels; private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FlashGUI window = new FlashGUI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public FlashGUI() { initialize(); JLabel lblJlabela = null, lblJlabelb = null; //labels = new JLabel[]{lblJlabela, lblJlabela, lblJlabelb}; } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 562, 875); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblJlabela = new JLabel("jLabelA"); lblJlabela.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { do_lblJlabela_mousePressed(e); } }); lblJlabela.setIcon(new ImageIcon("J:\\Eclipse Folder\\Eclipse1GUI\\Photos\\Viper1.jpg")); lblJlabela.setBounds(57, 55, 462, 298); frame.getContentPane().add(lblJlabela); JLabel lblJlabelb = new JLabel("jLabelB"); lblJlabelb.setIcon(new ImageIcon("J:\\Eclipse Folder\\Eclipse1GUI\\Photos\\Valkyrie1.jpg")); lblJlabelb.setBounds(42, 438, 448, 300); frame.getContentPane().add(lblJlabelb); } private void do_lblJlabela_mousePressed(MouseEvent e) { JLabel lblJlabela = null; lblJlabela.setIcon(new ImageIcon("J:\\Eclipse Folder\\Eclipse1GUI\\Photos\\Viper3.jpg")); } }
VIEWS ON THIS POST

117

Posted on:

Monday 1st October 2012
View Replies!

How to save the changes made in Jtree to the source file

Hi Friends, I'm a newbie in Java and we are creating one application where we fetch the data from a file and creating a tree structure (JTree) and we are able to change the data in JTree but the changes which we made in JTree are not reflecting in our file. Please help me out with this how to push back the data to the same file with changes we made in JTree.
VIEWS ON THIS POST

89

Posted on:

Monday 1st October 2012
View Replies!

how to keep change after i edit the Jtree's leaves??

I have following code can edit the leaf of the JTree, But after i edit it, I found what I updated is lost, How can I persist all changes I made to these edited leaves and nodes(not leaf). ie, to keep all these changes until i update them later. thanks sunny girl import java.awt.BorderLayout; import java.util.EventObject; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellEditor; import javax.swing.tree.TreeNode; public class EditLeafSample { public static void main(String args[]) { JFrame frame = new JFrame("Editable Tree"); JTree tree = new JTree(); tree.setEditable(true); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); TreeCellEditor editor = new LeafCellEditor(tree, renderer); tree.setCellEditor(editor); JScrollPane scrollPane = new JScrollPane(tree); frame.getContentPane().add(scrollPane, BorderLayout.CENTER); frame.setSize(300, 150); frame.setVisible(true); } } class LeafCellEditor extends DefaultTreeCellEditor { public LeafCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { super(tree, renderer); } public LeafCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { super(tree, renderer, editor); } public boolean isCellEditable(EventObject event) { // Get initial setting boolean returnValue = super.isCellEditable(event); // If still possible, check if current tree node is a leaf if (returnValue) { Object node = tree.getLastSelectedPathComponent(); if ((node != null) && (node instanceof TreeNode)) { TreeNode treeNode = (TreeNode) node; returnValue = treeNode.isLeaf(); } } return returnValue; } }
VIEWS ON THIS POST

80

Posted on:

Monday 1st October 2012
View Replies!

change text area background color at run time.

I have text area which is initially disabled on a button click i am enabling it and I am trying to change background color at run time but its not working. Can any body help me I am doing the below: notesJTextArea.setEditable(editable); Color color = Color.white; notesJTextArea.setBackground(color);
VIEWS ON THIS POST

155

Posted on:

Monday 1st October 2012
View Replies!

change the texts to a different one in a JButton each time it is pressed.

hello friends i am new to gui programming.. i was testing the following simple code public class SimpleGui implements ActionListener { JButton button; public static void main(String[] args) { SimpleGui gui=new SimpleGui(); gui.go(); } public void go() { JFrame frame=new JFrame(); button=new JButton("click me"); button.addActionListener(this); frame.add(button); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent event){ button.setText("button clicked"); } }
VIEWS ON THIS POST

146

Posted on:

Monday 1st October 2012
View Replies!

Newbie just trying to change icon image in a Jframe

I used Netbeans drag and drop design interface and it spit out this code: (I know some basic Java, but hardly any Swing or Jframe stuff, although I did read a few chapters from Dietel & Deitel book (actually, many chapters). Seems it should be pretty easy but I am not sure exactly how to go about it. The code it generated has setIcon() as part of a private function...I've looked up repaint and others but the example they gave were not clear to me. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JavaImageAppUI.java * * Created on Jan 28, 2012, 6:26:33 PM */ package my.javaimageappui; /** * * @author batman */ public class JavaImageAppUI extends javax.swing.JFrame { /** Creates new form JavaImageAppUI */ public JavaImageAppUI() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setIcon(new javax.swing.ImageIcon("/home/batman/Desktop/Viper-Green.jpg")); // NOI18N jLabel1.setText("jLabel1"); jButton1.setText("Next Image>"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(148, 148, 148) .addComponent(jButton1)) .addGroup(layout.createSequentialGroup() .addGap(62, 62, 62) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(71, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE) .addComponent(jButton1) .addContainerGap()) ); pack(); }// private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //This is where I would like to add some code to change the photo } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JavaImageAppUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JavaImageAppUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JavaImageAppUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JavaImageAppUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JavaImageAppUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; // End of variables declaration }
VIEWS ON THIS POST

100

Posted on:

Tuesday 2nd October 2012
View Replies!

cant i change LAF at runtime?

i have given lot of themes or lookandfeel of jtatoo in my application but the problem is when i click or select any laf the laf should change it is changing also but partially , i mean after changing laf at runtime i m not getting the entire look of that theme how to do that any idea
VIEWS ON THIS POST

116

Posted on:

Wednesday 3rd October 2012
View Replies!

JTable row change event?

I'm displaying database rows in a JTable and wan't to detect when a user selects a different row in the list of rows. The default behaviour is that you can highlight different rows but I don't know what event to listen for or how. Any ideas My aim is to display fields from the highlighted row in form input types so the user can update them.
VIEWS ON THIS POST

60

Posted on:

Wednesday 3rd October 2012
View Replies!

Swing + SWT, change mouse cursor to WAIT (newbie question)

all! I am a new to Eclipse RCP and I am having a trouble with getting a few things done correctly. The thing that I want to do is to change mouse cursor in whole application. I have 2 views in my app, one is a setting pane and the other one presents results. Both of them incorporate Swing containers, because I had to use old pieces of code, special graphs etc. Loading the result pane takes time, usually a few seconds. Meanwhile I want the cursor to be changed. So, when I press the correct button, I try to do something like that: Runner.enableWaitCursor(); if (comboMapa.getSelectedIndex()==0){ Register.getMapaView().clearMap(); comboSity.removeActionListener(sl); comboSity.setEnabled(false); comboSity.setSelectedIndex(0); registerActionListenerToSites(); comboCentra.removeActionListener(cl); comboCentra.setSelectedIndex(0); registerActionListenerToCentres(); } else { Register.getMapaView().loadMap(); comboSity.removeActionListener(sl); comboSity.setEnabled(true); registerActionListenerToSites(); } Runner.setMap(comboMapa.getSelectedIndex()); Runner.disableWaitCursor();
VIEWS ON THIS POST

94

Posted on:

Wednesday 3rd October 2012
View Replies!

How to change the alignment of buttons in a toolbar

! I've been searching for an answer a long time now. Some other issues I had I got solved simply by using the search in this forum ;) Ok, I have got a toolbar in my GUI and when I drag it out of the window and let it snap back again, the alignment of the buttons should change. That means when the toolbar is in the north(I am using border layout), the buttons should go from left to right, when it is in the east, they should go from up to down. Is there maybe some kind of event I can listen to so I can change the alignment manually Thank you for your help!
VIEWS ON THIS POST

79

Posted on:

Wednesday 17th October 2012
View Replies!

Restore the swing components with its value unchanged

Hi Guys, I'm developing a POS application in java swing. In my application, i have 3 different types of Billing screens (they're Jframes..) with their Jcomponents were different .But what i'm exactly need is to have a "Screen switch-over" option (like Alt+Tab in Windows XP) so that while i'm typing items for a bill in Screen-1 , i can switch over immediately by simple keyboard strokes to Screen-2 and make a bill in screen 2 and switch again to my Screen-1 so that my contents in Screen-1 remained unchanged.... Please guide me to do this.
VIEWS ON THIS POST

92

Posted on:

Wednesday 17th October 2012
View Replies!