Changing background color of Frame - java

I just started Java AWT programming.I can't change background color of my frame.!Here is my code..and below that error..Plz tell me why I'm facing this error and how to get rid of that..
Thanks in advance!
import java.awt.*;
import java.awt.event.*;
class F1 extends Frame
{
public void paint(Graphics g)
{
g.drawString("Hi",200,300);
}
public static void main(String args[])
{
F1 f = new F1();
f.setVisible(true);
f.setSize(1500,1500);
f.setBackground(Color.BLUE);
f.setTitle("First fRAME");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent x)
{
System.exit(0);
}
});
}
}

It works for me. Are you sure to have imported all required packages?
import java.awt.Color;
Try with this code, which is the simplest you can do to check if the problem is due to set background color or is due to something other:
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test
{
public static void main(String[] args)
{
Frame frame = new Frame("Title");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.addWindowListener(new WindowAdapter() {
#Override public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setBackground(Color.BLUE);
frame.setVisible(true);
}
}

Related

Java Swing KeyBinding with multiple key combination

I want to print to the console a message when both G key and A key are pressed. This should be a pretty easy task but for some reason i cannot achieve this, and cannot find any useful example online. I tried various syntaxes to describe the keystroke i wish to use, but none worked. This is my minimal code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
public class TestKeyBinding extends JFrame {
public static void main(String[] args) {
new TestKeyBinding();
}
public TestKeyBinding() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JLabel l = new JLabel();
l.getInputMap().put(KeyStroke.getKeyStroke("G A"), "ga");
l.getActionMap().put("ga", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("test ga");
}
});
l.setOpaque(true);
l.setBackground(Color.red);
frame.add(l);
frame.setVisible(true);
frame.pack();
}
});
}
}

Trying to use key listener but shape won't move

