I have the following button:
JButton S1L1Reset = new JButton("Reset");
S1L1Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L1Reset.setForeground(new Color(90, 90, 90));
S1L1Reset.setBackground(new Color(220, 208, 192));
S1L1Reset.setOpaque(true);
I would like for the button to be round instead of boxed. I found another post that created a class that can make the border of the button round which is shown below.
class RoundedBorder implements Border {
private int radius;
RoundedBorder(int radius) {
this.radius = radius;
}
public Insets getBorderInsets(Component c) {
return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
}
public boolean isBorderOpaque() {
return true;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawRoundRect(x, y, width-1, height-1, radius, radius);
}
}
When I make the changes to the button, to utilize this class, I get the following code:
JButton S1L1Reset = new JButton("Reset");
S1L1Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L1Reset.setForeground(new Color(90, 90, 90));
S1L1Reset.setBackground(new Color(220, 208, 192));
S1L1Reset.setOpaque(true);
S1L1Reset.setBorderPainted(false);
S1L1Reset.setBorder(new RoundedBorder(20)); //new line of code added
The code however creates a button that looks like the following: Button. Is there any way that I can format the button such that the background color also remains within the round border.
Entire Code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JMenu;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import java.awt.CardLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Graphics;
#SuppressWarnings("rawtypes")
public class TestEnvironment {
JFrame TestEnvironmentWindow;
Vector data1 = new Vector(100);
Vector data2 = new Vector(100);
Vector data3 = new Vector(100);
JTable S1L1;
JTable S1L2;
JTable S1L3;
private DefaultTableModel dataModel1;
private DefaultTableModel dataModel2;
private DefaultTableModel dataModel3;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
TestEnvironment window = new TestEnvironment();
window.TestEnvironmentWindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestEnvironment() {
initialize();
}
private void initialize() {
TestEnvironmentWindow = new JFrame();
TestEnvironmentWindow.getContentPane().setLayout(null);
TestEnvironmentWindow.setResizable(false);
TestEnvironmentWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TestEnvironmentWindow.setTitle("Statistics Tool Kit");
TestEnvironmentWindow.setIconImage(null);
TestEnvironmentWindow.setSize(new Dimension(1000, 650));
// Content Section
final TableModel dataModel = new AbstractTableModel() {
public int getColumnCount(){
return 5;
}
public int getRowCount(){
return 10;
}
public Object getValueAt(int row, int col){
return new Integer(row*col);
}
public boolean isCellEditable(int row, int col){
return true;
}
};
JPanel Content = new JPanel();
Content.setBounds(175, 0, 825, 605);
TestEnvironmentWindow.getContentPane().add(Content);
Content.setBackground(new Color(244,244,244));
Content.setLayout(new CardLayout(0, 0));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
Content.add(tabbedPane);
JPanel set1Panel = new JPanel();
set1Panel.setLayout(null);
Vector<String> columnNames = new Vector<String>(2);
columnNames.addElement("X-Values");
columnNames.addElement("Y-Values");
S1L1 = new JTable(data1, columnNames);
S1L1.setFont(new Font("Work Sans", Font.PLAIN, 12));
S1L1.setGridColor(new Color(150,150,150));
JScrollPane S1L1Scroll = new JScrollPane(S1L1,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
S1L1Scroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
dataModel1 = new DefaultTableModel(data1, columnNames);
S1L1.setModel(dataModel1);
S1L1Scroll.setBounds(38, 50, 225, 400);
set1Panel.add(S1L1Scroll);
S1L2 = new JTable(data2, columnNames);
S1L2.setFont(new Font("Work Sans", Font.PLAIN, 12));
S1L2.setGridColor(new Color(150,150,150));
JScrollPane S1L2Scroll = new JScrollPane(S1L2,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
S1L2Scroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
dataModel2 = new DefaultTableModel(data2, columnNames);
S1L2.setModel(dataModel2);
S1L2Scroll.setBounds(288, 50, 225, 400);
set1Panel.add(S1L2Scroll);
S1L3 = new JTable(data3, columnNames);
S1L3.setFont(new Font("Work Sans", Font.PLAIN, 12));
S1L3.setGridColor(new Color(150,150,150));
JScrollPane S1L3Scroll = new JScrollPane(S1L3,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
S1L3Scroll.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
dataModel3 = new DefaultTableModel(data3, columnNames);
S1L3.setModel(dataModel3);
S1L3Scroll.setBounds(538, 50, 225, 400);
set1Panel.add(S1L3Scroll);
JLabel ListOneLabel = new JLabel("List 1");
ListOneLabel.setFont(new Font("Work Sans", Font.PLAIN, 16));
ListOneLabel.setHorizontalAlignment(SwingConstants.CENTER);
ListOneLabel.setBackground(new Color(220, 208, 192));
ListOneLabel.setOpaque(true);
ListOneLabel.setBounds(77, 20, 150, 20);
set1Panel.add(ListOneLabel);
JLabel ListTwoLabel = new JLabel("List 2");
ListTwoLabel.setFont(new Font("Work Sans", Font.PLAIN, 16));
ListTwoLabel.setHorizontalAlignment(SwingConstants.CENTER);
ListTwoLabel.setBackground(new Color(220, 208, 192));
ListTwoLabel.setOpaque(true);
ListTwoLabel.setBounds(327, 20, 150, 20);
set1Panel.add(ListTwoLabel);
JLabel ListThreeLabel = new JLabel("List 3");
ListThreeLabel.setFont(new Font("Work Sans", Font.PLAIN, 16));
ListThreeLabel.setHorizontalAlignment(SwingConstants.CENTER);
ListThreeLabel.setBackground(new Color(220, 208, 192));
ListThreeLabel.setOpaque(true);
ListThreeLabel.setBounds(577, 20, 150, 20);
set1Panel.add(ListThreeLabel);
JButton S1L1Reset = new JButton("Reset");
S1L1Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L1Reset.setForeground(new Color(90, 90, 90));
S1L1Reset.setBackground(new Color(220, 208, 192));
S1L1Reset.setOpaque(true);
S1L1Reset.setBorderPainted(false);
S1L1Reset.setBorder(new RoundedBorder(20));
S1L1Reset.setBounds(43, 465, 100, 20);
set1Panel.add(S1L1Reset);
S1L1Reset.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
S1L1Reset.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
S1L1Reset.setForeground(new Color(90,90,90));
}
});
S1L1Reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteAllRows(dataModel1);
}
});
S1L1Reset.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
Color fillColor = c.getBackground();
g.setColor(fillColor);
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton S1L2Reset = new JButton("Reset");
S1L2Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L2Reset.setForeground(new Color(90, 90, 90));
S1L2Reset.setBackground(new Color(220, 208, 192));
S1L2Reset.setOpaque(true);
S1L2Reset.setBorderPainted(false);
S1L2Reset.setBorder(new RoundedBorder(20));
S1L2Reset.setBounds(293, 465, 100, 20);
set1Panel.add(S1L2Reset);
S1L2Reset.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
S1L2Reset.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
S1L2Reset.setForeground(new Color(90,90,90));
}
});
S1L2Reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteAllRows(dataModel2);
}
});
S1L2Reset.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton S1L3Reset = new JButton("Reset");
S1L3Reset.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L3Reset.setForeground(new Color(90, 90, 90));
S1L3Reset.setBackground(new Color(220, 208, 192));
S1L3Reset.setOpaque(true);
S1L3Reset.setBorderPainted(false);
S1L3Reset.setBorder(new RoundedBorder(20));
S1L3Reset.setBounds(543, 465, 100, 20);
set1Panel.add(S1L3Reset);
S1L3Reset.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
S1L3Reset.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
S1L3Reset.setForeground(new Color(90,90,90));
}
});
S1L3Reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
S1L3Reset.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton S1L1Save = new JButton("Save");
S1L1Save.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L1Save.setForeground(new Color(90, 90, 90));
S1L1Save.setBackground(new Color(220, 208, 192));
S1L1Save.setOpaque(true);
S1L1Save.setBorderPainted(false);
S1L1Save.setBorder(new RoundedBorder(20));
S1L1Save.setBounds(155, 465, 100, 20);
set1Panel.add(S1L1Save);
S1L1Save.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
S1L1Save.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
S1L1Save.setForeground(new Color(90,90,90));
}
});
S1L1Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
S1L1Save.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton S1L2Save = new JButton("Save");
S1L2Save.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L2Save.setForeground(new Color(90, 90, 90));
S1L2Save.setBackground(new Color(220, 208, 192));
S1L2Save.setOpaque(true);
S1L2Save.setBorderPainted(false);
S1L2Save.setBorder(new RoundedBorder(20));
S1L2Save.setBounds(405, 465, 100, 20);
set1Panel.add(S1L2Save);
S1L2Save.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
S1L2Save.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
S1L2Save.setForeground(new Color(90,90,90));
}
});
S1L2Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
S1L2Save.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton S1L3Save = new JButton("Save");
S1L3Save.setFont(new Font("Work Sans", Font.PLAIN, 14));
S1L3Save.setForeground(new Color(90, 90, 90));
S1L3Save.setBackground(new Color(220, 208, 192));
S1L3Save.setOpaque(true);
S1L3Save.setBorderPainted(false);
S1L3Save.setBorder(new RoundedBorder(20));
S1L3Save.setBounds(655, 465, 100, 20);
set1Panel.add(S1L3Save);
S1L3Save.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
S1L3Save.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
S1L3Save.setForeground(new Color(90,90,90));
}
});
S1L3Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
S1L3Save.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton ClearAll = new JButton("Clear All");
ClearAll.setFont(new Font("Work Sans", Font.PLAIN, 14));
ClearAll.setForeground(new Color(90, 90, 90));
ClearAll.setBackground(new Color(220, 208, 192));
ClearAll.setOpaque(true);
ClearAll.setBorderPainted(false);
ClearAll.setBorder(new RoundedBorder(20));
ClearAll.setBounds(238, 515, 150, 25);
set1Panel.add(ClearAll);
ClearAll.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
ClearAll.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
ClearAll.setForeground(new Color(90,90,90));
}
});
ClearAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ClearAll.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
JButton SaveAll = new JButton("Save All");
SaveAll.setFont(new Font("Work Sans", Font.PLAIN, 14));
SaveAll.setForeground(new Color(90, 90, 90));
SaveAll.setBackground(new Color(220, 208, 192));
SaveAll.setOpaque(true);
SaveAll.setBorderPainted(false);
SaveAll.setBorder(new RoundedBorder(20));
SaveAll.setBounds(410, 515, 150, 25);
set1Panel.add(SaveAll);
SaveAll.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
SaveAll.setForeground(new Color(0,0,0));
}
public void mouseExited(MouseEvent e) {
SaveAll.setForeground(new Color(90,90,90));
}
});
SaveAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
SaveAll.setUI(new BasicButtonUI() {
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
tabbedPane.add(set1Panel);
// Menu Bar Section
JPanel MenuBar = new JPanel();
MenuBar.setBackground(new Color(220, 208, 192));
MenuBar.setBounds(0, 0, 175, 605);
TestEnvironmentWindow.getContentPane().add(MenuBar);
MenuBar.setLayout(null);
// Menu Bar Section
JMenuBar menuBar = new JMenuBar();
TestEnvironmentWindow.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnSearch = new JMenu("Search");
menuBar.add(mnSearch);
JMenu mnWindow = new JMenu("Window");
menuBar.add(mnWindow);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
}
public static void deleteAllRows(final DefaultTableModel model) {
for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
model.removeRow(i);
}
}
}
The swing component uses UI delegate to draw itself, the background painting is done in the base class ComponentUI like this:
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRect(0, 0, c.getWidth(),c.getHeight());
}
paint(g, c);
}
As you can see it uses fillRect so it must fill the background rectangularly. To change it, create a subclass of BasicButtonUI (whose subclasses are UI delegate of various look & feels) and override this method by filling round rect instead:
S1L1Reset.setUI(new BasicButtonUI() {
#Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
Color fillColor = c.getBackground();
AbstractButton button = (AbstractButton) c;
ButtonModel model = button.getModel();
if (model.isPressed()) {
fillColor = fillColor.darker();
} else if (model.isRollover()) {
fillColor = fillColor.brighter();
}
g.setColor(fillColor);
g.fillRoundRect(0, 0, c.getWidth(),c.getHeight(), 20, 20);
}
paint(g, c);
}
});
As you can see in the code, you'll need to handle various states of the button like mouse pressed background because these are done in the BasicButtonUI subclasses, since you no longer using these subclasses, you'll have to implement all that by yourself. You may reference MetalButtonUI for an example of how a button paints itself under different states in the Metal look & feel.
And maybe the call to setBorderPainted(false) is not needed? If you really want to utilize the round border you should need it to be painted.
Just adjust the width and height of class RoundButton as well as corner in the method of setRoundRect(double a, double y, double w, double h, double arcWidth, double arcHeight)
class RoundButton extends JButton {
public RoundButton(String label) {
super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width,size.height);
setPreferredSize(size);
setContentAreaFilled(false);
}
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillRoundRect(0, 0, 250, 50, 40, 40);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawRoundRect(0, 0, 250, 50, 10, 10);
}
Shape shape;
public boolean contains(int x, int y) {
if (shape == null ||
!shape.getBounds().equals(getBounds())) {
shape = new RoundRectangle2D.Float(0, 0, 250, 50,10,10);
}
return shape.contains(x, y);
}
}
To use that class ex
JButton a = new RoundButton("ABC");
a.setBounds(400,0,250,50);
a.setForeground(Color.WHITE);
a.setBackground(Color.BLACK);
a.setFont(new Font("Roboto", Font.BOLD, 15));
panel.add(a);
I have created the interface gui and added the buttons. But now I am stuck with the "Steady" button. When I click it I want to the circle "light bulb" to change color from yellow to orange.
What am I doing wrong in my code and when I press the "Steady" button nothing is happening?
/**
* Created by Metallion on 30/03/2015.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BelishaBeacon {
public class Drawing extends JPanel {
private int x = 125;
private int y = 80;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//creating the shapes
Rectangle box1 = new Rectangle(165, 180, 20, 45);
Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(165, 270, 20, 45);
Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(165, 360, 20, 45);
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.YELLOW);
g2.fill(ball);
}
}
public class changeColors extends JPanel {
private boolean choseColor = false;
private int x = 125;
private int y = 80;
public void changeColor(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.ORANGE);
if (!choseColor) {
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
}
public void changeColor() { choseColor = false; }
}
public BelishaBeacon() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(350, 570);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
final changeColors colorinG = new changeColors();
JButton jbtFlash = new JButton("Flash");
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorinG.changeColor();
colorinG.repaint();
}
});
//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);
}
public static void main(String[] args) {
new BelishaBeacon();
}
}
You need to add handling logic to your Drawing Swing component, e.g.:
add method to your Drawing to change the color
modify the paintComponent(Graphics) according to the first step
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BelishaBeacon {
public class Drawing extends JPanel {
private int x = 125;
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(165, 180, 20, 45);
Rectangle box2 = new Rectangle(165, 225, 20, 45);
Rectangle box3 = new Rectangle(165, 270, 20, 45);
Rectangle box4 = new Rectangle(165, 315, 20, 45);
Rectangle box5 = new Rectangle(165, 360, 20, 45);
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.YELLOW);
g2.fill(ball);
if (changeColors) {
g2.setColor(Color.ORANGE);
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
changeColors = false;
}
public void changeColors() {
changeColors = true;
repaint();
}
}
public BelishaBeacon() {
//Creation of frame
JFrame frame = new JFrame();
frame.setSize(350, 570);
frame.setTitle("Belisha Beacon");
frame.setLayout(new BorderLayout(0, 0));
final Drawing shapes = new Drawing();
JButton jbtFlash = new JButton("Flash");
final JButton jbtSteady = new JButton("Steady");
jbtSteady.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.changeColors();
}
});
//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);
}
public static void main(String[] args) {
new BelishaBeacon();
}
}
So the task I've been set is to make an animation of a lamp. There are buttons added that do different actions such as change colour of the sphere etc.
Code: Sphere Class
public class Sphere extends JPanel {
private boolean flashinglights = false;
private int x = 168;
private int y = 75;
private Color[] colors = new Color[] {Color.ORANGE, Color.LIGHT_GRAY };
private int colorIndex = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Graphics2D g3 = (Graphics2D) g;
if (!flashinglights) {
Rectangle box0 = new Rectangle(x+16, y+50,14, 50);
g3.setColor(Color.black);
g3.draw(box0);
g3.fill(box0);
Rectangle box1 = new Rectangle(x+16, y+90,14, 50);
g3.setColor(Color.white);
g3.draw(box1);
g3.fill(box1);
Rectangle box2 = new Rectangle(x+16, y+130,14, 50);
g3.setColor(Color.black);
g3.draw(box2);
g3.fill(box2);
Rectangle box3 = new Rectangle(x+16, y+170,14, 50);
g3.setColor(Color.white);
g3.draw(box3);
g3.fill(box3);
Rectangle box4 = new Rectangle(x+16, y+210,14, 50);
g3.setColor(Color.black);
g3.draw(box4);
g3.fill(box4);
Rectangle box5 = new Rectangle(x+16, y+250,14, 50);
g3.setColor(Color.white);
g3.draw(box5);
g3.fill(box5);
Rectangle box6 = new Rectangle(x+16, y+290,14, 50);
g3.setColor(Color.black);
g3.draw(box6);
g3.fill(box6);
Rectangle box7 = new Rectangle(x+16, y+330,14, 50);
g3.setColor(Color.white);
g3.draw(box7);
g3.fill(box7);
Rectangle box8 = new Rectangle(x+16, y+370,14, 50);
g3.setColor(Color.black);
g3.draw(box8);
g3.fill(box8);
Rectangle box9 = new Rectangle(x+16, y+410,14, 50);
g3.setColor(Color.white);
g3.draw(box9);
g3.fill(box9);
Rectangle box10 = new Rectangle(x+16, y+450,14, 50);
g3.setColor(Color.black);
g3.draw(box10);
g3.fill(box10);
g2.setColor(Color.ORANGE);
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 50, 50);
g2.draw(ball);
g2.fill(ball);
} else {
if(colorIndex > colors.length - 1)
colorIndex = 0;
Rectangle box0 = new Rectangle(x+16, y+50,14, 50);
g3.setColor(Color.black);
g3.draw(box0);
g3.fill(box0);
Rectangle box1 = new Rectangle(x+16, y+90,14, 50);
g3.setColor(Color.white);
g3.draw(box1);
g3.fill(box1);
Rectangle box2 = new Rectangle(x+16, y+130,14, 50);
g3.setColor(Color.black);
g3.draw(box2);
g3.fill(box2);
Rectangle box3 = new Rectangle(x+16, y+170,14, 50);
g3.setColor(Color.white);
g3.draw(box3);
g3.fill(box3);
Rectangle box4 = new Rectangle(x+16, y+210,14, 50);
g3.setColor(Color.black);
g3.draw(box4);
g3.fill(box4);
Rectangle box5 = new Rectangle(x+16, y+250,14, 50);
g3.setColor(Color.white);
g3.draw(box5);
g3.fill(box5);
Rectangle box6 = new Rectangle(x+16, y+290,14, 50);
g3.setColor(Color.black);
g3.draw(box6);
g3.fill(box6);
Rectangle box7 = new Rectangle(x+16, y+330,14, 50);
g3.setColor(Color.white);
g3.draw(box7);
g3.fill(box7);
Rectangle box8 = new Rectangle(x+16, y+370,14, 50);
g3.setColor(Color.black);
g3.draw(box8);
g3.fill(box8);
Rectangle box9 = new Rectangle(x+16, y+410,14, 50);
g3.setColor(Color.white);
g3.draw(box9);
g3.fill(box9);
Rectangle box10 = new Rectangle(x+16, y+450,14, 50);
g3.setColor(Color.black);
g3.draw(box10);
g3.fill(box10);
g2.setColor(colors[colorIndex++]);
Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 50, 50);
g2.draw(ball);
g2.fill(ball);
}
}
public void chooseflashinglights(){
flashinglights = true;
}
public void choosesteady(){
flashinglights = false;
}
public static void main(String[] args) {
JFrame scFrame = new AnimationViewer();
scFrame.setTitle("Belisha Beacon");
scFrame.setSize(400, 500);
scFrame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
scFrame.setVisible(true);
}
}
Code: Animation Viewer CLass
public class AnimationViewer extends JFrame {
JButton jbtFlash = new JButton("Flash");
JButton jbtSteady = new JButton("Steady");
JPanel bPanel = new JPanel();
Sphere sphPanel = new Sphere();
Timer timer;
public AnimationViewer() {
timer = new Timer(500, new TimerListener());
this.add(bPanel, BorderLayout.SOUTH);
bPanel.add(jbtFlash);
bPanel.setLayout(new GridLayout(1, 1));
bPanel.add(jbtSteady);
this.add(sphPanel, BorderLayout.CENTER);
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sphPanel.chooseflashinglights();
timer.start();
}
});
jbtSteady.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sphPanel.choosesteady();
timer.stop();
sphPanel.repaint();
}
});
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
sphPanel.repaint();
}
}
}
The main two buttons do two different things. One makes the sphere stay a solid orange colour (Steady) and the other makes the sphere alternate from Orange to grey. (flashing)
NOW THE PROBLEM:
When you start the program the sphere starts of in Steady mode were the colour is just solid orange.
I want the program to START in flashing mode. So when you click run the sphere should be straight in the flashing stage alternating from orange to grey straight away.
So how can I make it so I can start a piece of code first so it goes straight to the flashing lights mode?
Extract the code used to switch the mode to flashing in a method, to avoid code duplication:
private void flash() {
sphPanel.chooseflashinglights();
timer.start();
}
Call this method from the action listener:
jbtFlash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
flash();
}
});
And also call it in the constructor:
public AnimationViewer() {
// existing code omitted
flash();
}
Thank you I finally got the button to work properly but now I'm stuck at making the shape I just create to stay on screen. Every time I click to create new shape I select the other shape I just create disappear. I look at custom paint but still confuse
public class ShapeStamps extends JFrame {
Random numGen = new Random();
public int x;
public int y;
private JPanel mousePanel, Bpanel;
private JButton circle, square, rectangle, oval;
private int choice = 0;
public ShapeStamps() {
super("Shape Stamps");
Bpanel = new JPanel();
circle = new JButton("Circle");
square = new JButton("Square");
rectangle = new JButton("Rectangle");
oval = new JButton("Oval");
circle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 1;
}
});
square.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 2;
}
});
rectangle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 3;
}
});
oval.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
choice = 4;
}
});
mousePanel = new JPanel();
mousePanel.setBackground(Color.WHITE);
MouseHandler handler = new MouseHandler();
setVisible(true);
addMouseListener(handler);
addMouseMotionListener(handler);
add(mousePanel);
Bpanel.add(circle);
Bpanel.add(square);
Bpanel.add(rectangle);
Bpanel.add(oval);
add(Bpanel, BorderLayout.SOUTH);
setSize(500, 500);
setVisible(true);
}
private class MouseHandler extends MouseAdapter implements
MouseMotionListener {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
}
public void paint(Graphics g) {
super.paintComponents(g);
setBounds(0, 0, 500, 500);
Graphics2D g2d = (Graphics2D) g;
if (choice == 0) {
g2d.setFont(new Font("Serif", Font.BOLD, 32));
g2d.drawString("Shape Stamper!", 150, 220);
g2d.setFont(new Font("Serif", Font.ITALIC, 16));
g2d.drawString("Programmed by: None", 150, 245);
}
if (choice == 1) {
Color randomColor1 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor1);
g2d.drawOval(x - 50, y - 50, 100, 100);
}
if (choice == 2) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.drawRect(x - 50, y - 50, 100, 100);
}
if (choice == 3) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Rectangle2D.Double(x - 75, y - 50, 150, 100));
}
if (choice == 4) {
Color randomColor2 = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256));
g2d.setPaint(randomColor2);
g2d.draw(new Ellipse2D.Double(x - 50, y - 25, 100, 50));
}
}
}
Everytime the JFrame gets repainted it will go through the drawing process, somif you stamp something on the screen you would have to have a data structure to hold the "objects" that were stamped. This way, each time the drawing process gets called it will repaint the objects on their correct position (and maybe colors with you decide to change this too)
I have a problem with 2D transformation program
I have the source code
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class House extends JPanel {
MyCanvas canvas;
JSlider sliderTransX, sliderTransY, sliderRotateTheta, sliderRotateX,
sliderRotateY, sliderScaleX, sliderScaleY, sliderWidth;
double transX = 0.0;
double transY = 0.0;
double rotateTheta = 0.0;
double rotateX = 150.0;
double rotateY = 150.0;
double scaleX = 1.0;
double scaleY = 1.0;
float width = 1.0f;
public House() {
super(new BorderLayout());
JPanel controlPanel = new JPanel(new GridLayout(3, 3));
add(controlPanel, BorderLayout.NORTH);
controlPanel.add(new JLabel("Translate(dx,dy): "));
sliderTransX = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 300, 150,
100, 50);
sliderTransY = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 300, 150,
100, 50);
// To control rotation
controlPanel.add(new JLabel("Rotate(Theta,ox,oy): "));
sliderRotateTheta = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 360,
0, 90, 45);
JPanel subPanel = new JPanel();
subPanel.setLayout(new GridLayout(1, 2));
sliderRotateX = setSlider(subPanel, JSlider.HORIZONTAL, 0, 300, 150,
150, 50);
sliderRotateY = setSlider(subPanel, JSlider.HORIZONTAL, 0, 300, 150,
150, 50);
controlPanel.add(subPanel);
// To control scaling
controlPanel.add(new JLabel("Scale(sx,sy)x10E-2:"));
sliderScaleX = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 200, 100,
100, 10);
sliderScaleY = setSlider(controlPanel, JSlider.HORIZONTAL, 0, 200, 100,
100, 10);
// To control width of line segments
JLabel label4 = new JLabel("Width Control:", JLabel.RIGHT);
sliderWidth = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
sliderWidth.setPaintTicks(true);
sliderWidth.setMajorTickSpacing(5);
sliderWidth.setMinorTickSpacing(1);
sliderWidth.setPaintLabels(true);
sliderWidth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
width = sliderWidth.getValue();
canvas.repaint();
}
});
JPanel widthPanel = new JPanel();
widthPanel.setLayout(new GridLayout(1, 2));
widthPanel.add(label4);
widthPanel.add(sliderWidth);
add(widthPanel, BorderLayout.SOUTH);
canvas = new MyCanvas();
add(canvas, "Center");
}
public JSlider setSlider(JPanel panel, int orientation, int minimumValue,
int maximumValue, int initValue, int majorTickSpacing,
int minorTickSpacing) {
JSlider slider = new JSlider(orientation, minimumValue, maximumValue,
initValue);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(majorTickSpacing);
slider.setMinorTickSpacing(minorTickSpacing);
slider.setPaintLabels(true);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider tempSlider = (JSlider) e.getSource();
if (tempSlider.equals(sliderTransX)) {
transX = sliderTransX.getValue() - 150.0;
canvas.repaint();
} else if (tempSlider.equals(sliderTransY)) {
transY = sliderTransY.getValue() - 150.0;
canvas.repaint();
} else if (tempSlider.equals(sliderRotateTheta)) {
rotateTheta = sliderRotateTheta.getValue() * Math.PI / 180;
canvas.repaint();
} else if (tempSlider.equals(sliderRotateX)) {
rotateX = sliderRotateX.getValue();
canvas.repaint();
} else if (tempSlider.equals(sliderRotateY)) {
rotateY = sliderRotateY.getValue();
canvas.repaint();
} else if (tempSlider.equals(sliderScaleX)) {
if (sliderScaleX.getValue() != 0.0) {
scaleX = sliderScaleX.getValue() / 100.0;
canvas.repaint();
}
} else if (tempSlider.equals(sliderScaleY)) {
if (sliderScaleY.getValue() != 0.0) {
scaleY = sliderScaleY.getValue() / 100.0;
canvas.repaint();
}
}
}
});
panel.add(slider);
return slider;
}
class MyCanvas extends Canvas {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.translate(transX, transY);
g2D.rotate(rotateTheta, rotateX, rotateY);
g2D.scale(scaleX, scaleY);
BasicStroke stroke = new BasicStroke(width);
g2D.setStroke(stroke);
drawHome(g2D);
}
public void drawHome(Graphics2D g2D) {
Line2D line1 = new Line2D.Float(100f, 200f, 200f, 200f);
Line2D line2 = new Line2D.Float(100f, 200f, 100f, 100f);
Line2D line3 = new Line2D.Float(100f, 100f, 200f, 100f);
Line2D line5 = new Line2D.Float(200f, 100f, 200f, 200f);
g2D.draw(line1);
g2D.draw(line2);
g2D.draw(line3);
g2D.draw(line5);
}
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.getContentPane().add(new House());
f.setDefaultCloseOperation(1);
f.setSize(700, 550);
f.setVisible(true);
}
}
Please help me.
Don't mix AWT and Swing components needlessly: extend JPanel and override paintComponent(). A call to super.paintComponent(g) will clean up rendering, and RenderingHints will improve rotated drawing.
class MyCanvas extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2D.translate(transX, transY);
g2D.rotate(rotateTheta, rotateX, rotateY);
g2D.scale(scaleX, scaleY);
BasicStroke stroke = new BasicStroke(width);
g2D.setStroke(stroke);
drawHome(g2D);
}
...
}