How to use a method from an already to Cotainer put JLabel? - java

I have to programm a Shikaku-Game and I have no the problem that I can not use one of the setLine-Methods from the ViewIcon-Class in the mouseReleased-Method of the class MyMouseAdapter.
Do you know a way how to use one of the methods?
Thanks and Cheers,
Me
Class MouseMain and Class MyMouseAdapter:
class MouseMain extends JFrame{
Container cont;
public MouseMain () {
super("Test");
cont = getContentPane();
p1 = new defaultPaterns(2);
p1.setLayout(new GridLayout(2, 2, 1, 1));
for (int i = 0; i < gameSize; i++) {
for (int j = 0; j < gameSize; j++) {
JLabel label = new JLabel(new ViewIcon());
label.setName (j + ";" + i);
label.addMouseListener(new MyMouseAdapter());
p1.add(label);
myLabels[j][i] = label;
}
}
cont.add(p1, BorderLayout.CENTER );
JPanel p2 = new JPanel();
cont.add(p2, BorderLayout.SOUTH);
setVisible(true);
}
public class MyMouseAdapter extends MouseAdapter {
public void mouseEntered(MouseEvent e) {
lastEntered = e.getComponent();
}
public void mousePressed(MouseEvent e) {
mousePressed = e.getComponent();
coordPressed = new Coordinate(mousePressed.getName());
System.out.println("mousePressed " + mousePressed.getName());
}
public void mouseReleased(MouseEvent e) {
mouseReleased = lastEntered;
coordReleased = new Coordinate(mouseReleased.getName());
System.out.println("mouseReleased " + mouseReleased.getName());
if (mouseReleased.getName().equals("0;0")) {
mouseReleased.setForeground(Color.RED);
mouseReleased.repaint();
}
}
}
Class ViewIcon:
class ViewIcon extends JLabel implements Icon {
Graphics2D g2;
int width;
int height;
public void paintIcon(Component c, Graphics g, int x, int y) {
g2 = (Graphics2D) g;
width = c.getWidth();
height = c.getHeight();
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0, 0, width, height);
}
public void setLeftLine() {
g2.setStroke (new BasicStroke (10));
g2.setColor(Color.RED);
g2.drawLine(0, 0, 0, height);
}
}