I have added a keylistener to try and get a shape to move right when I press the right arrow key. But it isn't working. I don't really know how to use keylistner that well. Can someone help me.
This is the code:
package walkingman;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class WalkingMan extends JPanel implements KeyListener{
int x = 0;
int y = 0;
#Override
public void paint(Graphics g){
super.paint(g);
g.fillOval(x, y, 150, 150);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame ("Walking Man");
frame.setSize(1080,720);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WalkingMan game = new WalkingMan();
frame.add(game);
while (true){
game.repaint();
game.keyPressed(e);
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
x++;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
There are a few issues with your code
You never add the KeyListener to the panel.
A KeyListener for a JPanel would only work if it is focusable & also focused.
Override paintComponent instead of paint.
Call setVisible at the end of the method.
Get rid of the whole while-loop, it'll only cause problems.
Use KeyBindings instead of KeyListeners.
Fixed code without key bindings:
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class WalkingMan extends JPanel implements KeyListener {
int x = 0;
int y = 0;
#Override
public void paintComponent(Graphics g) { // Overide paintComponent, not paint
super.paintComponent(g);
g.fillOval(x, y, 150, 150);
}
public WalkingMan() { // Class Constructor
setFocusable(true); // KeyListeners only work if the component is focusable
addKeyListener(this); // Add the KeyListener implemented by this class to the instance
}
public void createAndShowGUI() {
JFrame frame = new JFrame("Walking Man");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WalkingMan game = new WalkingMan();
frame.add(game);
frame.setSize(1080, 720);
frame.setVisible(true); // Call setVisible after adding the components
game.requestFocusInWindow(); // Request focus for the panel
}
public static void main(String[] args) throws InterruptedException {
new WalkingMan().createAndShowGUI();
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x++;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Set frame well before it is displayed And remove the while loop which is still running.
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame ("Walking Man");
frame.setSize(1080,720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WalkingMan game = new WalkingMan();
frame.add(game);
frame.setVisible(true);//Call visible method here
}
Why not restructure your code in a much clear way like this
import javax.swing.*;
import java.awt.*;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class WalkingMan extends JFrame{
EmilsKeyClass keyBoard = new EmilsKeyClass();
public WalkingMan (){
add(keyBoard,BorderLayout.CENTER);
keyBoard.addKeyListener(new KeyAdapter(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode()== KeyEvent.VK_ENTER){
x++;
repaint();
}
}
});
keyBoard.setFocusable(true);
}
public static void main(String [] args){
WalkingMan frame = new WalkingMan ();
frame.setTitle("Walking Man");
frame.setSize(1080,720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class EmilsKeyClass extends JPanel{
int x = 0;
int y = 0;
public EmilsKeyClass(){
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
super.paint(g);
g.fillOval(x, y, 150, 150);
//your code
}
}
}

Swing addWindowFocusListener

I have simple Java Swing application. I want before close main window get confirmation from user.
There is my code:
package client_interface;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MainWindow {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainWindow() {
initialize();
}
private void setFrameSize(JFrame frame) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
frame.setBounds(new Rectangle(width/4, height/4, width/2, height/2));
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
private void initialize() {
frame = new JFrame("Test");
setFrameSize(frame);
frame.addWindowFocusListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
}
}
But seems that frame.addWindowFocusListener doesn't work.
Please show me the correct way to add event windowClosing to my frame.
Replace
frame.addWindowFocusListener(new WindowAdapter() {
with
frame.addWindowListener(new WindowAdapter() {
The first takes a WindowFocusListener which will be called when the window either gains or loses focus.

KeyListener not working

public class KL implements KeyListener {
public static void main(String[] args) {
final JPopupMenu popup = new JPopupMenu();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getKeyChar());
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyChar());
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println(e.getKeyChar());
}
}
That's my class, it's probably something really stupid on my part, but my KeyListener here is not working. Nothing comes up on the console.
Let's start with the fact that you're not attached the listener to anything, then move on to the fact that you really should be using Key Bindings
And with example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTableEditing {
public static void main(String[] args) {
new TestTableEditing();
}
public TestTableEditing() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel key;
private int counter = 0;
public TestPane() {
key = new JLabel("...");
add(key);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "A.pressed");
am.put("A.pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("A was pressed");
key.setText("A was pressed " + (++counter));
}
});
}
}
}
I know this is an old post but I wanted to put this online so someone like myself can find it....
I worked on this problem for hours before figuring it out. Make sure that your Component has focus. For example I have all of my activity going on in a custom JPanel named SpaceShipPanel:
class SpaceShipPanel
{
//instance variables
//Now my constructor
SpaceShipPanel(){
//bla bla blah
setFocusable(true);//THIS LINE IS WHAT SAVED ME!!
}
}
From what I hear, keyBindings are the best route but the class I'm taking didn't cover this topic. Hopefully this will save someone hours of beating their heads against the wall.

Graphis2d drawString to generate german umlauts

I am trying to use Graphics2d to generate german unlauts and http://en.wikipedia.org/wiki/%C3%9F.
The output that I always see is two question marks. Any ideas about how to solve this?
Below is some code to print out the characters you want. My guess is that the font you are using may not have those characters if you are getting question marks. The font being reported when I run the example is LucidaGrande.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
public class DrawStringUmlaut extends JPanel {
public DrawStringUmlaut() {
setPreferredSize(new Dimension(getPreferredSize().width, 200));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("\u00f6", 10, 20);
g.drawString("\u00df", 40, 20);
g.drawString(g.getFont().getFontName(), 10, 40);
g.drawString(Integer.toString(g.getFont().getSize()) + " pt", 10, 60);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawStringUmlaut(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
});
}
}
If your system uses a font which can display these characters (ü and ß) , it should work out of the box.
Try the following example:
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Graphics2dUmlaut extends Frame {
public void paint(Graphics g) {
Graphics2D g1 = (Graphics2D) g;
g1.drawString("\u00fc\u00df", 100, 100);
}
public static void main(String args[]) {
Frame frame = new Graphics2dUmlaut();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
frame.setSize(200, 200);
frame.setVisible(true);
}
}

Categories