Good morning. I want to write a program that scale up a filledgraphic with the help of JSlider. When ActPanel and Contour were inner classes of Lab4, they at least showed themselves on a JFrame. But there was a huge problem with passing Radius and repainting. I refrained from using inner classes, but it gave me no more ActPanel and Contour on the screen.
Here is code's most important part
class ActPanel extends JPanel implements ChangeListener {
public Contour cont;
public ActPanel(Contour contour) {
super(new FlowLayout());
cont = contour;
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 250, 50);
slider.addChangeListener(this);
JButton button = new JButton("display mark");
}
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JSlider) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int R = (int)source.getValue();
cont.setR(R);
cont.repaint();
}
}
}
}
class Contour extends JPanel {
private static final int pointCount = 9;
public void paintComponent(Graphics gfx) {
super.paintComponent(gfx);
Graphics2D g = (Graphics2D) gfx;
GeneralPath fpolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD, pointCount);
fpolygon.moveTo(Float.valueOf((float)R+250), Float.valueOf(250.0f));
fpolygon.lineTo(Float.valueOf(250.0f), Float.valueOf(250.0f));
//some drawing
}
private int R;
public void setR(int R) {
this.R = R;
}
public int getR() {
return R;
}
}
public class Lab4 {
private static void addComponentsToPane(Container pane) {
if (!(pane.getLayout() instanceof BorderLayout)) {
pane.add(new JLabel("Container doesn't use BorderLayout!"));
return;
}
Contour cont = new Contour();
ActPanel bottom = new ActPanel(cont);
pane.add(bottom, BorderLayout.PAGE_END);
cont.setPreferredSize(new Dimension(500,500));
pane.add(cont, BorderLayout.LINE_END);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Lab4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String [] arg) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
And that's a full version
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.*;
class ActPanel extends JPanel implements ChangeListener {
public Contour cont;
public ActPanel(Contour contour) {
super(new FlowLayout());
cont = contour;
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 250, 50);
slider.addChangeListener(this);
JButton button = new JButton("display mark");
}
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JSlider) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int R = (int)source.getValue();
cont.setR(R);
cont.repaint();
}
}
}
}
class Contour extends JPanel {
private static final int pointCount = 9;
public void paintComponent(Graphics gfx) {
super.paintComponent(gfx);
double kappa = 0.5522847498;
Graphics2D g = (Graphics2D) gfx;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
GeneralPath fpolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD, pointCount);
fpolygon.moveTo(Float.valueOf((float)R+250), Float.valueOf(250.0f));
fpolygon.lineTo(Float.valueOf(250.0f), Float.valueOf(250.0f));
fpolygon.lineTo(Float.valueOf(250.0f), Float.valueOf((float)250-R/2));
fpolygon.curveTo(
Float.valueOf((float)((-R/2)*kappa+250)),Float.valueOf((float)(-R/2)+250),
Float.valueOf((float)(-R/2)+250),Float.valueOf((float)((-R/2)*kappa)+250),
Float.valueOf((float)-R/2+250), Float.valueOf(250.0f));
fpolygon.lineTo(Float.valueOf((float)-R+250), Float.valueOf(250.0f));
fpolygon.lineTo(Float.valueOf((float)-R+250), Float.valueOf((float)R+250));
fpolygon.lineTo(Float.valueOf(250.0f), Float.valueOf((float)R+250));
fpolygon.lineTo(Float.valueOf(250.0f), Float.valueOf((float)R/2+250));
fpolygon.lineTo(Float.valueOf((float)R+250), Float.valueOf(250.0f));
fpolygon.closePath();
g.setPaint(Color.red);
g.fill(fpolygon);
g.setPaint(Color.black);
g.draw(fpolygon);
}
private int R;
public void setR(int R) {
this.R = R;
}
public int getR() {
return R;
}
}
public class Lab4 {
private static void addComponentsToPane(Container pane) {
if (!(pane.getLayout() instanceof BorderLayout)) {
pane.add(new JLabel("Container doesn't use BorderLayout!"));
return;
}
Contour cont = new Contour();
ActPanel bottom = new ActPanel(cont);
pane.add(bottom, BorderLayout.PAGE_END);
JList<Integer> xList = new JList<Integer>(new Integer[] {4,2,5,1,-5,-1,-4});
pane.add(xList, BorderLayout.LINE_START);
JPanel yPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
yPanel.add(new Label("x\\y"));
yPanel.add(new JCheckBox("5"));
yPanel.add(new JCheckBox("1"));
yPanel.add(new JCheckBox("-5"));
yPanel.add(new JCheckBox("2"));
yPanel.add(new JCheckBox("-5"));
yPanel.add(new JCheckBox("-1"));
yPanel.add(new JCheckBox("4"));
pane.add(yPanel, BorderLayout.PAGE_START);
cont.setPreferredSize(new Dimension(500,500));
pane.add(cont, BorderLayout.LINE_END);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Lab4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String [] arg) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You never add the any component to the ActPanel:
public ActPanel(Contour contour) {
super(new FlowLayout());
...
// you're missing the following lines:
this.add(slider);
this.add(button);
So it is in the frame, but empty.
The Contour panel is also in the frame. Add these lines to it, and you'll see it:
public Contour() {
setBackground(Color.BLUE);
}
Related
Can You Guys Help me
like input 1 or 2 checked color RED
if both checked input checked turn green
its for XNOR gate logic gates in java
i dont know how to do this is for my college but they dont teach me how to do that i cant find a good docs for that
i tried so much things but when i try its keep give red when i check both
class XNOR extends JPanel {
JFrame frame = new JFrame("XNOR Gate");
JCheckBox input1 = new JCheckBox("Input 1");
JCheckBox input2 = new JCheckBox("Input 2");
JPanel outputPanel = new Box(Color.PINK);
public XNOR() {
input1.addActionListener(actionEvent -> {
updateOutputState1();
});
input2.addActionListener(actionEvent -> {
updateOutputState1();
});
input1.addActionListener(actionEvent -> {
updateOutputState();
});
input2.addActionListener(actionEvent -> {
updateOutputState();
});
createFrame();
}
private void createFrame() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JPanel inputPanel = new JPanel();
inputPanel.add(input1);
inputPanel.add(input2);
frame.add(inputPanel);
frame.add(outputPanel);
frame.setSize(300, 300);
frame.setVisible(true);
}
private void updateOutputState() {
if(input1.isSelected() && input2.isSelected()){
frame.remove(outputPanel);
this.outputPanel = new Box(Color.GREEN);
frame.add(outputPanel);
}
else {
frame.remove(outputPanel);
this.outputPanel = new Box(Color.RED);
frame.add(outputPanel);
}
frame.revalidate();
frame.repaint();
}
private void updateOutputState1() {
if(input1.isSelected() || input2.isSelected()){
frame.remove(outputPanel);
this.outputPanel = new Box(Color.RED);
frame.add(outputPanel);
}
else {
frame.remove(outputPanel);
this.outputPanel = new Box(Color.GREEN);
frame.add(outputPanel);
}
frame.revalidate();
frame.repaint();
}
}
class Box extends JPanel {
Color color;
public Box(Color color) {
this.color = color;
}
public Dimension getPreferredSize() {
return new Dimension(200,200);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2=(Graphics2D) g;
g2.setPaint(color);
Rectangle2D rect=new Rectangle2D.Double(20,20,200,200);
g2.draw(rect);
g2.fill(rect);
}
}
class RunXNOR {
public static void main(String[] args) {
new XNOR();
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
class AndGate extends JPanel {
JFrame frame = new JFrame("And Gate");
JCheckBox input1 = new JCheckBox("Input 1");
JCheckBox input2 = new JCheckBox("Input 2");
Box outputPanel = new Box();
public AndGate() {
input1.addActionListener(actionEvent -> {
updateOutputState();
});
input2.addActionListener(actionEvent -> {
updateOutputState();
});
createFrame();
}
private void createFrame() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JPanel inputPanel = new JPanel();
inputPanel.add(input1);
inputPanel.add(input2);
frame.add(inputPanel);
outputPanel.repaint();
frame.add(outputPanel);
frame.setSize(300, 300);
frame.setVisible(true);
}
private void updateOutputState() {
if(input1.isSelected() && input2.isSelected()) {
this.outputPanel.changeColor(Color.GREEN);
} else {
this.outputPanel.changeColor(Color.RED);
}
}
}
class Box extends JPanel {
Graphics2D g2;
Color color = Color.RED;
Rectangle2D rect=new Rectangle2D.Double(20,20,200,200);
public Box() {
}
public Dimension getPreferredSize() {
return new Dimension(200,200);
}
public void changeColor(Color color) {
this.color = color;
g2.setPaint(color);
g2.fill(rect);
this.repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g2 = (Graphics2D) g;
g2.setPaint(color);
g2.draw(rect);
g2.fill(rect);
}
}
class RunAndGate {
public static void main(String[] args) {
new AndGate();
}
}
Don't extend JFrame but extend JPanel. That can serve as your output panel. Then just add the CheckBoxes and small panel to that main panel.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
class AndGate extends JPanel {
JFrame frame = new JFrame("And Gate");
JCheckBox input1 = new JCheckBox("Input 1");
JCheckBox input2 = new JCheckBox("Input 2");
JPanel output = new JPanel();
public AndGate() {
input1.addActionListener(actionEvent -> {
updateOutputState();
});
input2.addActionListener(actionEvent -> {
updateOutputState();
});
createFrame();
}
private void createFrame() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
output.setPreferredSize(new Dimension(200,200));
output.setVisible(true);
output.setBackground(Color.red);
add(input1);
add(input2);
add(output);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null); // center on screen
frame.setVisible(true);
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private void updateOutputState() {
if(input1.isSelected() && input2.isSelected()) {
output.setBackground(Color.green);
} else {
output.setBackground(Color.red);
}
}
}
public class RunAndGate {
public static void main(String[] args) {
new AndGate();
}
}
JButtons are not displayed until or unless I hover on the buttons.
package paint;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* #author Rehan Shakir
*/
public class PaintFrame extends JFrame implements MouseMotionListener,ActionListener
{
private int x=0;
private int y=0;
private final JButton red,yellow,blue,green;
private final JPanel p;
//private final JLabel l;
private final Container c;
private Color color;
public PaintFrame()
{
setTitle("Paint");
setSize(800,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//setLayout(new FlowLayout());
p = new JPanel();
p.setLayout(new GridLayout(4,1));
red = new JButton("Red");
red.setBackground(Color.red);
p.add(red);
yellow = new JButton("Yellow");
yellow.setBackground(Color.yellow);
p.add(yellow);
blue = new JButton("Blue");
blue.setBackground(Color.blue);
p.add(blue);
green = new JButton("Green");
green.setBackground(Color.green);
p.add(green);
red.addActionListener(this);
yellow.addActionListener(this);
blue.addActionListener(this);
green.addActionListener(this);
c = this.getContentPane();
c.setLayout(new BorderLayout());
JLabel l = new JLabel("Drag the mouse to draw",JLabel.RIGHT);
c.add(l,BorderLayout.SOUTH);
c.add(p,BorderLayout.WEST);
c.addMouseMotionListener(this);
setVisible(true);
}
#Override
public void mouseDragged(MouseEvent e )
{
x= e.getX();
y= e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e)
{
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Red"))
color = Color.red;
else if(s.equals("Yellow"))
color = Color.yellow;
else if(s.equals("Blue"))
color = Color.blue;
else if(s.equals("Green"))
color = Color.green;
else
color = Color.BLACK;
}
#Override
public void paint(Graphics g)
{
g.setColor(color);
g.fillOval(x, y, 4, 4);
}
}
Main Class
public class Paint {
package paint;
public static void main(String[] args) {
// TODO code application logic here
PaintFrame Jf = new PaintFrame();
}
}
When I execute this program only the first JButton is displayed on the screen. I have to hover on other buttons so that they can be displayed on the screen.
Why does this happen?
Immediately from your title, I could guess that you weren't calling the super's painting method in your override -- and I was right:
#Override
public void paint(Graphics g)
{
// ********** no super call here! *******
g.setColor(color);
g.fillOval(x, y, 4, 4);
}
By not doing this, you're not allowing the component to do its important house-keeping painting, including the painting of child components and removal of "dirty" pixels
This:
#Override
public void paint(Graphics g)
{
super.paint(g);
g.setColor(color);
g.fillOval(x, y, 4, 4);
}
will likely fix things
Having said this, I must add:
Don't paint directly in a JFrame
Do paint in the paintComponent method override of a class that extends JPanel instead
Call the super.paintComponent(g) in your JPanel's overridden method (for the same reasons).
Example using a BufferedImage:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainPaintPanel extends JPanel {
private PaintPanel paintPanel = new PaintPanel();
public MainPaintPanel() {
MyMouse myMouse = new MyMouse();
paintPanel.addMouseListener(myMouse);
paintPanel.addMouseMotionListener(myMouse);
JPanel btnPanel = new JPanel(new GridLayout(0, 1, 3, 3));
addColorButton(btnPanel, Color.RED, "Red");
addColorButton(btnPanel, Color.YELLOW, "Yellow");
addColorButton(btnPanel, Color.BLUE, "Blue");
addColorButton(btnPanel, Color.GREEN, "Green");
setLayout(new BorderLayout());
add(paintPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.LINE_START);
}
class MyMouse extends MouseAdapter {
Point p1 = null;
private void moveOval(MouseEvent e) {
if (p1 == null) {
return;
}
Point p2 = e.getPoint();
paintPanel.addLine(p1, p2);
}
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
moveOval(e);
p1 = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
moveOval(e);
p1 = null;
}
}
private void addColorButton(JPanel btnPanel, Color color, String name) {
JButton button = new JButton(new ButtonAction(name, color));
button.setBackground(color);
btnPanel.add(button);
}
class ButtonAction extends AbstractAction {
private Color color;
public ButtonAction(String name, Color color) {
super(name);
this.color = color;
}
#Override
public void actionPerformed(ActionEvent e) {
paintPanel.setOvalColor(color);
}
}
private static void createAndShowGui() {
MainPaintPanel mainPanel = new MainPaintPanel();
JFrame frame = new JFrame("Painting GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class PaintPanel extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
private static final int OVAL_WIDTH = 4;
private static final Stroke BASIC_STROKE = new BasicStroke(OVAL_WIDTH);
private BufferedImage img;
private Color ovalColor;
public PaintPanel() {
img = new BufferedImage(PREF_W, PREF_W, BufferedImage.TYPE_INT_ARGB);
}
public void addLine(Point p1, Point p2) {
if (img != null && ovalColor != null) {
Graphics2D g2 = img.createGraphics();
g2.setStroke(BASIC_STROKE);
g2.setColor(ovalColor);
g2.drawLine(p1.x, p1.y, p2.x, p2.y);
g2.dispose();
repaint();
}
}
public void setOvalColor(Color ovalColor) {
this.ovalColor = ovalColor;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
I have a class which extends a Jframe, and i have it centered using setLocationRelativeTo(null);. The layouManager is null aswell.
My JFrame:
mport com.sxf.protocol.chat.util.window.AbstractField;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
public class Field extends AbstractField {
private Container cp;
public Field() {
super("Test");
buildWindow();
}
private void buildWindow() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(frameWidth, frameHeight));
setResizable(false);
cp = getContentPane();
cp.setLayout(null);
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void initComponents() {
JLabel label = new JLabel("Test", SwingConstants.CENTER);
JLabel border = new JLabel("");
label.setSize(200, 30);
label.setLocation((frameWidth - label.getWidth()) / 2, (frameHeight - label.getHeight()) / 2);
border.setBounds(frameWidth / 2, 0, frameWidth / 2, frameHeight);
label.setBorder(new LineBorder(new Color(0, 0, 0)));
border.setBorder(new LineBorder(new Color(255, 0, 0)));
cp.add(label);
cp.add(border);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Field();
}
});
}
}
I added to border to see if its centered correctly or not.
The AbstractField (only some calculations in it):
public abstract class AbstractField extends JFrame {
private final static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private static final Dimension frameSize = new Dimension(screenSize.width / 4, screenSize.height / 4);
protected static final int frameWidth;
protected static final int frameHeight;
protected static final int x;
protected static final int y;
static {
frameWidth = frameSize.width;
frameHeight = frameSize.height;
x = (screenSize.width - frameWidth) / 2;
y = (screenSize.height - frameHeight) / 2;
}
public AbstractField(String title) {
super(title);
}
}
But when i try to center my components, e.g. the JLabel, doing
(frame.getWidth - component.getWidth) / 2, and the same for the height, it is not actually centered but a little bit to the right.
Is that due to a native moved beginning of the jframe and can i calculate that?
How to indeed center object in a JFrame?
Indeed add it as the only component added to a JPanel with a GridBagLayout. Use that panel as the content pane.
Example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CenteredLabel {
private JComponent ui = null;
CenteredLabel() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(4,4,4,4));
JLabel centeredLabel = new JLabel("Test");
centeredLabel.setBorder(new LineBorder(Color.RED));
ui.add(centeredLabel);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
CenteredLabel o = new CenteredLabel();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
I have a JPanel which contains a JToolbar (including few buttons without text) and a JTable and I need to enable/disable (make internal widgets not clickable). I tried this:
JPanel panel = ....;
for (Component c : panel.getComponents()) c.setEnabled(enabled);
but it doesn't work. Is there a better and more generic solution to enable/disable all internal components in a JPanel?
I have partially solved my problem using JLayer starting from the example here http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html:
layer = new JLayer<JComponent>(myPanel, new BlurLayerUI(false));
.....
((BlurLayerUI)layer.getUI()).blur(...); // switch blur on/off
class BlurLayerUI extends LayerUI<JComponent> {
private BufferedImage mOffscreenImage;
private BufferedImageOp mOperation;
private boolean blur;
public BlurLayerUI(boolean blur) {
this.blur = blur;
float ninth = 1.0f / 9.0f;
float[] blurKernel = {
ninth, ninth, ninth,
ninth, ninth, ninth,
ninth, ninth, ninth
};
mOperation = new ConvolveOp(
new Kernel(3, 3, blurKernel),
ConvolveOp.EDGE_NO_OP, null);
}
public void blur(boolean blur) {
this.blur=blur;
firePropertyChange("blur", 0, 1);
}
#Override
public void paint (Graphics g, JComponent c) {
if (!blur) {
super.paint (g, c);
return;
}
int w = c.getWidth();
int h = c.getHeight();
if (w == 0 || h == 0) {
return;
}
// Only create the offscreen image if the one we have
// is the wrong size.
if (mOffscreenImage == null ||
mOffscreenImage.getWidth() != w ||
mOffscreenImage.getHeight() != h) {
mOffscreenImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
Graphics2D ig2 = mOffscreenImage.createGraphics();
ig2.setClip(g.getClip());
super.paint(ig2, c);
ig2.dispose();
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(mOffscreenImage, mOperation, 0, 0);
}
#Override
public void applyPropertyChange(PropertyChangeEvent pce, JLayer l) {
if ("blur".equals(pce.getPropertyName())) {
l.repaint();
}
}
}
I still have 2 problems:
In the link above events are relative to mouse only. How can I manage the keyboard events?
How can I create a "gray out" effect in place of blur?
It requires a recursive call.
import java.awt.*;
import javax.swing.*;
public class DisableAllInContainer {
public void enableComponents(Container container, boolean enable) {
Component[] components = container.getComponents();
for (Component component : components) {
component.setEnabled(enable);
if (component instanceof Container) {
enableComponents((Container)component, enable);
}
}
}
DisableAllInContainer() {
JPanel gui = new JPanel(new BorderLayout());
final JPanel container = new JPanel(new BorderLayout());
gui.add(container, BorderLayout.CENTER);
JToolBar tb = new JToolBar();
container.add(tb, BorderLayout.NORTH);
for (int ii=0; ii<3; ii++) {
tb.add(new JButton("Button"));
}
JTree tree = new JTree();
tree.setVisibleRowCount(6);
container.add(new JScrollPane(tree), BorderLayout.WEST);
container.add(new JTextArea(5,20), BorderLayout.CENTER);
final JCheckBox enable = new JCheckBox("Enable", true);
enable.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
enableComponents(container, enable.isSelected());
}
});
gui.add(enable, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new DisableAllInContainer();
}
});
}}
I used the following function:
void setPanelEnabled(JPanel panel, Boolean isEnabled) {
panel.setEnabled(isEnabled);
Component[] components = panel.getComponents();
for(int i = 0; i < components.length; i++) {
if(components[i].getClass().getName() == "javax.swing.JPanel") {
setPanelEnabled((JPanel) components[i], isEnabled);
}
components[i].setEnabled(isEnabled);
}
}
you can overlay whole Container / JComponent
GlassPane block by default MouseEvents, but not Keyboard, required consume all keyevents from ToolKit
JLayer (Java7) based on JXLayer (Java6)
can't see reason(s) why not works for you
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class AddComponentsAtRuntime {
private JFrame f;
private JPanel panel;
private JCheckBox checkValidate, checkReValidate, checkRepaint, checkPack;
public AddComponentsAtRuntime() {
JButton b = new JButton();
//b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(600, 20));
panel = new JPanel(new GridLayout(0, 1));
panel.add(b);
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel, "Center");
f.add(getCheckBoxPanel(), "South");
f.setLocation(200, 200);
f.pack();
f.setVisible(true);
}
private JPanel getCheckBoxPanel() {
checkValidate = new JCheckBox("validate");
checkValidate.setSelected(false);
checkReValidate = new JCheckBox("revalidate");
checkReValidate.setSelected(true);
checkRepaint = new JCheckBox("repaint");
checkRepaint.setSelected(true);
checkPack = new JCheckBox("pack");
checkPack.setSelected(true);
JButton addComp = new JButton("Add New One");
addComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton b = new JButton();
//b.setBackground(Color.red);
b.setBorder(new LineBorder(Color.black, 2));
b.setPreferredSize(new Dimension(400, 10));
panel.add(b);
makeChange();
System.out.println(" Components Count after Adds :" + panel.getComponentCount());
}
});
JButton removeComp = new JButton("Remove One");
removeComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int count = panel.getComponentCount();
if (count > 0) {
panel.remove(0);
}
makeChange();
System.out.println(" Components Count after Removes :" + panel.getComponentCount());
}
});
JButton disabledComp = new JButton("Disabled All");
disabledComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Component c : panel.getComponents()) {
c.setEnabled(false);
}
}
});
JButton enabledComp = new JButton("Enabled All");
enabledComp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Component c : panel.getComponents()) {
c.setEnabled(true);
}
}
});
JPanel panel2 = new JPanel();
panel2.add(checkValidate);
panel2.add(checkReValidate);
panel2.add(checkRepaint);
panel2.add(checkPack);
panel2.add(addComp);
panel2.add(removeComp);
panel2.add(disabledComp);
panel2.add(enabledComp);
return panel2;
}
private void makeChange() {
if (checkValidate.isSelected()) {
panel.validate();
}
if (checkReValidate.isSelected()) {
panel.revalidate();
}
if (checkRepaint.isSelected()) {
panel.repaint();
}
if (checkPack.isSelected()) {
f.pack();
}
}
public static void main(String[] args) {
AddComponentsAtRuntime makingChanges = new AddComponentsAtRuntime();
}
}
#Kesavamoorthi
if you want to make it more general:
void setPanelEnabled(java.awt.Container cont, Boolean isEnabled) {
cont.setEnabled(isEnabled);
java.awt.Component[] components = cont.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof java.awt.Container) {
setPanelEnabled((java.awt.Container) components[i], isEnabled);
}
components[i].setEnabled(isEnabled);
}
}
I've hit a wall (in my brain) trying to update my board on button presses. Am I right in thinking that the GameBoard class is the one that needs to be repaint()ed?
GameBoard.java
public class GameBoard extends Panel {
static Compass compass = new Compass();
private static final long serialVersionUID = 1;
Graphics2D g2d;
static final Dimension WINDOW_SIZE = new Dimension(1150, 800);
public void boardMaker() throws Exception {
JFrame frame = new JFrame("Display image");
JPanel panel = new JPanel();
/* unimportant stuff
.....
*/
//
DieRoll roll = new DieRoll("Roll Dies");
roll.setC(compass);
roll.setG2D(g2d);
//
Button button = new Button("new");
button.setGameBoard(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
buttonPanel.add(roll);
buttonPanel.setPreferredSize(new Dimension(200,100));
frame.getContentPane().add(buttonPanel, BorderLayout.NORTH);
//
frame.getContentPane().add(panel);
frame.setVisible(true);
}
public void paint(Graphics g) {
// not important I think
}
}
Button.java
public class Button extends JButton implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JFrame frame = new JFrame();
Compass c = new Compass();
GameBoard gb = new GameBoard();
Button(String text) {
this.setText(text);
this.addActionListener(this);
}
void setGameBoard(GameBoard gb) {
this.gb = gb;
}
#Override
public void actionPerformed(ActionEvent e) {
gb.g2d.setColor(Color.black);
gb.g2d.fillRect(100, 100, 100, 200);
gb.repaint();
}
}
This gives a null pointer exception. So any idea how to repaint my GameBoard? I'm not mad if I've to rewrite everything because of stupidity! ;)
Thanks
You have the wrong idea about how to draw in Java. Components like Panels draw themselves, and all drawing takes place on the UI thread.
Check out this tutorial: docs.oracle.com/javase/tutorial/2d/index.html
The article Painting in AWT and Swing may offer some perspective on application-triggered painting. The example below illustrates the principle. Note that setForeground() calls repaint() automatically because the foreground color is a bound property, but you can always call it yourself.
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class SwingPaint {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
final GamePanel gp = new GamePanel();
f.add(gp);
f.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
gp.update();
}
}), BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
private static class GamePanel extends JPanel {
private static final Random r = new Random();
public GamePanel() {
this.setForeground(new Color(r.nextInt()));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
public void update() {
this.setForeground(new Color(r.nextInt()));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = this.getSize();
int d = Math.min(size.width, size.height) - 10;
int x = (size.width - d) / 2;
int y = (size.height - d) / 2;
g.fillOval(x, y, d, d);
g.setColor(Color.blue);
g.drawOval(x, y, d, d);
}
}
}