class ViewIcon extends JLabel implements Icon {
Don't extend JLabel. All your code is doing is implementing the Icon interface.
I can not use one of the setLine-Methods from the ViewIcon-Class
Custom painting should only be done in the paintIcon(...) method. You should NEVER invoke a painting method directly.
If you want to change the appearance of your painting then you need to set properties of the Icon. For example to paint the top line you rename and change your setTopLine(...) method to look something like:
public void setTopLinePainted(boolean topLinePainted)
{
this.topLinePainted = topLinePainted;
}
Then in the paintIcon(...) method you have code like:
g2.fillRect(0, 0, width, height);
if (topLinePainted)
{
g2.setStroke (new BasicStroke (10));
g2.setColor(Color.RED);
g2.drawLine(0, 0, width, 0);
}
Then in your mouseReleased(...) code you do something like:
JLabel label = (JLabel)lastEntered;
ViewIcon icon = (ViewIcon)label.getIcon();
icon.setTopLinePainted( true );
label.repaint();

Related

java- repaint() method is misbehaving?

I am working on a Music Player
I am using a JSlider as seek bar and using a JLabel to draw text on screen, such as song name.
I am new to Graphics2D
Here's the minimized code:
public class JSliderDemo extends JFrame
{
JLabel label;
JSlider seek = new JSlider();
int y = 10;
public JSliderDemo()
{
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
startThread();
}
public void createWindow()
{
JPanel panel = new JPanel(null);
panel.setOpaque(true);
panel.setBackground(Color.BLUE);
label = new Component();
label.setSize(400, 400);
label.setLocation(0, 0);
createSlider();
panel.add(seek);
panel.add(label);
add(panel);
}
protected void createSlider()
{
seek.setUI(new SeekBar(seek, 300, 10, new Dimension(20, 20), 5,
Color.DARK_GRAY, Color.RED, Color.RED));
seek.setOrientation(JProgressBar.HORIZONTAL);
seek.setOpaque(false);
seek.setLocation(10, 50);
seek.setSize(300, 20);
seek.setMajorTickSpacing(0);
seek.setMinorTickSpacing(0);
seek.setMinimum(0);
seek.setMaximum(1000);
}
protected void startThread()
{
Thread thread = new Thread(new Runnable(){
#Override
public void run()
{
try
{
while(true)
{
if(y == label.getHeight()){y = 1;}
label.repaint();
y += 1;
Thread.sleep(100);
}
}
catch(Exception ex){}
}
});
thread.start();
}
protected class Component extends JLabel
{
#Override
public void paintComponent(Graphics g)
{
Graphics2D gr = (Graphics2D) g;
gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gr.setColor(Color.RED);
gr.setFont(new Font("Calibri", Font.PLAIN, 16));
gr.drawString("Slider", 50, y);
}
}
public static void main(String[] args)
{
new JSliderDemo();
}
}
The Custom Slider UI class prints a line each time the JSlider is repainted.
Through this, I was able to find out that, when I call repaint() for JLabel it automatically repaints JSlider with it even though JSlider is not included in JLabel.
Output :
Slider re-painted
Slider re-painted
Slider re-painted
Slider re-painted
Slider re-painted
Slider re-painted.........
Now if I remove label.repaint() from the Thread, then the JSlider is not re-painted.
Output:
Slider re-painted
Slider re-painted
Is the repaint() method supposed to work like this?
Here's the Custom Slider UI class :
package jsliderdemo;
import java.awt.*;
import javax.swing.*;
import java.awt.geom.RoundRectangle2D;
import javax.swing.plaf.basic.BasicSliderUI;
public class SeekBar extends BasicSliderUI
{
private int TRACK_ARC = 5;
private int TRACK_WIDTH = 8;
private int TRACK_HEIGHT = 8;
private Color backGround = Color.GRAY;
private Color trackColor = Color.RED;
private Color thumbColor = Color.WHITE;
private Dimension THUMB_SIZE = new Dimension(20, 20);
private final RoundRectangle2D.Float trackShape = new RoundRectangle2D.Float();
public SeekBar(final JSlider b, int width, int height, Dimension thumbSize, int arc,
Color backGround, Color trackColor, Color thumbColor)
{
super(b);
this.TRACK_ARC = arc;
this.TRACK_WIDTH = width;
this.TRACK_HEIGHT = height;
this.THUMB_SIZE = thumbSize;
this.backGround = backGround;
this.trackColor = trackColor;
this.thumbColor = thumbColor;
}
#Override
protected void calculateTrackRect()
{
super.calculateTrackRect();
if (isHorizontal())
{
trackRect.y = trackRect.y + (trackRect.height - TRACK_HEIGHT) / 2;
trackRect.height = TRACK_HEIGHT;
}
else
{
trackRect.x = trackRect.x + (trackRect.width - TRACK_WIDTH) / 2;
trackRect.width = TRACK_WIDTH;
}
trackShape.setRoundRect(trackRect.x, trackRect.y, trackRect.width, trackRect.height, TRACK_ARC, TRACK_ARC);
}
#Override
protected void calculateThumbLocation()
{
super.calculateThumbLocation();
if (isHorizontal())
{
thumbRect.y = trackRect.y + (trackRect.height - thumbRect.height) / 2;
}
else
{
thumbRect.x = trackRect.x + (trackRect.width - thumbRect.width) / 2;
}
}
#Override
protected Dimension getThumbSize()
{
return THUMB_SIZE;
}
private boolean isHorizontal()
{
return slider.getOrientation() == JSlider.HORIZONTAL;
}
#Override
public void paint(final Graphics g, final JComponent c)
{
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g, c);
}
#Override
public void paintTrack(final Graphics g)
{
System.out.println("Slider re-painted");
Graphics2D g2 = (Graphics2D) g;
Shape clip = g2.getClip();
boolean horizontal = isHorizontal();
boolean inverted = slider.getInverted();
// Paint shadow.
//g2.setColor(new Color(170, 170 ,170));
//g2.fill(trackShape);
// Paint track background.
g2.setColor(backGround);
g2.setClip(trackShape);
trackShape.y += 1;
g2.fill(trackShape);
trackShape.y = trackRect.y;
g2.setClip(clip);
// Paint selected track.
if (horizontal)
{
boolean ltr = slider.getComponentOrientation().isLeftToRight();
if (ltr) inverted = !inverted;
int thumbPos = thumbRect.x + thumbRect.width / 2;
if (inverted)
{
g2.clipRect(0, 0, thumbPos, slider.getHeight());
}
else
{
g2.clipRect(thumbPos, 0, slider.getWidth() - thumbPos, slider.getHeight());
}
}
else
{
int thumbPos = thumbRect.y + thumbRect.height / 2;
if (inverted)
{
g2.clipRect(0, 0, slider.getHeight(), thumbPos);
}
else
{
g2.clipRect(0, thumbPos, slider.getWidth(), slider.getHeight() - thumbPos);
}
}
g2.setColor(trackColor);
g2.fill(trackShape);
g2.setClip(clip);
}
#Override
public void paintThumb(final Graphics g)
{
g.setColor(thumbColor);
g.fillOval(thumbRect.x, thumbRect.y, thumbRect.width, thumbRect.height);
}
#Override
public void paintFocus(final Graphics g) {}
}

