Change Background color on button Click


Hi

I want to change Background color of Jpanel and its font on button click.

Can anyone tell me what i am doing wrong
Here is the code:
import java.applet.*; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.event.*; import javax.swing.*; public class test3 extends Applet { JPanel c; JScrollPane s; Button connect; Panel controls; Color back,fore; public void init() { back = Color.black; fore = Color.white; setBackground(Color.darkGray); setLayout(new BorderLayout()); s = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); //s.setSize(100, 100); add("Center",s); c = new myCanvas11(this); s.setOpaque(false); s.setViewportView(c); //s.add(c); c.setSize(1000, 16000); add("North", controls = new Panel()); controls.setLayout(new FlowLayout()); controls.add(connect = new Button("Change Color")); } public void start() { // s.setScrollPosition(100, 100); } public boolean action(Event e, Object arg) { back = Color.magenta; fore = Color.blue; //setBackground(back); //invalidate(); //repaint(); c.setBackground(back); c.repaint(); //s.getViewport().setBackground(back); // s.getViewport().repaint(); //c.repaint(); c.setFocusable(true); return true; } } class myCanvas11 extends JPanel implements KeyListener { Image buffImage; Graphics offscreen; boolean initDone = false; int chw, chh; // size of a char (in pixels) int chd; // offset of char from baseline int width, height; // size of applet (in pixels) int w, h; // size of applet (in chars) Font fn; Graphics gr; int nh, nw; test3 owner; static int counter = 0; myCanvas11(test3 t) { super(); owner = t; nh = 16000; nw = 1000; this.setOpaque(true); this.setFocusable(true); addKeyListener(this); } public void reshape(int nx, int ny, int nw1, int nh1) { if (nw1 != width || nh1 != height) { width = nw; height = nh; gr = getGraphics(); fn = new Font("Courier", Font.PLAIN, 11); if (fn != null) gr.setFont(fn); FontMetrics fnm = gr.getFontMetrics(); chw = fnm.getMaxAdvance(); chh = fnm.getHeight(); chd = fnm.getDescent(); // kludge for Windows NT and others which have too big widths if (chw + 1 >= chh) { chw = (chw + 1) / 2; } // work out size of drawing area h = nh / chh; w = nw / chw; buffImage = this.createImage(nw, nh); offscreen = buffImage.getGraphics(); //offscreen.setColor(Color.black); //offscreen.fillRect(0, 0, nw, nh); offscreen.setColor(Color.blue); offscreen.setFont(fn); if (initDone) offscreen.drawString(" World!", 0, 50); else offscreen.drawString("khushbu", 2, 50); initDone = true; offscreen.drawImage(buffImage, 0, 0, this); } super.reshape(nx, ny, nw, nh); } public void paint(Graphics g) { // if (!initDone) // initpaint(g); // else g.drawImage(buffImage, 0, 0, this); //g.drawImage(buffImage, 0, 0, owner.back, this); } public void update(Graphics g) { g.drawImage(buffImage, 0, 0, this); super.update(g); //g.drawImage(buffImage, 0, 0, owner.back, this); } public void initpaint(Graphics g) { try { nh = getHeight(); nw = getWidth(); gr = getGraphics(); fn = new Font("Courier", Font.PLAIN, 11); if (fn != null) gr.setFont(fn); FontMetrics fnm = gr.getFontMetrics(); chw = fnm.getMaxAdvance(); chh = fnm.getHeight(); chd = fnm.getDescent(); // kludge for Windows NT and others which have too big widths if (chw + 1 >= chh) { chw = (chw + 1) / 2; } // work out size of drawing area h = nh / chh; w = nw / chw; buffImage = this.createImage(nw, nh); offscreen = buffImage.getGraphics(); //offscreen.setColor(Color.black); //offscreen.fillRect(0, 0, nw, nh); offscreen.setColor(Color.white); offscreen.setFont(fn); if (initDone) offscreen.drawString(" World!", 0, 50); else offscreen.drawString("khushbu", 2, 50); initDone = true; g.drawImage(buffImage, 0, 0, this); } catch (Exception e) { e.printStackTrace(); } } /** Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { } /** Handle the key pressed event from the text field. */ public void keyPressed(KeyEvent e) { String s; offscreen.setColor(owner.fore); offscreen.setFont(fn); for (int i = counter; i < counter + 25; ++i) { s = Integer.toString(i); offscreen.drawString(s, 3, i * chh); offscreen.drawLine(10, i * chh, 160, i * chh); } //owner.s.setScrollPosition(0, counter * 16); counter = counter + 25; repaint(); } /** Handle the key released event from the text field. */ public void keyReleased(KeyEvent e) { } public boolean keyDown(Event e, int k) { String s; offscreen.setColor(owner.fore); offscreen.setFont(fn); for (int i = counter; i < counter + 25; ++i) { s = Integer.toString(i); offscreen.drawString(s, 3, i * chh); offscreen.drawLine(10, i * chh, 160, i * chh); } //owner.s.setScrollPosition(0, counter * 16); counter = counter + 25; repaint(); return true; } }
Posted On: Saturday 22nd of September 2012 05:04:38 AM Total Views:  151
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




How to update changes made in JTree to xml file

, I have a xml file which i am parsing using a dom parser and displaying as a JTree. Now I want that if any changes are made in the JTree, the changes should get updated to the xml. Please help
VIEWS ON THIS POST

189

Posted on:

Wednesday 19th September 2012
View Replies!

create a jtable which can combine and split and the image change also

hi newbie here and would like to know how to create a jtable with default images and with specific column and rows that if you combine the cells the image enlarge and when split the image decreases.
VIEWS ON THIS POST

213

Posted on:

Wednesday 19th September 2012
View Replies!

Change icon color dinamically

! I'm trying to create a JFrame with 3 circles inside it and make it work like a traffic light. I've created a separate class for lights, but I can't make them change colors dinamically, because once the icon has been drawn, I can't change it's color anymore Should I give up this idea or there is a way to get it done package trafficlight; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.Icon; public class Light implements Icon { private int size; private Color colorOff = Color.BLACK; private Color currentColor = Color.BLACK; private Color colorOn; private int delay; public Light(Color color, int size, int delay) { this.colorOn = color; this.size = size; this.delay = delay; } public void switchLight(boolean turnOn) { //here I want to make my Light to change its color } @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(currentColor); g.drawOval(x, y, size, size); g.fillOval(x, y, size, size); } @Override public int getIconWidth() { return size; } @Override public int getIconHeight() { return size; } public int getDelay() { return delay; } public void setDelay(int delay) { this.delay = delay; } }
VIEWS ON THIS POST

115

Posted on:

Thursday 20th September 2012
View Replies!

color help

Folks, Below is a code I have been writing on my own (well a modification from what online version read). The error has been highlighted. import javax.swing.JOptionPane; public class playwithrange { public static void main(String[] args) { String color ; color= JOptionPane.showInputDialog("Choose between green, black and white"); switch (color){ case green: System.out.println("You are a green person"); break; default: System.out.println("Eh whatever"); } } }
VIEWS ON THIS POST

108

Posted on:

Thursday 20th September 2012
View Replies!

JcomboBox master, change the values of all jComboBoxes on a Jatable

Guys, I have one doubt, I'm using a single JcomboBox that must change all the Jcomboboxes of a jtable to the same value of the master jcombobox. I have the attached code, but It doesnt´t work, I dont know where could be the issue :S, could any body help me The master jComboBox is named: combo1 and this need to change all the comboboxes named: comboBox on the jtable called tbl. http://www.javaclub.com.mx/code/ComboBoxTable.java http://www.javaclub.com.mx/code/ComboBoxTable.txt package comboBox; import javax.swing.*; import javax.swing.table.*; import java.awt.Component; import java.awt.event.*; public class ComboBoxTable { private static JComboBox combo1; public static void main(String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception evt) {} JFrame f = new JFrame("Combo Box Table"); final JTable tbl = new JTable(new ComboBoxTableModel()); // Create the combo box editor JComboBox comboBox = new JComboBox(ComboBoxTableModel.getValidStates()); comboBox.setEditable(true); DefaultCellEditor editor = new DefaultCellEditor(comboBox); // Assign the editor to the second column TableColumnModel tcm = tbl.getColumnModel(); tcm.getColumn(1).setCellEditor(editor); // Set column widths tcm.getColumn(0).setPreferredWidth(200); tcm.getColumn(1).setPreferredWidth(100); // Set row heighht tbl.setRowHeight(20); tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); tbl.setPreferredScrollableViewportSize(tbl.getPreferredSize()); combo1=new JComboBox(); combo1.setBounds(350,10,80,20); combo1.addItem("On order"); combo1.addItem("In stock"); combo1.addItem("Out of print"); combo1.setVisible(true); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { TableColumn col = tbl.getColumnModel().getColumn(1); col.setCellRenderer(new MyComboBoxRenderer(ComboBoxTableModel.getValidStates())); } }; combo1.addActionListener(actionListener); f.add(combo1); f.getContentPane().add(new JScrollPane(tbl), "Center"); f.pack(); f.setSize(500, 300); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); f.setVisible(true); } } class ComboBoxTableModel extends AbstractTableModel { // Implementation of TableModel interface public int getRowCount() { return data.length; } public int getColumnCount() { return COLUMN_COUNT; } public Object getValueAt(int row, int column) { return data[row][column]; } public Class getColumnClass(int column) { return (data[0][column]).getClass(); } public String getColumnName(int column) { return columnNames[column]; } public boolean isCellEditable(int row, int column) { return column == 1; } public void setValueAt(Object value, int row, int column) { if (isValidValue(value)) { data[row][column] = value; fireTableRowsUpdated(row, row); } } // Extra public methods public static String[] getValidStates() { return validStates; } // Protected methods protected boolean isValidValue(Object value) { if (value instanceof String) { String sValue = (String)value; for (int i = 0; i < validStates.length; i++) { if (sValue.equals(validStates[i])) { return true; } } } return false; } protected static final int COLUMN_COUNT = 2; protected static final String[] validStates = { "On order", "In stock", "Out of print" }; protected static final String[] validStatesMaster = { "On order", "In stock", "Out of print" }; protected Object[][] data = new Object[][] { { "Core Java Volume 1", validStates[0] }, { "Core Java Volume 2", validStates[0] }, { "Core Web Programming", validStates[0] }, { "Core Visual Basic 5", validStates[0] }, { "Core Java Foundation Classes", validStates[0] } }; protected static final String[] columnNames = { "Book Name", "Status" }; } class MyComboBoxRenderer extends JComboBox implements TableCellRenderer { public MyComboBoxRenderer(String[] items) { super(items); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { System.out.println("in"); if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setSelectedItem(value); return this; } }
VIEWS ON THIS POST

139

Posted on:

Thursday 20th September 2012
View Replies!

make all components visble, when jframe size changed horizontally or vertically

Hi I have developed user interface in swing with two panels, lower panel and upper panel, both uses FormLayout and used BorderLayout to add these panels to JFrame. When the JFrame size is changed horizontally or vertically some components are not visible in JFrame going out. Please help how to minimize the size of all the components to make visble, when JFrame size is changed. Many
VIEWS ON THIS POST

205

Posted on:

Friday 21st September 2012
View Replies!

Problem in changing title of frame of outer class by inner class button

import java.awt.*; import java.awt.event.*; class setTittleTest extends Frame implements ActionListener // outer class { Button b; setTittleTest() // main frame { b = new Button("Main"); add(b); b.addActionListener(this); setSize(450,450); setTitle("Yes"); setVisible(true); } public void change() { setTitle("tittle changed"); } class newtitle extends Frame implements ActionListener // inner class { Button b1; newtitle() { setSize(300,120); setTitle("inner class Dialogue"); b1 = new Button("click"); add(b1); b1.addActionListener(this); setVisible(true); } public void actionPerformed(ActionEvent e1) { change(); // here can be a better approach then this } } // inner class end public void actionPerformed(ActionEvent e) { newtitle nt = new newtitle(); } public static void main (String[] args) { setTittleTest t = new setTittleTest(); } }
VIEWS ON THIS POST

143

Posted on:

Friday 21st September 2012
View Replies!

disappearing text on disabled buttons

Hi Guys, Until now I've not had an issue with JButtons on an interface retaining their text label, but since I've recently added a plugin app to my main applicaton it has had a strange effect on those buttons that are initially disabled on the main application. I've been trying to figure out what is different about this plugin application that is affecting the main application in this manner, but it eludes me. I'm hoping someone can just suggest setting some property on the buttons in question to ensure they always display their text label whether they're enabled or not. ow me to explain that the main application has a Language menu with three submenus (JMenuRadioButtons) that allow the user to select to a different language. They each call a method named changeMenus_Buttons(). Like so: public static Locale currentLocale = null; public static Languages currentLanguage = null; public static PNSResource messages = null; ... /**Language | English action performed*/ void jrbMenuLanguageEnglish_actionPerformed(ActionEvent e) { currentLocale = new Locale("en", "CA"); currentLanguage = Languages.en; messages = new PNSResource_en_CA(); changeMenus_Buttons(); jPanel1.revalidate(); jPanel1.repaint(); } /**Language | French action performed*/ void jrbMenuLanguageFrench_actionPerformed(ActionEvent e) { currentLocale = new Locale("fr", "CA"); currentLanguage = Languages.fr; messages = new PNSResource_fr_CA(); changeMenus_Buttons(); jPanel1.revalidate(); jPanel1.repaint(); } /**Language | Spanish action performed*/ void jrbMenuLanguageSpanish_actionPerformed(ActionEvent e) { currentLocale = new Locale("es", "ES"); currentLanguage = Languages.es; messages = new PNSResource_es_ES(); changeMenus_Buttons(); jPanel1.revalidate(); jPanel1.repaint(); }
VIEWS ON THIS POST

237

Posted on:

Friday 21st September 2012
View Replies!

Swing not Showing Windows like button and borders

These buttons are not like Windows 7 buttons. i m using JFrame. how can i make that type of buttons like gray buttons with gray hover etc(windows style).
VIEWS ON THIS POST

206

Posted on:

Friday 21st September 2012
View Replies!

Why do the sizes of my components change when I specify a look-and-feel?

Why do the sizes of my components/containers change when I specify a look-and-feel or change look-and-feel repeatedly,with different layouts or without layout
VIEWS ON THIS POST

107

Posted on:

Friday 21st September 2012
View Replies!

how to get colored line to differentiate text field array in swing

I have developed one frame on which I used GridBagLayout to arrange textfields of 12X12. i.e., total 144 textfields on frame. Now I want to differentiate these text fields with colored line after each 3 columns and three rows as shown in the following diagram. I shouldn't change the names of that text fields, because I interrelated those text fields using their names as jt[0][0], jt[0][1]......jt[6][2]........ and So on.I tried in many ways, but I couldn't find the solution. Please suggest. Below is the some part of my code.
VIEWS ON THIS POST

210

Posted on:

Friday 21st September 2012
View Replies!

Program color scheme controlled by a Colors class: object or enum?

I'm writing a rather large program with lots of classes and potentially lots of JFrames. Could I have one class devoted to establishing the primary selection of colors that will be repeated throughout the program That way, rather than remembering each color definition, I can just code something like Colors.TitleFont to represent the color of the title of each window, and Colors.InputPanelBg to represent the background of any input window. I have not found examples of this on-line, but it seems reasonable. Would a Colors object or an Enum work for this Here is my attempt, but Eclipse says "The constructor GSCOLORS(String) is undefined." import java.awt.Color; public enum GSCOLORS { InputPanelA("0xa29292"), InputPanelB("0x92a292"); private Color col; GSCOLORS(Color colorId) { col = colorId; } public Color getCol() { return col; } }
VIEWS ON THIS POST

115

Posted on:

Friday 21st September 2012
View Replies!

having problems with setting the color of a buffered Imaghe

I created a buffered image in my programme and I want it to have a green (orany color other than black)background however i have been unable to get it to change from black to any other other color.hers the code i have been working with .
VIEWS ON THIS POST

289

Posted on:

Friday 21st September 2012
View Replies!

Is it possible to create a compound button in swing?

compound button, or what ever you might call it, is it possible to create a button or group of buttons to look like this the said button should be able to act as individual buttons like, button_north, button_center, button_south, button_east and button_west. looking forward to possible hints on how to come up with the said component.
VIEWS ON THIS POST

197

Posted on:

Saturday 22nd September 2012
View Replies!

Synth change JComboBox Arrow size

I have a synth XML that I'm using to change the appearance but with the CombBox, I got the arrow to use my image but now it keeps stretching to the largest size. How can I make the arrow appear smaller
VIEWS ON THIS POST

229

Posted on:

Saturday 22nd September 2012
View Replies!

Reset slide button???

all, I have a simple image-editing program where slide button change the contrast and brightness in buffered image. I would like when press a button to get the original image and the slilde knob to be set in the initial values. Does anyone that can help me Here is the slider: JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { rescale = new RescaleOp(scaleFactor, offset, null); JSlider tempSlider = (JSlider) e.getSource(); scaleFactor = (float) (tempSlider.getValue() / 50.0); textFieldSc.setText(Float.toString(scaleFactor)); imageModified = rescale.filter(imageOriginal, null); image = imageModified; canvas.repaint(); } });
VIEWS ON THIS POST

