Blink boxes in sequence - java

I changed a program (see below) I nabbed and have managed to get it to do some of what I want. I need a number of rows/bands/stripes of 3 to blink in sequence. If you could imagine three sets of three vertical bars/bands and each bar numbered 1-3. I want to get each band/bar numbered 1 of each group to blink. So all bands numbered 1 blinks for a finite time, then bands numbered 2, then 3 then repeat. So when looking at it it looks like vertical stripes blinking 1,2,3,1,2,3 etc.
What's set out below and what I have described as boxes below refers to the bands I am talking about
class BelishN {
private Timer timer;
public class Drawing extends JPanel {
private int x = 125;// Not required - it was for the ball!
private int y = 80;
private boolean changeColors = false;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(1, 1, 10, 770);
//Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(10, 1, 10, 770);
//Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(20, 1, 10, 770);
// Rectangle box6 = new Rectangle(165, 405, 20, 45);
//drawing the shapes
//Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
//g2.draw(ball);
g2.draw(box1);
//g2.draw(box2);
//g2.draw(box3);
//g2.draw(box4);
//g2.draw(box5);
//g2.draw(box6);
//coloring the shapes
g2.setColor(Color.BLACK);
g2.fill(box1);
g2.fill(box3);
g2.fill(box5);
g2.setColor(Color.ORANGE);
//g2.fill(ball);
changeColors = !changeColors;
if (changeColors) {
g2.setColor(Color.white);
//g2.fill(new Ellipse2D.Double(x, y, 100, 100));
g2.fill(box1 = new Rectangle(1, 1, 10, 770));//3 vertical bands are flashing together
g2.fill(box3 = new Rectangle(10, 1, 10, 770));
g2.fill(box5 = new Rectangle(20, 1, 10, 770));
}
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishN() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(800, 770); //Screen size
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
shapes.repaint();
}
});
JButton jbtFlash = new JButton("Flash");
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
//Positioning
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
controlPanel.add(jbtFlash);
controlPanel.add(jbtSteady);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.add(shapes);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// in last line here, start the timer:
timer.start();
}
public static void main(String[] args) {
new BelishN();
}
}

Related

Why cant I draw a rectangle with fillPolygon()