How to make a JPanel reset?

I have a simple game of pong where when the user clicks a JButton which is displayed on the JPanel it should reset the game. How can I do this? I was thinking just remove the JPanel and add a new one (the JPanel contains all of the necessary code/class references for the game) I tried writing this however, and it didn't work, nothing happens. Here is my code:
JFrame Class:
public class Window extends JFrame implements ActionListener {
static int length = 1000;
static int height = 1000;
Display display = new Display();
Window() {
setTitle("Program Display");
setSize(length + 22, height + 40);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton restart = new JButton("Start New Game");
add(display);
display.add(restart);
restart.addActionListener(this);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
remove(display);
Display display2 = new Display();
JButton restart = new JButton("Start New Game");
add(display2);
display2.add(restart);
restart.addActionListener(this);
revalidate();
repaint();
}
}
JPanel Class:
public class Display extends JPanel implements ActionListener {
int up = 0;
int down = 500;
double ballx = 500;
double bally = 500;
char ballDirection;
Rectangle border;
static Rectangle borderEast;
static Rectangle borderNorth;
static Rectangle borderSouth;
static Rectangle borderWest;
static boolean gameOver;
Timer timer;
Paddle p;
Ball b;
Display() {
p = new Paddle();
b = new Ball();
up = p.up;
down = p.down;
ballx = b.ballx;
bally = b.bally;
ballDirection = b.ballDirection;
initTimer();
b.startBall();
addKeyListener(p);
setFocusable(true);
}
public void initTimer() {
timer = new Timer(10, this);
timer.start();
}
public void setUpBorders(Graphics2D g2d) {
border = new Rectangle(0, 0, Window.length, Window.height);
borderEast = new Rectangle(Window.length, 0, 2, Window.height);
borderWest = new Rectangle(0, 0, 2, Window.height);
borderSouth = new Rectangle(0, Window.height, Window.length, 2);
borderNorth = new Rectangle(0, 0, Window.length, 2);
g2d.setColor(Color.RED);
g2d.draw(border);
}
public void paintPaddle(Graphics2D g2d) {
g2d.setColor(new Color(0, 130, 130));
g2d.fill(p.paddle);
}
public void paintBall(Graphics2D g2d) {
g2d.setColor(new Color(0, 130, 130));
g2d.fillOval((int) ballx, (int) bally, 20, 20);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D) g;
setUpBorders(g2d);
paintPaddle(g2d);
paintBall(g2d);
if(gameOver == true) {
Font custom = new Font("Dialog", Font.BOLD, 60);
g2d.setColor(Color.RED);
g2d.setFont(custom);
g2d.drawString("Game Over. Your score was: " + Ball.score + "!", 50, 500);
}
}
public void checkBorderHit() {
b.checkBorderHit();
p.checkBorderHit();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
up = p.up;
down = p.down;
ballx = b.ballx;
bally = b.bally;
ballDirection = b.ballDirection;
b.moveBall();
checkBorderHit();
repaint();
}
}
You didn't say what exactly doesn't work, but you forgot to call revalidate() and repaint() after adding display2. If your problem was that after pressing the button nothing happens, this will probably solve it.
Edit:
We still can't run you code, because the Ball and Paddle class are missing (my mistake for not mentioning that), but try to set important variables like gameOver false when first "mentioning them" (I don't know the proper term, just do static boolean gameOver = false; instead of static boolean gameOver;). Do this in all other classes also. Sorry for not saying which variables you exactly must change, but I'm not saying anything I'm not 100% sure about without being able to test it :P (maybe a more experienced person can help you more)