129

Posted on:

Saturday 22nd September 2012
View Replies!

JTextArea size changes on pressing TAB key

When i enter data inside JTextArea, and press TAB key to move to next textfield/ or anything, it doesn't moves. Instead it changes the size of JTextArea each time i press TAB key. By using "setTabSize(0);" i can stop it from re-sizing the textarea, but how to move to the next textfield
VIEWS ON THIS POST

213

Posted on:

Saturday 22nd September 2012
View Replies!

Submitting info using a button

So i have 4 text fields that a user can input numbers into. I want to use the button associated with these text fields to submit the info from the fields to 4 variables outside of the method. Im having trouble setting up the method so that it sends back the user's input. public class SubmitButtonListener implements ActionListener { public void actionPerformed(ActionEvent ev) { ipSeriesOne = ipGroupOne.getText(); ipSeriesTwo = ipGroupTwo.getText(); ipSeriesThree = ipGroupThree.getText(); ipSeriesFour = ipGroupFour.getText(); System.out.println(ipGroupOne + "." + ipGroupTwo + "." + ipGroupThree + "." + ipGroupFour); return } }
VIEWS ON THIS POST

196

Posted on:

Saturday 22nd September 2012
View Replies!

Minimize and Maximize button in JDialog

I need to add minimize and maximize button in the titlebar of JDialog. Is there a way to do this
VIEWS ON THIS POST

139

Posted on:

Saturday 22nd September 2012
View Replies!

API to track clipboard changes ?

Is there any API which will notify me (Listener) whenever any changes occurs at system clipboard I already know a method (by using Timer) to track clipboard changes but I think if i check for clipboard's data at 100ms then lots of CPU (which has just single core) time will be wasted
VIEWS ON THIS POST

114

Posted on:

Saturday 22nd September 2012
View Replies!