I'm trying to make a bit of code that has a gui that gets the GCD of of 2 numbers. I keep getting an error when I try to compile my code
Error: Could not find or load main class Gooie.Gooie
Java Result: 1\
Can someone tell me what exactly I'm doing wrong?
my code
package Gooie;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gooie {
public static void main(String[] args) {
JFrame frame = new GcdFrame();
frame.setVisible(true);
}
}
class GcdFrame extends JFrame {
public GcdFrame() {
setTitle("Greatest Common Divisor Finder");
centerWindow(this);
setSize(267, 200);
//setResizable(false);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new GcdPanel();
this.add(panel);
}
private void centerWindow(Window w) {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width - w.getWidth()) / 2,
(d.height - w.getHeight()) / 2);
}
}
class GcdPanel extends JPanel implements ActionListener {
private JTextField xTextField, yTextField,
gcdTextField;
private JLabel xLabel, yLabel, gcdLabel;
private JButton calculateButton, exitButton;
public GcdPanel() {
// display panel
JPanel displayPanel = new JPanel();
// displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
displayPanel.setLayout(new GridLayout(4, 2));
// payment label
xLabel = new JLabel("X:");
displayPanel.add(xLabel);
// payment text field
xTextField = new JTextField(10);
displayPanel.add(xTextField);
// rate label
yLabel = new JLabel("Y:");
displayPanel.add(yLabel);
// rate text field
yTextField = new JTextField(10);
displayPanel.add(yTextField);
// future value label
gcdLabel = new JLabel("GCD:");
displayPanel.add(gcdLabel);
// future value text field
gcdTextField = new JTextField(10);
gcdTextField.setEditable(false);
gcdTextField.setFocusable(false);
displayPanel.add(gcdTextField);
// button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
// calculate button
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
buttonPanel.add(calculateButton);
// exit button
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
// add panels to main panel
this.setLayout(new BorderLayout());
this.add(displayPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == exitButton)
System.exit(0);
else if (source == calculateButton) {
int x = Integer.parseInt(xTextField.getText());
int y = Integer.parseInt(yTextField.getText());
int gcd = greatestCommonDivisor(x, y);
gcdTextField.getText();
}
}
private int greatestCommonDivisor(int x, int y) {
// TODO Auto-generated method stub
while (x != y) {
if (x > y) {
x = x - y;
} else {
y = y - x;
}
}
return y;
}
}
I ran your program in Eclipse and it seems to run fine....no errors ! Download IDE such as eclipse or anything that you like and try to run the program from there.
http://www.eclipse.org/downloads/
https://netbeans.org/
Related
I'm trying to create a program that lists movies in a Netflix style to learn Front-End coding.
How I want it to look in the end:
My guess is that every movie is a button component with an image a name label and a release year label.
I'm struggling to recreate this look. This is how it looks when I try it:
The navigationbar in my image is at the page start of a border layout. Below the navigationbar the movie container is in the center of the border layout.
My idea was creating a GridLayout and then create a button for each movie and adding it to the GridLayout.
You can recreate this with this code:
public class Main {
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel moviePanel = new JPanel();
GridLayout layout = new GridLayout(0, 10);
layout.setHgap(3);
layout.setVgap(3);
moviePanel.setLayout(layout);
moviePanel.setBackground(new Color(32, 32, 32));
ArrayList<String> exampleList = new ArrayList<>();
// Add stuff to the example list
for(int i = 0; i < 120; i++) {
exampleList.add(Integer.toString(i));
}
final File root = new File("");
for(final String movie : exampleList) {
JLabel picLabel = new JLabel();
try {
File imageFile = new File(root.getAbsolutePath() + "\\src\\images\\" + "imageName.jpg"); // Try to find the cover image
if(imageFile.exists()) {
BufferedImage movieCover = ImageIO.read(imageFile);
picLabel = new JLabel(new ImageIcon(movieCover));
} else {
BufferedImage movieCover = ImageIO.read(new File(root.getAbsolutePath() + "\\src\\images\\temp.jpg")); // Get a temp image
picLabel = new JLabel(new ImageIcon(movieCover));
}
} catch (IOException e) {
e.printStackTrace();
}
JLabel movieName = new JLabel("New Movie");
movieName.setForeground(Color.WHITE);;
JButton movieButton = new JButton();
movieButton.setLayout(new GridLayout(0, 1));
//movieButton.setContentAreaFilled(false);
//movieButton.setBorderPainted(false);
//movieButton.setFocusPainted(false);
movieButton.add(picLabel);
movieButton.add(movieName);
moviePanel.add(movieButton);
}
return moviePanel;
}
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
}
I noticed that the GridLayout always tries to fit everything onto the window.
All that's needed is a properly configured JButton in a GridLayout.
E.G.
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 1; ii < 21; ii++) {
JButton picButton = new JButton("Mov " + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
Here is a complete source for the above with a tweak to put the year on a new line. It uses HTML in the JButton to break the button text into two lines.
The input focus is on the first button, whereas the mouse hovers over the '2009' movie:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class MovieGrid {
MovieGrid() {
JFrame f = new JFrame("Movie Grid");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(createMoviePanel());
f.pack();
f.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(
9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 2001; ii < 2021; ii++) {
JButton picButton = new JButton(
"<html>Movie<br>" + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new MovieGrid();
}
};
SwingUtilities.invokeLater(r);
}
}
Same idea's from Andrew Thompson answer but with some minor text alignment changes and hover effect
final class Testing
{
public static void main(String[] args)
{
JFrame frame=new JFrame("NEFLIX");
frame.setContentPane(new GridDisplay());
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final class GridDisplay extends JPanel implements ActionListener
{
private GridDisplay()
{
super(new GridLayout(0,5,20,20));
setBackground(new Color(0,0,0,255));
BufferedImage image=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)image.getGraphics();
g2d.setColor(Color.BLUE);
g2d.fillRect(0,0,image.getWidth(),image.getHeight());
HoverPainter painter=new HoverPainter();
for(int i=0;i<10;i++)
{
TVShowCard card=new TVShowCard(image,"Show "+i,"199"+i);
card.addMouseListener(painter);
add(card);
}
}
//highlight only on hover
private final class HoverPainter extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(false);
}
#Override
public void mouseEntered(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(true);
}
}
private final class TVShowCard extends JButton
{
private TVShowCard(BufferedImage preview,String name,String year)
{
super();
setContentAreaFilled(false);
setBackground(new Color(0,0,0,0));
setFocusPainted(false);
setBorderPainted(false);
//I didn't use image icon & text horizontal alignment because the text always horizontally centered aligned but from the expected output it was left so created 2 labels for the job
setLayout(new GridBagLayout());
addIcon(preview);
addLabel(name,year);
addActionListener(GridDisplay.this);
}
private void addIcon(BufferedImage preview)
{
JLabel icon=new JLabel();
icon.setIcon(new ImageIcon(preview));
add(icon,new GridBagConstraints(0,0,1,1,1.0f,0.0f,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
}
private void addLabel(String name,String year)
{
JLabel label=new JLabel("<html><body>"+name+"<br>"+year+"</body></html>");
label.setForeground(Color.white);
label.setBackground(new Color(0,0,0,0));
add(label,new GridBagConstraints(0,1,1,1,1.0f,1.0f,GridBagConstraints.SOUTHWEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
}
}
#Override
public void actionPerformed(ActionEvent e)
{
TVShowCard card=(TVShowCard)e.getSource();
//do stuff with it
}
}
}
There is 3 panels which I created as seen in the image. The first panel is the "From" panel, second is "To" panel, and third is the buttons panel. So the question is, how can I put a new line for the "Enter Temperature: [ ]" so that it will be under neath the radio buttons? I am very new to Java swing/awt please bear with me.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame{
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion(){
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFromTemp = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// decorate the panel
pnlFromRadioButton.setBorder(BorderFactory.createTitledBorder("From"));
pnlToRadioButton.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlFromRadioButton.add(lblFromTemp);
pnlFromRadioButton.add(txtFromTemp);
pnlToRadioButton.add(lblToTemp);
txtToTemp.setEditable(false);
pnlToRadioButton.add(txtToTemp);
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected())
System.out.print("exit");
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Nest more JPanels and use layout managers
For instance, in the JPanel where you want two lines, give it a BoxLayout oriented along the BoxLayout.PAGE_AXIS, and then add two more JPanels to this BoxLayout-using, a top JPanel with the radio buttons and bottom JPanel with the JLabel and JTextField (or whatever else you want in it).
Side note: this would be a great place to use an enum one called TempScale that had three values: CELSIUS, FAHRENHEIT, KELVIN. You could even give the enum the formulas for conversion to and from Kelvin.
For example:
import java.awt.Component;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class TempConversion2 extends JPanel {
private ToFromPanel fromPanel = new ToFromPanel("From", true);
private ToFromPanel toPanel = new ToFromPanel("To", false);
private ButtonPanel buttonPanel = new ButtonPanel(fromPanel, toPanel);
public TempConversion2() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(fromPanel);
add(toPanel);
add(buttonPanel);
}
private static void createAndShowGui() {
TempConversion2 mainPanel = new TempConversion2();
JFrame frame = new JFrame("Temp Convert");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
public ButtonPanel(ToFromPanel fromPanel, ToFromPanel toPanel) {
add(new JButton(new ConvertAction("Convert", fromPanel, toPanel)));
add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
}
}
#SuppressWarnings("serial")
class ConvertAction extends AbstractAction {
private ToFromPanel fromPanel;
private ToFromPanel toPanel;
public ConvertAction(String name, ToFromPanel fromPanel, ToFromPanel toPanel) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
this.fromPanel = fromPanel;
this.toPanel = toPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = fromPanel.getText();
try {
double fromTemp = Double.parseDouble(text.trim());
TempScale fromScale = fromPanel.getTempScalesPanel().getSelectedTempScale();
double kelvinValue = fromScale.convertToKelvin(fromTemp);
TempScale toScale = toPanel.getTempScalesPanel().getSelectedTempScale();
double toValue = toScale.convertFromKelvin(kelvinValue);
String toValueString = String.format("%.2f", toValue);
toPanel.setText(toValueString);
} catch (NumberFormatException e1) {
Component parentComponent = fromPanel;
String message = "Text must be a valid number: " + text;
String title = "Invalid Text Entered";
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parentComponent, message, title, messageType);
fromPanel.setText("");
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
#SuppressWarnings("serial")
class ToFromPanel extends JPanel {
private String title;
private TempScalesPanel tempScalesPanel = new TempScalesPanel();
private JTextField tempTextField = new JTextField(3);
public ToFromPanel(String title, boolean textFieldEnabled) {
this.title = title;
tempTextField.setFocusable(textFieldEnabled);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
bottomPanel.add(new JLabel("Temperature:"));
bottomPanel.add(Box.createHorizontalStrut(8));
bottomPanel.add(tempTextField);
setBorder(BorderFactory.createTitledBorder(title));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(tempScalesPanel);
add(bottomPanel);
}
public String getTitle() {
return title;
}
public TempScalesPanel getTempScalesPanel() {
return tempScalesPanel;
}
public String getText() {
return tempTextField.getText();
}
public void setText(String text) {
tempTextField.setText(text);
}
}
#SuppressWarnings("serial")
class TempScalesPanel extends JPanel {
private ButtonGroup buttonGroup = new ButtonGroup();
private Map<ButtonModel, TempScale> buttonTempMap = new HashMap<>();
public TempScalesPanel() {
for (TempScale tempScale : TempScale.values()) {
JRadioButton radioButton = new JRadioButton(tempScale.getName());
add(radioButton);
buttonGroup.add(radioButton);
buttonTempMap.put(radioButton.getModel(), tempScale);
// set first button as selected by default
if (buttonGroup.getSelection() == null) {
buttonGroup.setSelected(radioButton.getModel(), true);
}
}
}
public TempScale getSelectedTempScale() {
ButtonModel model = buttonGroup.getSelection();
return buttonTempMap.get(model);
}
}
This is the enum that I was talking about. Note that if you change the enum, and for instance add another temperature scale element, the program will automatically include it in the GUI and in the calculations. God I love Java and OOP.
public enum TempScale {
CELSIUS("Celsius", 1.0, -273.15),
FAHRENHEIT("Fahrenheit", 5.0 / 9.0, -459.67),
KELVIN("Kelvin", 1.0, 0.0);
private TempScale(String name, double ratioToKelvin, double absZero) {
this.name = name;
this.ratioToKelvin = ratioToKelvin;
this.absZero = absZero;
}
private String name;
private double ratioToKelvin;
private double absZero;
public String getName() {
return name;
}
public double getRatioToKelvin() {
return ratioToKelvin;
}
public double getAbsZero() {
return absZero;
}
public double convertToKelvin(double value) {
return (value - absZero) * ratioToKelvin;
}
public double convertFromKelvin(double kelvinValue) {
return (kelvinValue / ratioToKelvin) + absZero;
}
}
Always consider posting an MCVE.
For example you layout can be simplified and demonstrated with :
import java.awt.BorderLayout;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TemperatureConversion extends JFrame{
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
// constructor
public TemperatureConversion(){
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Suppose you want to an "Enter Temperature: [ ]" label to show in a different "line" under From buttons, your constructor will change to :
public TemperatureConversion(){
//set a layout manger. You could use grid layout
//GridLayout gridLayout = new GridLayout(4, 1);
//Or BoxLayout
BoxLayout boxLayout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS); // top to bottom
setLayout(boxLayout);
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
//create a panel to hold the desired label
pnlFromTemp = new JPanel();
pnlFromTemp.add(new JLabel("Enter Temperature: [ ]"));//add label
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
//the panel will show in the order added
add(pnlFromRadioButton);
add(pnlFromTemp);
add(pnlToRadioButton);
add(pnlButton);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Sorry I am new to forums and am not familiar with posting etiquette for codes #c0der. But using GridLayout solved my problem and I want to show you what I did, it is a big mess but here it is. Here is my bizarre code but don't know how to reduce it any further. This is how it is suppose to look as I wanted and because now I understand what you mean by "Nest more JPanels and use layout managers" #Hovercraft Full of Eels:
my temperature program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame {
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp, lblToTempbox;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFrom, pnlTo, pnlButton;
JPanel pnlEnterTemp, pnlComparableTemp;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion() {
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFrom = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
pnlTo = new JPanel();
pnlEnterTemp = new JPanel();
pnlComparableTemp = new JPanel();
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFrom.setLayout(new GridLayout(2, 1));
pnlFrom.add(pnlFromRadioButton);
pnlFrom.add(pnlEnterTemp);
pnlTo.setLayout(new GridLayout(2, 1));
pnlTo.add(pnlToRadioButton);
pnlTo.add(pnlComparableTemp);
// decorate the panel
pnlFrom.setBorder(BorderFactory.createTitledBorder("From"));
pnlTo.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlEnterTemp.add(lblFromTemp);
pnlEnterTemp.add(txtFromTemp);
pnlComparableTemp.add(lblToTemp);
txtToTemp.setEditable(false);
pnlComparableTemp.add(txtToTemp);
// add panels to the frame
add(pnlFrom, BorderLayout.NORTH);
add(pnlTo, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected() && radToFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int celsius = strInput * 9 / 5 + 32;
txtToTemp.setText(Integer.toString(celsius));
} else if (radFromCelsius.isSelected() && radToCelsius.isSelected() ||
radFromFahrenheit.isSelected() && radToFahrenheit.isSelected() ||
radFromKelvin.isSelected() && radToKelvin.isSelected()) {
txtToTemp.setText(txtFromTemp.getText());
} else if (radToCelsius.isSelected() && radFromFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int fahrenheit = (strInput - 32) * 5 / 9;
txtToTemp.setText(Integer.toString(fahrenheit));
} else if (radFromKelvin.isSelected() && radToCelsius.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput - 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromKelvin.isSelected() && radToFahrenheit.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput - 459.67;
txtToTemp.setText(Double.toString(fahrenheit));
} else if (radFromCelsius.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput + 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromFahrenheit.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput + 255.37;
txtToTemp.setText(Double.toString(fahrenheit));
}
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
By the way #Hovercraft Full Of Eels, your solution is way more efficient and advanced than my level of thinking. I am newbie to programming in general so bear with me on my messy code and organization lol. I have barely dipped my feet into OOP. I do have a sense of how you used enum for TempScale and I thank you for your suggestion. I will keep these in my notes as references.
I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}
I am trying to get the code below to display the coordinates in info_panel but it is not working. How would I get the coordinates from the mouseListener from SimpleFrameViewWidget to be displayed in the info_panel? I am using setText right now... Thanks!
public static void main(String[] args) throws IOException {
Frame f = A7Helper.readFromURL("http://www.cs.unc.edu/~kmp/kmp.jpg");
f.setTitle("");
SimpleFrameViewWidget simple_widget = new SimpleFrameViewWidget(f);
JFrame main_frame = new JFrame();
main_frame.setTitle("Assignment 7 Pixel Inspector");
main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel top_panel = new JPanel();
top_panel.setLayout(new BorderLayout());
top_panel.add(simple_widget, BorderLayout.CENTER);
main_frame.setContentPane(top_panel);
JPanel info_panel = new JPanel();
info_panel.setLayout(new BorderLayout());
top_panel.add(info_panel, BorderLayout.SOUTH);
JLabel x_label = new JLabel("");
x_label.setHorizontalAlignment(SwingConstants.CENTER);
x_label.addMouseListener(simple_widget);
x_label.setText(simple_widget.getStringInfo());
info_panel.add(x_label);
main_frame.setContentPane(top_panel);
main_frame.pack();
main_frame.setVisible(true);
}
This is the code that has the mouseListener and mouseClick. Thanks in advance!
public class SimpleFrameViewWidget extends JPanel implements MouseListener {
private FrameView frame_view;
private String stringInfo;
public SimpleFrameViewWidget(Frame f) {
setLayout(new BorderLayout());
frame_view = new FrameView(f);
frame_view.addMouseListener(this);
add(frame_view, BorderLayout.CENTER);
JLabel title_label = new JLabel(f.getTitle());
add(title_label, BorderLayout.SOUTH);
}
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
stringInfo = "X: " + x + "Y: " + y;
}
public String getStringInfo(){
return stringInfo;
}
You Could...
Register another MouseListener to SimpleFrameViewWidget that simply feed the results directly to info_panel or have info_panel do it all for you....
Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png