When i add code to paintComponent() my gui disappears

In my code after i added code to paintComponent() when i run it, all the JLabel, textfields, and buttons disappear the textfields and buttons reappear when i click on them while the program is running but i still can't see any of the JLabels.
I hope it is something silly i have commented out the code in the paintComponent() method that seems to cause this error.
public class snowBoarding extends JFrame {
private JButton getReset() {
if (Reset == null) {
Reset = new JButton();
Reset.setBounds(new Rectangle(162, 411, 131, 39));
Reset.setFont(new Font("Dialog", Font.BOLD, 18));
Reset.setText("Reset");
Reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e){
textField_1.setText("0");
textField_2.setText("0");
textField_3.setText("0");
textField_4.setText("0");
textField_5.setText("0");
textField_6.setText("0");
textField_7.setText("0");
textField_8.setText("0");
textField_9.setText("0");
textField_10.setText("0");
textField_11.setText("0");
textField.setText("0");
total_1.setText("0");
total_2.setText("0");
Overall.setText("0");
DrawPanel.clear(DrawPanel.getGraphics());
DrawPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
}
});
}
return Reset;
}
public JButton getButton_calc_draw() {
if (Button_calc_draw == null) {
Button_calc_draw = new JButton();
Button_calc_draw.setBounds(303, 411, 131, 39);
Button_calc_draw.setFont(new Font ("Dialog", Font.BOLD, 18));
Button_calc_draw.setText("Draw");
Button_calc_draw.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
// Get values from the text fields
run_1[0] = Integer.parseInt(textField.getText());
run_1[1] = Integer.parseInt(textField_1.getText());
run_1[2] = Integer.parseInt(textField_2.getText());
run_1[3] = Integer.parseInt(textField_3.getText());
run_1[4] = Integer.parseInt(textField_4.getText());
run_1[5] = Integer.parseInt(textField_5.getText());
for (int i = 0; i < run_1.length; i++) {
temp[i] = run_1[i];
}
Arrays.sort(temp);
for (int i = 1; i < (temp.length -1) ; i++){
avg1+=temp[i];
}
avg1 = avg1/4;
run_2[0] = Integer.parseInt(textField_6.getText());
run_2[1] = Integer.parseInt(textField_7.getText());
run_2[2] = Integer.parseInt(textField_8.getText());
run_2[3] = Integer.parseInt(textField_9.getText());
run_2[4] = Integer.parseInt(textField_10.getText());
run_2[5] = Integer.parseInt(textField_11.getText());
for (int i = 0; i < run_2.length; i++) {
temp[i] = run_2[i];
}
Arrays.sort(temp);
for (int i = 1; i < (temp.length -1) ; i++){
avg2+=temp[i];
}
avg2 = avg2/4;
if (avg1 > avg2){
OverallScore = avg1;
}
else {
OverallScore = avg2;
}
total_1.setText(Integer.toString(avg1));
total_2.setText(Integer.toString(avg2));
Overall.setText(Integer.toString(OverallScore));
DrawPanel.repaint();
}
// Transfer the image from the BufferedImage to the JPanel to make it visible.
;
});
}
return Button_calc_draw;
}
}
});
}
return Reset;
}
private myJPanel getDrawPanel() {
if (DrawPanel == null) {
DrawPanel = new myJPanel();
DrawPanel.setLayout(new GridBagLayout());
DrawPanel.setBounds(new Rectangle(258, 39, 326, 361));
DrawPanel.setBackground(Color.white);
DrawPanel.setEnabled(true);
DrawPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
//Instantiate the BufferedImage object and give it the same width
// and height as that of the drawing area JPanel
img = new BufferedImage(DrawPanel.getWidth(),
DrawPanel.getHeight(),
BufferedImage.TYPE_INT_RGB);
//Get its graphics context. A graphics context of a particular object allows us to draw on it.
g2dImg = (Graphics2D)img.getGraphics();
//Draw a filled white coloured rectangle on the entire area to clear it.
g2dImg.setPaint(Color.WHITE);
g2dImg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
}
return DrawPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
snowBoarding thisClass = new snowBoarding();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
public snowBoarding() {
super();
setResizable(false);
getContentPane().setLayout(null);
initialize();
}
private void initialize() {
this.setSize(600, 500);
this.setContentPane(getJContentPane());
this.setTitle("Snowboarding Score Calculator");
this.setResizable(false);
this.setVisible(true);
}
}
class myJPanel extends JPanel {
BufferedImage img;
Graphics2D g2dImg;
private static final long serialVersionUID = 1L;
private Rectangle2D.Double rectangle;
public void paintComponent(Graphics g) {
//Must be called to draw the JPanel control.
// As a side effect, it also clears it.
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
rectangle = new Rectangle2D.Double(0, 260-score[0] * 2, 25, score[0] * 2);
g2D.setPaint(Color.blue);
g2D.fill(rectangle);
g2D.draw(rectangle);
}
protected void clear(Graphics g) {
super.paintComponent(g);
// Also clear the BufferedImage object by drawing a white coloured filled rectangle all over.
g2dImg.setPaint(Color.WHITE);
g2dImg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
}
}
edit: removing unnecessary code
i need the repaint to draw rectangles using the run_1 and the run_2 array as the x or y values after i click draw and the reset to return the painted image back to a white slate.
draw button --> draws the graph
reset button --> removes the graph so that a new graph can be created.
You shall not use g2dImg in paintComponent(), but g instead (the parameter received by method paintComponent()). More precisely, ((Grpahics2D)g) instead of g2dImg.
g2dImg doesn't seem to be initialized in your code posted here, maybe you have done it somewhere...
More generally, you shall always use the Graphics instance you received in paint methods (casting it to Graphics2D if needed). You shall not try to reuse/share/store instances of Graphics.
The same applies for the clear() method.
Here is an example of how to rewrite this paintComponent() method:
private boolean shallPaint = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (shallPaint) {
Graphics2D g2D = (Graphics2D) g;
rectangle = new Rectangle2D.Double(0, 260-score1 * 2, 25, score1 * 2);
g2D.setPaint(Color.blue);
g2D.fill(rectangle);
g2D.draw(rectangle);
}
}
public void setShallPaint(boolean pShallPaint) {
shallPaint = pShallPaint;
}
Then simply call myJPanel.repaint() to repaint it.
You shall replace, in your reset button:
DrawPanel.clear(DrawPanel.getGraphics());
with:
DrawPanel.setShallPaint(false);
DrawPanel.repaint();
And in Button_calc_draw:
DrawPanel.setShallPaint(true);
DrawPanel.repaint();