I am learning Java graphics. I am trying to draw simple figures. However I noticed that the following code won't draw properly:
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xpoints = new int[] { 20, 50, 80 };
int[] ypoints = new int[] { 40, 10, 40 };
g.fillPolygon(xpoints, ypoints, 3);
int[] recXp = new int[] { 20, 80, 20, 80 };
int[] recYp = new int[] { 50, 60, 50, 60 };
g.fillPolygon(recXp, recYp, 4);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw panel = new Draw();
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
}
}
In order to achieve what I want I have to use
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xpoints = new int[] { 20, 50, 80 };
int[] ypoints = new int[] { 40, 10, 40 };
g.fillPolygon(xpoints, ypoints, 3);
g.fillRect(20, 50, 60, 10);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw panel = new Draw();
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
}
}
Why is this happening? Am I missing something? Sorry if this is a trivial question, I am just trying to understand Java better.
int[] recXp = new int[] { 20, 80, 20, 80 };
int[] recYp = new int[] { 50, 60, 50, 60 };
You only have two sets of points.
You need 4 different sets of point. One for each corner of the Rectangle.
Something like:
top/left (20, 50)
top/right (x is different from above, y is the same)
bottom/right (x is same as above, y is different.
bottom/left (x is same as first, y is save as above)

Add a button over image

How can I add a button over an image created with JLabel?
Even if I put the same coordinates on ".setbounds" the image usually gets behind the buttons.
public class Tatica extends JFrame {
JPanel jl = new JPanel();
JLabel jp = new JLabel();
public Tatica(){
jl.setLayout(null);
jp.setIcon(new ImageIcon("C:\\Users\\LG\\workspace\\Teste\\src\\snippet\\asdiuashd.Jpg"));
jl.add(jp);
add(jl);
jp.setBounds(100, 0, 1000, 1000);
validate();
JButton team2 = new JButton("Gk");
jl.add(team2);
team2.setBounds(400, 0, 100, 20);
team2.setVisible(true);
team2.setLayout(null);
JButton dc = new JButton("Dc");
jl.add(dc);
dc.setBounds(300, 200, 100, 20);
dc.setVisible(true);
JButton dc2 = new JButton("Dc");
jl.add(dc2);
dc2.setBounds(500, 200, 100, 20);
dc2.setVisible(true);
JButton dl = new JButton("Dl");
jl.add(dl);
dl.setBounds(100, 200, 100, 20);
dl.setVisible(true);
JButton dr = new JButton("Dr");
jl.add(dr);
dr.setBounds(700, 200, 100, 20);
dr.setVisible(true);
}
}
I'd instead slice up the image and use the sub-images as icons for either buttons or labels. Then arrange them all in a GridBagLayout.
Here is an example of what I mean (special thanks to #camickr for solving the bug in my layout code!):
(It uses a an icon with a transparent shade of white for mouse hover, black for pressed. The mouse was pointing at the left center forward when the screen shot was taken. It is left as an exercise for the reader to implement the logic needed to alternate between labels and buttons as required, in the GUI formed from 81 sub images.)
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import javax.imageio.ImageIO;
public class SoccerField {
private JPanel ui = null;
int[] x = {0, 35, 70, 107, 142, 177, 212, 247, 282, 315};
int[] y = {0, 45, 85, 140, 180, 225, 265, 280, 320, 345};
Color brighter = new Color(255,255,255,92);
Color darker = new Color(0,0,0,92);
SoccerField() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridBagLayout());
ui.setBackground(Color.RED);
try {
URL url = new URL("http://i.stack.imgur.com/9E5ky.jpg");
BufferedImage img = ImageIO.read(url);
BufferedImage field = img.getSubimage(100, 350, 315, 345);
BufferedImage[] bi = subSampleImageColumns(field);
BufferedImage[][] fieldParts = new BufferedImage[bi.length][];
for (int ii=0; ii<bi.length; ii++) {
fieldParts[ii] = subSampleImageRows(bi[ii]);
}
for (int ii=0; ii<fieldParts[0].length; ii++) {
for (int jj=0; jj<fieldParts.length; jj++) {
addImageToPanel(ui, fieldParts[ii][jj], ii, jj);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void addImageToPanel(
JPanel panel, BufferedImage img, int row, int col) {
Insets insets = new Insets(0,0,0,0);
double weighty = img.getHeight()==40 ? .5 : .1;
GridBagConstraints gbc = new GridBagConstraints(
row, col,
1, 1,
.5, weighty,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
insets, 0, 0);
ImageIcon ii = new ImageIcon(img);
JButton b = new JButton(ii);
b.setRolloverIcon(new ImageIcon(getFadeImage(img, brighter)));
b.setPressedIcon(new ImageIcon(getFadeImage(img, darker)));
b.setBorder(null);
b.setBorder(new EmptyBorder(0, 0, 0, 0));
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setFocusPainted(false);
panel.add(b, gbc);
}
private BufferedImage[] subSampleImageColumns(BufferedImage img) {
BufferedImage[] imageRows = new BufferedImage[x.length - 1];
for (int ii = 0; ii < x.length - 1; ii++) {
BufferedImage bi = img.getSubimage(
x[ii], 0, x[ii + 1] - x[ii], img.getHeight());
imageRows[ii] = bi;
}
return imageRows;
}
private BufferedImage[] subSampleImageRows(BufferedImage img) {
BufferedImage[] imageRows = new BufferedImage[y.length - 1];
for (int ii = 0; ii < y.length - 1; ii++) {
BufferedImage bi = img.getSubimage(
0, y[ii], img.getWidth(), y[ii + 1] - y[ii]);
imageRows[ii] = bi;
}
return imageRows;
}
private BufferedImage getFadeImage(BufferedImage img, Color clr) {
BufferedImage bi = new BufferedImage(
img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(img, 0, 0, ui);
g.setColor(clr);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.dispose();
return bi;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
SoccerField o = new SoccerField();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
How can I add a button over an image created with JLabel?
Add the buttons to the label, not the panel.
So the basic code is:
JPanel panel = new JPanel();
JLabel label = new JLabel( new ImageIcon(...) );
label.setLayout( new FlowLayout() );
JButton button1 = new JButton("Button1");
label.add(button1);
JButton button2 = new JButton("Button1");
label.add(button2);
So now the label will be the size of the image. The buttons will be displayed in a FlowLayout on the image. It is your responsibility to make sure the buttons fit on the image or the buttons will not be displayed properly.
The question is do you really need to add the label to the panel or should you just add the label to the frame?

Resizing Graphics2D Objects with JFrame Resize

I am making a GUI that has Graphics2D objects drawn on a JPanel within a JFrame. When I resize the window the Graphics2D objects reduce into a tiny rectangle. How can I set the drawing to resize with the JFrame when the user resizes the window?
I have tried using gridlayout, flowlayout, borderlayout, and settled on gridbaglayout. This helps with the resizing of btnPanel and the JButton but not for the Graphics2D objects.
Here is my self contained example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DrawPanelMain extends JPanel {
/*
* Variables used to set the value of preferred height and width
*/
public static final double version = 0.0;
JPanel btnPanel = new JPanel();
JPanel switchPanel = new JPanel();
DrawEllipses drawEllipses = new DrawEllipses(POINT_LIST);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initializePointList();
createAndShowGui();
}
});
}
public static java.util.List<Point> POINT_LIST = new ArrayList<>();
/*
* This loop will initialize POINT_LIST with the set of points for drawing the ellipses.
* The for each loop initializes points for the top row and the second for loop draws the
* right triangle.
*/
public static void initializePointList() {
int ellipsePointsYCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620};
int ellipsePointsXCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620, 680};
int xx = 80;
for (int aXt : ellipsePointsXCoordinate) {
POINT_LIST.add(new Point(aXt, xx));
}
for (int i = 0; i < ellipsePointsYCoordinate.length; i++) {
for (int j = i; j < ellipsePointsYCoordinate.length; j++) {
POINT_LIST.add(new Point(ellipsePointsXCoordinate[i], ellipsePointsYCoordinate[j]));
}
}
}
public DrawPanelMain() {
switchPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
switchPanel.setBackground(Color.DARK_GRAY);
switchPanel.add(drawEllipses);
switchPanel.revalidate();
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// first column
c.gridx = 0;
add(switchPanel, c);
// second column
c.gridx = 1;
add(switchPanel, c);
// first row
c.gridy = 0;
// second row
c. gridy = 1;
add(btnPanel, c);
btnPanel.add(new JButton(new AddSwitchAction("Add Switch Panel")));
}
public static void createAndShowGui() {
JFrame frame = new JFrame("RF Connection Panel " + version);
frame.setLayout(new BorderLayout());
frame.add(new DrawPanelMain());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(false);
//frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
/*
* AddSwitchAction will add a new pane to the tabbedPane when the add switch button is clicked
*/
private class AddSwitchAction extends AbstractAction {
public AddSwitchAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String title = "Switch ";
DrawEllipses tabComponent = new DrawEllipses(POINT_LIST);
switchPanel.add(title, tabComponent);
}
}
}
#SuppressWarnings("serial")
class DrawEllipses extends JPanel {
private final int PREF_W = 750; //Window width
private final int PREF_H = 750; //Window height
private final int OVAL_WIDTH = 30;
private static final Color INACTIVE_COLOR = Color.RED;
private static final Color ACTIVE_COLOR = Color.green;
private java.util.List<Point> points;
private java.util.List<Ellipse2D> ellipses = new ArrayList<>();
private Map<Ellipse2D, Color> ellipseColorMap = new HashMap<>();
/*
* This method is used to populate "ellipses" with the initialized ellipse2D dimensions
*/
public DrawEllipses(java.util.List<Point> points) {
this.points = points;
for (Point p : points) {
int x = p.x - OVAL_WIDTH / 2;
int y = p.y - OVAL_WIDTH / 2;
int w = OVAL_WIDTH;
int h = OVAL_WIDTH;
Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
ellipses.add(ellipse);
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
MyMouseAdapter mListener = new MyMouseAdapter();
addMouseListener(mListener);
addMouseMotionListener(mListener);
}
/*
* paintComponent is used to paint the ellipses
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ellipse2D ellipse : ellipses) {
g2.setColor(ellipseColorMap.get(ellipse));
g2.fill(ellipse);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.draw(ellipse);
}
/*
* Set the font characteristics, color, and draw the row labels.
*/
g.setFont(new Font("TimesRoman", Font.BOLD, 18));
g.setColor(Color.BLACK);
//Along the top row
g.drawString("External Port", 10, 50);
g.drawString("1", 135, 50);
g.drawString("2", 195, 50);
g.drawString("3", 255, 50);
g.drawString("4", 315, 50);
g.drawString("5", 375, 50);
g.drawString("6", 435, 50);
g.drawString("7", 495, 50);
g.drawString("8", 555, 50);
g.drawString("9", 615, 50);
g.drawString("10", 672, 50);
//Along the Y-axis
g.drawString("Radio 2", 40, 145);
g.drawString("3", 90, 205);
g.drawString("4", 90, 265);
g.drawString("5", 90, 325);
g.drawString("6", 90, 385);
g.drawString("7", 90, 445);
g.drawString("8", 90, 505);
g.drawString("9", 90, 565);
g.drawString("10", 90, 625);
//Along the X-Axis
g.drawString("1", 135, 670);
g.drawString("2", 195, 670);
g.drawString("3", 255, 670);
g.drawString("4", 315, 670);
g.drawString("5", 375, 670);
g.drawString("6", 435, 670);
g.drawString("7", 495, 670);
g.drawString("8", 555, 670);
g.drawString("9", 615, 670);
//Draws a 3DRect around the top row of ellipse2D objects
g2.setColor(Color.lightGray);
g2.draw3DRect(120, 60, 580, 40, true);
g2.draw3DRect(121, 61, 578, 38, true);
g2.draw3DRect(122, 62, 576, 36, true);
}
/*
* MouseAdapter is extended for mousePressed Event that detects if the x, y coordinates
* of a drawn ellipse are clicked. If the color is INACTIVE it is changed to ACTIVE and
* vice versa.
*/
private class MyMouseAdapter extends MouseAdapter {
#Override
/*
* When mousePressed event occurs, the color is toggled between ACTIVE and INACTIVE
*/
public void mousePressed(MouseEvent e) {
Color c;
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(e.getPoint())) {
c = (ellipseColorMap.get(ellipse) == INACTIVE_COLOR) ? ACTIVE_COLOR : INACTIVE_COLOR;
ellipseColorMap.put(ellipse, c);
}
}
repaint();
}
}
/*
* This method will set the dimensions of the JFrame equal to the preferred H x W
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
/*
* Used for button click action to change all ellipses to ACTIVE_COLOR
*/
public void activateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, ACTIVE_COLOR);
}
repaint();
}
/*
* Used for button click action to change all ellipses to INACTIVE_COLOR
*/
public void deactivateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
repaint();
}
}
This method will set the dimensions of the JFrame equal to the preferred H x W
No it set the preferred size of the panel. The size of the frame will be the preferred size of all the components added to it plus the frame decorations (title bar, borders).
When I resize the window the Graphics2D objects reduce into a tiny rectangle.
The GridBagLayout respects the preferred size of the component. When there is not enough space to display the component it will shrink to its "minimum size".
You probably need to override the getMinimumSize() method to equal the preferred size. Then in this case the component should just be truncated if space is not available.
If you want you actually painting to shrink then you need to build the logic into your painting code so that the painting is done relative to the space available on the panel.
Try adding your 2D object to a JLabel as BufferedImage of ImageIcon. You can do this by:
JLabel label2 = new JLabel(new ImageIcon(//Location of your Image);
Or I think you can also add Graphics2D objects directly creating them inside label bu I'm not sure about that

JTabbedPanel and Paint

I have small issue. In main i have such thing:
JTabbedPane tabsPane = new JTabbedPane();
add(tabsPane,BorderLayout.CENTER);
JPanel tab1Panel = new JPanel();
JPanel tab2Panel = new JPanel();
//DrawingWindow drawingWindow= new DrawingWindow();
//add(drawingWindow);
tabsPane.addTab("Animacja", tab1Panel);
tabsPane.addTab("Wykresy", tab2Panel);
JButton test = new JButton("Press");
tab2Panel.add(test);
Drawing Window class
public class DrawingWindow extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public static Balls balls=new Balls();
public DrawingWindow() {
MakeBall();
}
private void MakeBall()
{
balls=new Balls(10,205,5,10);
}
public void paint(Graphics gg){
super.paint(gg);
Graphics2D g = (Graphics2D) gg;
g.setColor(Color.GRAY);
g.fillRect(0,70,515,410);
g.setColor(Color.WHITE);
g.drawLine(10, 285, 57, 265);
g.drawLine(10, 285, 57, 305);
g.drawLine(515, 285, 458, 265);
g.drawLine(515, 285, 458, 305);
for(int ii=0;ii<Parameters.numberOfCovers;ii++)
{
if(Parameters.whatCovers[ii]==0)
{
g.setColor(Color.YELLOW);
g.fillRect(132+(57*2*ii), 205, 29+2*Parameters.cmCovers[ii], 150 );
}
if(Parameters.whatCovers[ii]==1)
{
g.setColor(Color.GREEN);
g.fillRect(132+(57*2*ii), 205, 29+2*Parameters.cmCovers[ii], 150 );
}
// Ellipse2D.Double shape = new Ellipse2D.Double(balls.getX(), balls.getY(), balls.getVelocity(),balls.getRadius());
// g.fill(shape);
repaint();
}
}
public void funkcja()
{
repaint();
}
}
And my question is after uncommenting the // in Main my JTabbedPanel disappears.
I want paint to draw in JTab.
http://forum.4programmers.net/Java/232952-jtabbedpanel_i_paint?mode=download&id=6326 <-- While it is commented
http://forum.4programmers.net/Java/232952-jtabbedpanel_i_paint?mode=download&id=6327 <-- After uncommenting.
Iam kinda newbie in Java so I would like to get easy answers :P.
Hej,
replace this
JPanel tab1Panel = new JPanel();
with that
JPanel tab1Panel = new DrawingWindow();
up to now, you add the DrawingPanel to another JPanel, but if you want to draw on your Tab, then add create a JPanel, which you'll add to your JTabbedPane with addTab().

Draw in an image inside panel

I have a panel with two buttons. I'm trying to insert an image inside the panel and I want to draw lines inside the image after clicking on a button. I have used the below code but this doesn't seem to work.
public class Try_Panel extends JFrame {
// start attributes
private JPanel jPanel1 = new JPanel(null, true);
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
// end attributes
public Try_Panel(String title) {
// Frame-Init
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 300;
int frameHeight = 300;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);
// start components
jPanel1.setBounds(48, 24, 209, 145);
jPanel1.setOpaque(false);
cp.add(jPanel1);
jButton1.setBounds(88, 208, 75, 25);
jButton1.setText("jButton1");
jButton1.setMargin(new Insets(2, 2, 2, 2));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1_ActionPerformed(evt);
}
});
cp.add(jButton1);
jButton2.setBounds(184, 208, 75, 25);
jButton2.setText("jButton2");
jButton2.setMargin(new Insets(2, 2, 2, 2));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2_ActionPerformed(evt);
}
});
cp.add(jButton2);
// end components
setVisible(true);
} // end of public Try_Panel
// start methods
public void jButton1_ActionPerformed(ActionEvent evt) {
BufferedImage image=new BufferedImage(jPanel1.getWidth(), jPanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
JLabel l=new JLabel(new ImageIcon(image));
Graphics graphics = image.getGraphics();
Graphics2D g = (Graphics2D) graphics;
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.BLUE);
g.drawLine(0, 0, 300, 400);
jPanel1.add(l);
} // end of jButton1_ActionPerformed
public void jButton2_ActionPerformed(ActionEvent evt) {
// TODO add your code here
} // end of jButton2_ActionPerformed
// end methods
public static void main(String[] args) {
new Try_Panel("Try_Panel");
} // end of main
} // end of class Try_Panel
The biggest problem is the same code worked in my other class.
Try wrapping the image inside the ImageIcon AFTER you have updated it. Also, you should also call Graphics#dispose when you are finished rendering to the graphics context.
public void jButton1_ActionPerformed(ActionEvent evt) {
BufferedImage image=new BufferedImage(jPanel1.getWidth(), jPanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = image.createGraphics();
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.BLUE);
g.drawLine(0, 0, 300, 400);
g.dispose();
JLabel l=new JLabel(new ImageIcon(image));
jPanel1.add(l);
}
You should also rely on the layout managers rather the trying to do it yourself, it will simply make your life easier.
Personally, I think it would easier to paint directly to a custom component, like JPanel. Check out Performing Custom Painting for more details
UPDATED with example
Basically, I changed your example to
Use layout managers
Load the UI within the context of the EDT
revalidate the jPanel1
public class BadLabel extends JFrame {
// start attributes
private JPanel jPanel1 = new JPanel(new BorderLayout(), true);
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
// end attributes
public BadLabel(String title) {
// Frame-Init
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 300;
int frameHeight = 300;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
// setResizable(false);
Container cp = getContentPane();
// cp.setLayout(null);
// start components
// jPanel1.setBounds(48, 24, 209, 145);
jPanel1.setOpaque(true);
jPanel1.setBackground(Color.RED);
cp.add(jPanel1);
JPanel buttons = new JPanel();
// jButton1.setBounds(88, 208, 75, 25);
jButton1.setText("jButton1");
jButton1.setMargin(new Insets(2, 2, 2, 2));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1_ActionPerformed(evt);
}
});
buttons.add(jButton1);
// jButton2.setBounds(184, 208, 75, 25);
jButton2.setText("jButton2");
jButton2.setMargin(new Insets(2, 2, 2, 2));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2_ActionPerformed(evt);
}
});
buttons.add(jButton2);
// end components
cp.add(buttons, BorderLayout.SOUTH);
setVisible(true);
} // end of public BadLabel
// start methods
public void jButton1_ActionPerformed(ActionEvent evt) {
BufferedImage image = new BufferedImage(jPanel1.getWidth(), jPanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = image.createGraphics();
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.BLUE);
g.drawLine(0, 0, 300, 400);
g.dispose();
JLabel l = new JLabel(new ImageIcon(image));
l.setBorder(new LineBorder(Color.BLUE));
jPanel1.add(l);
jPanel1.revalidate();
} // end of jButton1_ActionPerformed
public void jButton2_ActionPerformed(ActionEvent evt) {
// TODO add your code here
} // end of jButton2_ActionPerformed
// end methods
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
}
new BadLabel("BadLabel");
}
});
} // end of main
} // end of class BadLabel}
Something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.border.EmptyBorder;
public class Try_Panel {
// start attributes
private JButton jButton1 = new JButton("jButton1");
private JButton jButton2 = new JButton("jButton2");
private JLabel imageView;
BufferedImage image;
int x = 300;
int y = 50;
// end attributes
public Component getGui() {
JPanel gui = new JPanel(new BorderLayout(5, 5));
gui.setBorder(new EmptyBorder(3, 3, 3, 3));
image = new BufferedImage(300, 100, BufferedImage.TYPE_INT_RGB);
imageView = new JLabel(new ImageIcon(image));
gui.add(imageView, BorderLayout.CENTER);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
gui.add(buttons, BorderLayout.PAGE_END);
jButton1.setMargin(new Insets(2, 2, 2, 2));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1_ActionPerformed(evt);
}
});
buttons.add(jButton1);
jButton2.setMargin(new Insets(2, 2, 2, 2));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2_ActionPerformed(evt);
}
});
buttons.add(jButton2);
// end components
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
// Frame-Init
JFrame f = new JFrame("Try Panel");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
Container cp = f.getContentPane();
cp.setLayout(new BorderLayout(3, 3));
Try_Panel tp = new Try_Panel();
cp.add(tp.getGui());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
} // end of public Try_Panel
// start methods
public void jButton1_ActionPerformed(ActionEvent evt) {
Graphics graphics = image.getGraphics();
Graphics2D g = (Graphics2D) graphics;
g.setColor(Color.RED);
g.drawLine(0, 0, x, y);
x -= 4;
y += 2;
g.dispose();
imageView.repaint();
} // end of jButton1_ActionPerformed
public void jButton2_ActionPerformed(ActionEvent evt) {
// TODO add your code here
} // end of jButton2_ActionPerformed
} // end of class Try_Panel

Categories

Resources