Change background and font color of jpanel on button click

I want to change Background color of Jpanel and its font on button click.
Can anyone tell me what i am doing wrong?
Can I set JPanel background transparent?if yes How?
On button click test4.action method is called where i need to change Jpanel background color?
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("Hello 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("Hello 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;
}
}
Can I set JPanel background transparent?if yes How?
Yes, just call setOpaque(false); on that JPanel. On the contrary, if you want the background to be painted, call setOpaque(true); on that panel.
Additional remarks:
public boolean action(Event e, Object arg) is Deprecated. Add the appropriate listeners instead.
Follow Java coding conventions and use an Uppercase letter for the first character of a class
You should almost never call getGraphics(); on a Component
Don't override public void paint(Graphics g) but protected void paintComponent(Graphics g). Don't forget to call super.paintComponent if you want the background to be painted
Why do you override reshape?
Why do you create an internal buffer? Swing already has built-in double buffering and they do a much better job.
If you overrode already paint() why do you also override update()? You are performing the same job twice.
Remove that gr class variable, it does not make any sense. When you use Graphics object, use the one provided as a parameter of the paintComponent method but don't keep a reference to it, as it will be disposed later.
counter does not need to be static. Try to avoid static as much as possible.
Try to avoid so much coupling between your classes. It makes your code harder to maintain and less predictable.
Next time, post an SSCCE with something else than an Applet (a JFrame, for example) unless the problem you are having really requires an Applet to be reproduced.

How to "paint" on JLabels on a JPanel?

I have a set of JLabels, each containing a letter (via seText()), opaque and background set to white, on a JPanel with a GridLayout so the labels are forming a table.
I am doing a simple animation of highlighting certain rows and columns then there intersection. I can use the setBackground() of labels for this purpose, but thought I'd have more "choices" if a was able to use a Graphics object (maybe drawing a circle around intersection, then clearing it).
I tried to extend JLabel, or drawing on the JPanel directly(using getGraphics() in a method) but it didn't work, I think the drawing is behind the labels in this case. I can't figure out where should the "painting" code be placed in either case, nothing appeared on the screen.
in short, a method like the following, can be used to draw on top of labels?
should it be a JLabel or a JPanel method?
public void drawsomething() {
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.fillRect(100, 100, 100, 100);
}
What if you override paintChildren() ?
protected void paintChildren(Graphics g) {
super.paintChildren(g);
//paint your lines here
}
You might want to try a JLayeredPane to paint your specific drawings on top of the existing JComponents
see example here http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html
I really don't know much about drawing stuff yet, but just created one small sample code for you to look at, hopefully you can get some information out of it. In order to paint on the JLabel you can use it's paintComponent(Graphics g) method.
A Sample Code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingOnJLabel extends JFrame
{
private CustomLabel label;
private int flag = 1;
private JPanel contentPane;
public DrawingOnJLabel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
label = new CustomLabel(200, 200);
label.setLabelText("A");
label.setValues(50, 50, 100, 100, 240, 60);
final JButton button = new JButton("CLEAR");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (flag == 1)
{
label.setFlag(flag);
flag = 0;
button.setText("REPAINT");
contentPane.revalidate();
contentPane.repaint();
}
else if (flag == 0)
{
label.setFlag(flag);
flag = 1;
button.setText("CLEAR");
contentPane.revalidate();
contentPane.repaint();
}
}
});
}
});
contentPane.add(label);
add(contentPane, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DrawingOnJLabel();
}
});
}
}
class CustomLabel extends JLabel
{
private int sizeX;
private int sizeY;
private int x, y, width, height, startAngle, arcAngle;
private int flag = 0;
private String text;
public CustomLabel(int sX, int sY)
{
sizeX = sX;
sizeY = sY;
}
// Simply call this or any set method to paint on JLabel.
public void setValues(int x, int y, int width, int height, int startAngle, int arcAngle)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.startAngle = startAngle;
this.arcAngle = arcAngle;
repaint();
}
public void setFlag(int value)
{
flag = value;
repaint();
}
public Dimension getPreferredSize()
{
return (new Dimension(sizeX, sizeY));
}
public void setLabelText(String text)
{
super.setText(text);
this.text = text;
flag = 0;
repaint();
}
public void paintComponent(Graphics g)
{
if (flag == 0)
{
g.setColor(Color.RED);
g.drawString(text, 20, 20);
g.setColor(Color.BLUE);
g.drawOval(x, y, width, height);
g.fillOval(x + 20, y + 20, 15, 15);
g.fillOval(x + 65, y + 20, 15, 15);
g.fillRect(x + 40, y + 40, 5, 20);
g.drawArc(x + 20, y + 30, 55, 55, startAngle, arcAngle);
}
else if (flag == 1)
{
g.clearRect(x, y, width, height);
}
}
}
Use paintComponent(Graphics g) instead of paint(Graphics g). That will paint over the GUI

Categories