I am pretty new to using swing, and I have a question. My code stopped working this morning, but I don't know why. I ran the debugger, and it says 2 lines of code. One is in the main class, one is in the other. They are both creating instances of each other.
The lines are something like this:
Main Class:
OnePlayerFrame OnePFrame = new OnePlayerFrame();
OnePlayerFrame Class:
MainFrame MainClass = new MainFrame();
I hope you can understand what I'm saying, as I said I'm pretty new to swing.
Thanks
-Matt
Ok, here is the whole thing:
Right, forgot to mention, I may have deleted a simple line of code and am overlooking it, so please stay calm if it's something simple :)
Main Class:
package rockpaperscissors;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame {
public JFrame frame = new JFrame();
private final ImageIcon rock = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/rock.jpg");
private final ImageIcon paper = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/paper.png");
private final ImageIcon scissors = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/scissors.png");
private final JLabel rockLabel = new JLabel();
private final JLabel paperLabel = new JLabel();
private final JLabel scissorsLabel = new JLabel();
private final JPanel panel1 = new JPanel();
private final JPanel panel2 = new JPanel();
private final JPanel panel3 = new JPanel();
private final JPanel empty1 = new JPanel();
private final JPanel empty2 = new JPanel();
private final JPanel empty3 = new JPanel();
private final JPanel empty4 = new JPanel();
private final JPanel empty5 = new JPanel();
OnePlayerFrame OnePlayerFrame = new OnePlayerFrame();
public JButton btn1 = new JButton("1 Player");
private final JTextField text = new JTextField();
private final Font font = new Font("Showcard Gothic Regular", Font.BOLD, 28);
public MainFrame(){
frame.setSize(360, 300);
frame.setAlwaysOnTop(false);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.setLayout(new GridLayout(3, 1));
panel1.setLayout(new GridLayout(1, 3));
panel1.add(rockLabel);
panel1.add(paperLabel);
panel1.add(scissorsLabel);
panel1.setBackground(Color.WHITE);
panel2.setLayout(new GridLayout(2, 3));
panel2.add(empty1);
panel2.add(empty2);
panel2.add(empty3);
panel2.add(empty4);
panel2.add(btn1);
panel2.add(empty5);
panel3.add(text);
panel3.setBackground(Color.WHITE);
empty1.setBackground(Color.WHITE);
empty2.setBackground(Color.WHITE);
empty3.setBackground(Color.WHITE);
empty4.setBackground(Color.WHITE);
empty5.setBackground(Color.WHITE);
text.setText("Rock Paper Scissors");
text.setFont(font);
text.setPreferredSize(new Dimension(360, 80));
text.setEditable(false);
text.setBorder(null);
text.setHorizontalAlignment(JTextField.CENTER);
text.setBackground(Color.WHITE);
rockLabel.setIcon(rock);
paperLabel.setIcon(paper);
scissorsLabel.setIcon(scissors);
btn1.setFocusPainted(false);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frame.dispose();
OnePlayerFrame.startGame1();
}
});
}
public static void main(String[] args) {
new MainFrame();
}
}
And here is the second class:
package rockpaperscissors;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class OnePlayerFrame {
MainFrame MainClass = new MainFrame();
JFrame gameFrame = new JFrame();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
JPanel panel9 = new JPanel();
JPanel empty1 = new JPanel();
JPanel empty2 = new JPanel();
JTextField playerText1 = new JTextField();
JTextField playerText2 = new JTextField();
JTextField playerText3 = new JTextField();
JTextField compText1 = new JTextField();
JTextField compText2 = new JTextField();
JTextField compText3 = new JTextField();
JTextField pChoose = new JTextField();
JTextField cChoose = new JTextField();
JButton btn1 = new JButton("Rock");
JButton btn2 = new JButton("Paper");
JButton btn3 = new JButton("Scissors");
JButton btn4 = new JButton("Confirm");
JButton btn5 = new JButton("Fight!");
JButton getB = new JButton();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
boolean confirmed = false;
boolean hasSelected = false;
boolean runThread = true;
String playerMove;
ImageIcon playerIcon = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/question-mark.jpg");
ImageIcon computerIcon = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/question-mark.jpg");
Font font = new Font("Showcard Gothic Regular", Font.BOLD, 18);
public OnePlayerFrame(){
gameFrame.setVisible(true);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setSize(500, 400);
gameFrame.setLocationRelativeTo(MainClass.frame);
gameFrame.setLayout(new GridLayout(3, 1));
gameFrame.add(panel1);
gameFrame.add(panel2);
gameFrame.add(panel3);
MainClass.frame.dispose();
panel1.setBackground(Color.WHITE);
panel1.setLayout(new GridLayout(1, 4));
panel1.add(panel4);
panel1.add(panel5);
panel1.add(panel6);
panel1.add(panel7);
panel2.setBackground(Color.WHITE);
panel2.setLayout(new GridLayout(3, 1));
panel2.add(pChoose);
panel2.add(panel8);
panel2.add(btn4);
panel3.setBackground(Color.WHITE);
panel3.add(cChoose);
panel3.add(panel9);
panel3.setLayout(new GridLayout(2, 1));
panel4.setBackground(Color.WHITE);
panel4.add(playerText1);
panel4.add(playerText2);
panel4.add(playerText3);
panel4.setLayout(new GridLayout(3, 1));
panel5.setBackground(Color.WHITE);
panel5.add(label1);
panel6.setBackground(Color.WHITE);
panel6.add(label2);
panel7.setBackground(Color.WHITE);
panel7.add(compText1);
panel7.add(compText2);
panel7.add(compText3);
panel7.setLayout(new GridLayout(3, 1));
panel8.setLayout(new GridLayout(1, 3));
panel8.add(btn1);
panel8.add(btn2);
panel8.add(btn3);
panel9.setLayout(new GridLayout(1, 3));
panel9.setBackground(Color.WHITE);
panel9.add(empty1);
panel9.add(btn5);
panel9.add(empty2);
empty1.setBackground(Color.WHITE);
empty2.setBackground(Color.WHITE);
playerText1.setEditable(false);
playerText1.setBorder(null);
playerText1.setText("Player");
playerText1.setBackground(Color.WHITE);
playerText1.setFont(font);
playerText1.setHorizontalAlignment(JTextField.CENTER);
playerText2.setEditable(false);
playerText2.setBorder(null);
playerText2.setText("Chose");
playerText2.setBackground(Color.WHITE);
playerText2.setFont(font);
playerText2.setHorizontalAlignment(JTextField.CENTER);
playerText3.setEditable(false);
playerText3.setBorder(null);
playerText3.setText("====>");
playerText3.setBackground(Color.WHITE);
playerText3.setFont(font);
playerText3.setHorizontalAlignment(JTextField.CENTER);
compText1.setEditable(false);
compText1.setBorder(null);
compText1.setText("Computer");
compText1.setBackground(Color.WHITE);
compText1.setFont(font);
compText1.setHorizontalAlignment(JTextField.CENTER);
compText2.setEditable(false);
compText2.setBorder(null);
compText2.setText("Chose");
compText2.setBackground(Color.WHITE);
compText2.setFont(font);
compText2.setHorizontalAlignment(JTextField.CENTER);
compText3.setEditable(false);
compText3.setBorder(null);
compText3.setText("<====");
compText3.setBackground(Color.WHITE);
compText3.setFont(font);
compText3.setHorizontalAlignment(JTextField.CENTER);
pChoose.setEditable(false);
pChoose.setBorder(null);
pChoose.setText("Choose your move");
pChoose.setFont(font);
pChoose.setHorizontalAlignment(JTextField.CENTER);
pChoose.setBackground(Color.WHITE);
cChoose.setEditable(false);
cChoose.setBorder(null);
cChoose.setText("Computer is choosing");
cChoose.setFont(font);
cChoose.setHorizontalAlignment(JTextField.CENTER);
cChoose.setBackground(Color.WHITE);
btn1.setRolloverEnabled(true);
btn1.setFocusPainted(false);
btn2.setFocusPainted(false);
btn2.setRolloverEnabled(true);
btn3.setFocusPainted(false);
btn3.setRolloverEnabled(true);
btn4.setFocusPainted(false);
btn4.setRolloverEnabled(true);
btn5.setFocusPainted(false);
btn5.setRolloverEnabled(true);
btn5.setVisible(false);
btn5.setFont(font);
label1.setIcon(playerIcon);
label2.setIcon(computerIcon);
}
public void startGame1(){
new Thread(new Runnable() {
public void run() {
while(confirmed == true || confirmed == false){
if(confirmed == false){
try{
if(confirmed == false){
cChoose.setText("Computer is choosing");
Thread.sleep(500);
}
if(confirmed == false){
cChoose.setText("Computer is choosing.");
Thread.sleep(500);
}
if(confirmed == false){
cChoose.setText("Computer is choosing..");
Thread.sleep(500);
}
if(confirmed == false){
cChoose.setText("Computer is choosing...");
Thread.sleep(500);
}
}
catch(Exception e){
gameFrame.dispose();
}
}
if(confirmed == true){
cChoose.setText("Computer has chosen!");
fightButtonSet();
}
}
}
}).start();
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(confirmed == false){
playerMove = btn1.getText();
hasSelected = true;
pChoose.setText("You have selected rock");
getB = btn1;
}
else{
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
});
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(confirmed == false){
playerMove = btn2.getText();
hasSelected = true;
pChoose.setText("You have selected paper");
getB = btn2;
}
else{
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
});
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(confirmed == false){
playerMove = btn3.getText();
hasSelected = true;
pChoose.setText("You have selected scissors");
getB = btn3;
}
else{
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
});
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(hasSelected == true && confirmed == false){
confirmed = true;
pChoose.setText("You have confirmed " + getB.getText().toLowerCase() + "!");
cChoose.setText("Computer has chosen!");
}
else{
if(hasSelected == false){
pChoose.setText("You haven't selected anything yet!");
}
else if (confirmed == true){
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
}
});
}
public void fightButtonSet(){
btn5.setVisible(true);
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
FIGHT();
}
});
}
public void FIGHT(){
if(getB.getText().equalsIgnoreCase("Rock")){
}
if(getB.getText().equalsIgnoreCase("Paper")){
}
if(getB.getText().equalsIgnoreCase("Scissors")){
}
}
}
We can abstract a little you have this.
public class TestCircularDependency {
static class A{
B b = new B();
}
static class B{
A a = new A();
}
public static void main(String args[]){
A a = new A();
}
}
This will throw a StackOverflowError. You have a circular dependency. The problem is that you are instance each one in constructor then you have infinite recursion.
In java you can have circular dependency but not in object creation. You can do something like this.
public class TestCircularDependency {
static class A{
B b;
}
static class B{
A a;
}
public static void main(String args[]){
A a = new A();
a.b = new B();
b.a= a;
}
}
Related
import javax.swing.*; // Graphics import java.awt.Color; // Graphics Colors
import java.awt.event.ActionListener; // Events
import java.awt.event.ActionEvent; // Events
public class ButtonDemo_Extended implements ActionListener {
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel, redScore, blueScore;
JButton redButton, blueButton, resetButton;
public JPanel createContentPane() {
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(10, 10);
titlePanel.setSize(250, 30);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(0, 0);
redLabel.setSize(120, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(130, 0);
blueLabel.setSize(120, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(260, 30);
totalGUI.add(scorePanel);
redScore = new JLabel("" + redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(120, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
blueScore = new JLabel("" + blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(120, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(260, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(120, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(130, 0);
blueButton.setSize(120, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 40);
resetButton.setSize(250, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redButton) {
redScoreAmount = redScoreAmount + 1;
redScore.setText("" + redScoreAmount);
JOptionPane.showMessageDialog(buttonPanel, "GOOOOOOOOOOOL");
} else if (e.getSource() == blueButton) {
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText("" + blueScoreAmount);
JOptionPane.showMessageDialog(buttonPanel, "GOOOOOOOOOOOL");
} else if (e.getSource() == resetButton) {
redScoreAmount = 0;
blueScoreAmount = 0;
redScore.setText("" + redScoreAmount);
blueScore.setText("" + blueScoreAmount);
}
}
private static void createAndShowGUI() { // For this Class Onlyyyyyyyyyyyy .
JFrame.setDefaultLookAndFeelDecorated(true); // Style Of Frame
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 190);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
} }
this might be one way to do it:
`
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AutoCloseJOption {
private static final int TIME_VISIBLE = 3000;
public static void main(String[] args) {
final JFrame frame1 = new JFrame("My App");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(100, 100);
frame1.setLocation(100, 100);
JButton button = new JButton("My Button");
frame1.getContentPane().add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = new JOptionPane("Message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(null, "Title");
dialog.setModal(false);
dialog.setVisible(true);
new Timer(TIME_VISIBLE, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
}).start();
}
});
frame1.setVisible(true);
}
}`
I hope this helps you
I am receiving this error when i change items in the Jcombobox, nothing breaks it just shows this error, is there anyway to just throw it so it doesn't show up. everything still works fine, but if you wish to have a look at the code. i will post below.
Error message:
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:2056)
at java.awt.Component.getLocationOnScreen(Component.java:2030)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:395)
at sun.lwawt.macosx.CAccessibility$23.call(CAccessibility.java:393)
at sun.lwawt.macosx.LWCToolkit$CallableWrapper.run(LWCToolkit.java:538)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301)
And my code which i don't know which section to show so its all their.
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
public class TouchOn extends JDialog {
private JPanel mainPanel;
public ArrayList Reader(String Txtfile) {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File(Txtfile);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
if(!line.contains("*")){
Trains.add(line + "\n");
}
stringBuffer.append("\n");
}
fileReader.close();
//Arrays.asList(Trains).stream().forEach(s -> System.out.println(s));
return Trains;
} catch (IOException e) {
e.printStackTrace();
}
//return toString();
return null;
}
public TouchOn()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
JTextField touchOnTimeFieldhour = new JTextField();
JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
apply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if(belgrave.isSelected()){
String trainline = belgrave.getText();
}
if(glenwaverly.isSelected()){
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10,10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
Don't create multiple JComboBoxes and then swap visibility. Instead use one JComboBox and create multiple combo box models, such as by using DefaultComboBoxModel<String>, and then swap out the model that it holds by using its setModel(...) method. Problem solved.
Note that using a variation on your code -- I'm not able to reproduce your problem:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFoo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGui();
}
});
}
public static void createAndDisplayGui() {
final JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent evt) {
TouchOn2 touchOn2 = new TouchOn2(frame);
touchOn2.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class TouchOn2 extends JDialog {
private JPanel mainPanel;
#SuppressWarnings({ "rawtypes", "unused" })
public ArrayList Reader(String Txtfile) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add("Data String Number " + (i + 1));
}
// return toString();
// !! return null;
return list;
}
public TouchOn2(Window owner) {
super(owner);
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 300);
setVisible(true);
}
#SuppressWarnings("unchecked")
public void setPanels() {
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JLabel startDay = new JLabel("Day:");
final JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
final JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
final JTextField sYear = new JTextField("2015");
final String trainline = "";
JLabel touchOnTimehr = new JLabel("Time Hour: ");
JLabel touchOnTimem = new JLabel("Time Minute:");
JLabel station = new JLabel("Station: ");
final JTextField touchOnTimeFieldhour = new JTextField();
final JTextField touchOnTimeFieldminute = new JTextField();
JPanel lowerPanel = new JPanel(new FlowLayout());
ArrayList<String> stations = Reader("TrainLines.txt");
final JComboBox<String> cb = new JComboBox<>(
stations.toArray(new String[stations.size()]));
final JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
final JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on");
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
apply.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e) {
String timestamp = new java.text.SimpleDateFormat("dd/MM/yyyy")
.format(new Date());
String day = sDay.getText();
String month = sMonth.getText();
String year = sYear.getText();
String hour = touchOnTimeFieldhour.getText();
String minute = touchOnTimeFieldminute.getText();
if (belgrave.isSelected()) {
// !! ***** note you're shadowing variables here!!!! ****
String trainline = belgrave.getText();
}
if (glenwaverly.isSelected()) {
// !! and here too
String trainline = glenwaverly.getText();
}
System.out.println(trainline);
}
});
cb.setVisible(true);
bG.add(belgrave);
bG.add(glenwaverly);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(touchOnTimehr);
mainPanel.add(touchOnTimeFieldhour);
mainPanel.add(touchOnTimem);
mainPanel.add(touchOnTimeFieldminute);
mainPanel.add(belgrave);
mainPanel.add(glenwaverly);
mainPanel.add(station);
mainPanel.add(new JLabel());
mainPanel.add(cb);
lowerPanel.add(apply);
lowerPanel.add(cancel);
touchOnTimeFieldhour.setSize(10, 10);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
}
}
I am writing a stock control system program for a school project. This is the last thing I need to do, but seeing as I am a relative Java noob, I kindly request your assistance.
I have a DisplayRecord class, which is created by taking String input from a "search" JTextField in the Search class, finding the Object (Product p) it's linked to, and passing it to the displayRecord method. This part works perfectly.
I want to take that Product p and pass it to the EditProduct class or the DeleteRecord class (depending on the JButton pressed) so the user can then edit the Name, Quantity or Cost of that same Product. Here are my DisplayRecord, EditProduct and DeleteRecord classes. I have no idea what to do.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
public class DisplayRecord extends JFrame implements ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JFrame showWindow;
private JPanel top, bot;
private JPanel barcodePanel1 = new JPanel();
private JPanel barcodePanel2 = new JPanel();
private JPanel namePanel1 = new JPanel();
private JPanel namePanel2 = new JPanel();
private JPanel descPanel1 = new JPanel();
private JPanel descPanel2 = new JPanel();
private JPanel compPanel1 = new JPanel();
private JPanel compPanel2 = new JPanel();
private JPanel ratingPanel1 = new JPanel();
private JPanel ratingPanel2 = new JPanel();
private JPanel costPanel1 = new JPanel();
private JPanel costPanel2 = new JPanel();
private JPanel quantityPanel1 = new JPanel();
private JPanel quantityPanel2 = new JPanel();
private JLabel barcodeLabel = new JLabel();
private JLabel nameLabel = new JLabel();
private JLabel descLabel = new JLabel();
private JLabel compLabel = new JLabel();
private JLabel ratingLabel = new JLabel();
private JLabel costLabel = new JLabel();
private JLabel quantityLabel = new JLabel();
private GridLayout displayLayout;
JButton edit = new JButton("Edit");
JButton backToMenu = new JButton("Back to Menu");
JButton delete = new JButton("Delete");
public DisplayRecord() {
stocks = new StockList();
list = stocks.getList();
try {
stocks.load();
} catch (IOException ex) {
System.out.println("Cannot load file");
}
}
public void displayRecord(Product p) {
this.setTitle("Displaying one record");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 350));
top = new JPanel();
displayLayout = new GridLayout(7, 2, 2, 2);
top.setLayout(displayLayout);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
barcodeLabel.setText("Barcode: ");
nameLabel.setText("Name: ");
descLabel.setText("Description: ");
compLabel.setText("Developer: ");
ratingLabel.setText("EU Rating: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity in Stock: ");
JLabel barcodeField = new JLabel(Long.toString(p.getBarcode()));
JLabel nameField = new JLabel(p.getName());
JLabel descField = new JLabel(p.getDesc());
JLabel compField = new JLabel(p.getCompany());
JLabel ratingField = new JLabel(p.getRating());
JLabel costField = new JLabel(Double.toString(p.getCost()));
JLabel quantityField = new JLabel(Integer.toString(p.getQuantity()));
barcodePanel1.add(barcodeLabel);
barcodePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
barcodePanel2.add(barcodeField); barcodePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel1.add(nameLabel);
namePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel2.add(nameField);
namePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel1.add(descLabel);
descPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel2.add(descField);
descPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel1.add(compLabel);
compPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel2.add(compField);
compPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel1.add(ratingLabel);
ratingPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel2.add(ratingField);
ratingPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel1.add(costLabel);
costPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel2.add(costField);
costPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel1.add(quantityLabel);
quantityPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel2.add(quantityField);
quantityPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
top.add(barcodePanel1);
top.add(barcodePanel2);
top.add(namePanel1);
top.add(namePanel2);
top.add(descPanel1);
top.add(descPanel2);
top.add(compPanel1);
top.add(compPanel2);
top.add(ratingPanel1);
top.add(ratingPanel2);
top.add(costPanel1);
top.add(costPanel2);
top.add(quantityPanel1);
top.add(quantityPanel2);
edit.addActionListener(this);
delete.addActionListener(this);
backToMenu.addActionListener(this);
bot.add(edit);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(delete);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(backToMenu);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) { // here is where I'd LIKE to pass Product p as parameter but obviously that's not a thing
if (e.getSource() == edit) {
// EditProduct ed = new EditProduct(); <- hypothetical!
// ed.editProduct(p);
} else if (e.getSource() == delete) {
// DeleteRecord del = new DeleteRecord(); <- hypothetical!
// del.deleteRecord(p);
} else if (e.getSource() == backToMenu) {
new CreateDisplay();
this.dispose();
}
}
}
My EditProduct class:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class EditProduct extends JFrame implements FocusListener, ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JPanel top, bot;
JLabel nameLabel, costLabel, quantityLabel = new JLabel();
JTextField nameField, costField, quantityField = new JTextField();
JButton save, quit = new JButton();
private GridLayout topLayout;
public EditProduct() {
stocks = new StockList();
list = stocks.getList();
}
public void editProduct(Product p) {
this.setTitle("Editing a Product");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 250));
top = new JPanel();
topLayout = new GridLayout(3, 2, 5, 5);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
top.setLayout(topLayout);
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
nameLabel.setText("Name: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity: ");
top.add(nameLabel);
top.add(costLabel);
top.add(quantityLabel);
nameField = new JTextField(p.getName());
costField = new JTextField(String.valueOf(p.getCost()));
quantityField = new JTextField(p.getQuantity());
nameField.addFocusListener(this);
costField.addFocusListener(this);
quantityField.addFocusListener(this);
save.setText("Save");
save.addActionListener(this);
quit.setText("Quit");
quit.addActionListener(this);
bot.add(save);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(quit);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void focusGained(FocusEvent e) {
if (e.getSource() == nameField) {
nameField.setText("");
} else if (e.getSource() == costField) {
costField.setText("");
} else if (e.getSource() == quantityField) {
quantityField.setText("");
}
}
#Override
public void focusLost(FocusEvent fe) {
//do nothing
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == save) {
String newName = nameField.getText();
double newCost = Double.parseDouble(costField.getText());
int newQty = Integer.parseInt(quantityField.getText());
stocks.editProduct(newName, newCost, newQty);
this.dispose();
JOptionPane.showMessageDialog(null, "Changes have been saved!", "Saved!", JOptionPane.PLAIN_MESSAGE);
} else if (e.getSource() == quit) {
}
}
}
Aaand the DeleteRecord class:
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class DeleteRecord {
private StockList stocks;
private ArrayList<Product> list;
public DeleteRecord() {
stocks = new StockList();
list = stocks.getList();
}
public DeleteRecord(Product p) {
String title = "Are you sure you want to delete " + p.getName() + "?";
if (JOptionPane.showConfirmDialog(null, title, "Deleting...", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
stocks.deleteRecord(p);
} else {
new CreateDisplay();
}
}
}
I'm sorry for the massive post and text wall but I honestly have no idea where my problem is or how to work around this problem (and I'm also new to StackOverflow). Can anyone help me?
It seems to me that DisplayRecord can only display one Product at a time. If that is indeed the case, you can store that Product in a field and then access it from actionPerfomed().
In this program, I am trying to select images from users using filechooser and then displaying those images. By default I added 2 images. When I add more images it doesn't display?
Below is my entire code
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class CLayout {
JFrame frame = new JFrame("CardLayout demo");
JPanel panelCont = new JPanel();
LoginView log = new LoginView();
JPanel Img = new ImageGallery();
CardLayout cl = new CardLayout();
public CLayout() {
panelCont.setLayout(cl);
log.setLayout(new BoxLayout(log, BoxLayout.PAGE_AXIS));
Img.setLayout(new BoxLayout(Img, BoxLayout.PAGE_AXIS));
panelCont.add(log, "1");
panelCont.add(Img, "2");
cl.show(panelCont, "1");
ActionListener loginListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userName = log.getUserName();
char[] password = log.getPassword();
String pass=new String(password);
if (LoginView.LOGIN.equals(e.getActionCommand())) {
if(userName.equals("imagegallery")&& pass.equals("12345"))
cl.show(panelCont, "2");
}
}
};
log.addActionListener(loginListener);
frame.add(panelCont);
frame.setSize(800,600);
frame.setTitle(" Image Gallery ");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CLayout();
}
});
}
}
class ImageGallery extends JPanel {
private ImageIcon myImage1 = new ImageIcon ("Chrysanthemum.jpg");
private ImageIcon myImage2 = new ImageIcon ("Desert.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages =new ImageIcon[10];
private int curImageIndex=0;
private int count=0;
private int total=1;
public ImageGallery () {
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
add(ImageGallery, BorderLayout.CENTER);
JButton PREVIOUS = new JButton ("Previous");
JButton NEXT = new JButton ("Next");
JDialog.setDefaultLookAndFeelDecorated(true);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName().toString());
ImageIcon tImage=new ImageIcon("selectedFile.getName().toString()");
System.out.println(myImages.length);
int n=2+count;
myImages[n]=tImage;
total=total+count+1;
count++;
System.out.println(total+" "+count);
}
}
});
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,3));
add(Menu, BorderLayout.NORTH);
Menu.add(PREVIOUS);
Menu.add(NEXT);
Menu.add(button);
//register listener
PreviousButtonListener PreviousButton = new PreviousButtonListener ();
NextButtonListener NextButton = new NextButtonListener ();
//add listeners to corresponding componenets
PREVIOUS.addActionListener(PreviousButton);
NEXT.addActionListener(NextButton);
}
class PreviousButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(curImageIndex>0 && curImageIndex <=total) {
ImageGallery.remove(0);
curImageIndex=curImageIndex-1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
} else {
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage1));
curImageIndex=0;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
class NextButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(curImageIndex>=0 && curImageIndex <total){
ImageGallery.remove(0);
curImageIndex = curImageIndex + 1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
} else {
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImages[total]));
curImageIndex=total ;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
}
class LoginView extends JPanel {
JLabel userLabel = new JLabel("User");
JTextField userText = new JTextField(20);
JLabel passwordLabel = new JLabel("Password");
JPasswordField passwordText = new JPasswordField(20);
private final JButton loginButton;
private final JButton registerButton;
public static final String LOGIN = "Login";
public static final String REGISTER = "Regster";
public LoginView() {
setLayout(new GridLayout(0, 2));
userLabel.setBounds(10, 10, 80, 25);
add(userLabel);
userText.setBounds(10, 10, 60, 25);
add(userText);
passwordLabel.setBounds(10, 40, 80, 25);
add(passwordLabel);
passwordText.setBounds(100, 40, 160, 25);
add(passwordText);
loginButton = new JButton("login");
loginButton.setActionCommand(LOGIN);
registerButton = new JButton("register");
registerButton.setActionCommand(REGISTER);
add(loginButton);
}
public void addActionListener(ActionListener listener) {
loginButton.addActionListener(listener);
registerButton.addActionListener(listener);
}
public String getUserName() {
return userText.getText();
}
public char[] getPassword() {
return passwordText.getPassword();
}
}
Problem is in this line
ImageIcon tImage=new ImageIcon("selectedFile.getName().toString()");
you need to remove double-quotes in order to read actual file name.
ImageIcon tImage=new ImageIcon(selectedFile.getName().toString());
Hope this helps.
My program is about a supermarket. I want to position the JButton 'b1' just below JLabel 'l1' and also below JTextField 'jt1'. I want the JButton 'b1' to also be in the centre but below 'l1' and 'jt1'. Below is the delivery() method of my program:
public static void delivery()
{
final JFrame f1 = new JFrame("Name");
f1.setVisible(true);
f1.setSize(600,200);
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setLocation(700,450);
JPanel p1 = new JPanel();
final JLabel l1 = new JLabel("Enter your name: ");
final JTextField jt1 = new JTextField(20);
JButton b1 = new JButton("Ok");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input1 = jt1.getText();
f1.setVisible(false);
}
});
p1.add(b1);
p1.add(l1);
p1.add(jt1);
f1.add(p1);
final JFrame f2 = new JFrame("Address");
f2.setVisible(true);
f2.setSize(600,200);
f2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f2.setLocation(700,450);
JPanel p2 = new JPanel();
final JLabel l2 = new JLabel("Enter your address: ");
final JTextField jt2 = new JTextField(20);
JButton b2 = new JButton("Ok");
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
input2 = jt2.getText();
f2.setVisible(false);
}
});
p2.add(b2);
p2.add(l2);
p2.add(jt2);
f2.add(p2);
}
}
You can use multiple JPanels to get close to what you want:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyGui {
public static void delivery()
{
JFrame f1 = new JFrame("Name");
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f1.setBounds(200, 100, 500, 300);
Container cpane = f1.getContentPane();
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.LINE_AXIS)); //Horizontal
JLabel l1 = new JLabel("Enter your name: ");
JTextField jt1 = new JTextField(20);
jt1.setMaximumSize( jt1.getPreferredSize() );
p1.add(l1);
p1.add(jt1);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS)); //Vertical
p2.add(p1);
JButton b1 = new JButton("Ok");
p2.add(b1);
cpane.add(p2);
f1.setVisible(true);
}
}
public class SwingProg {
private static void createAndShowGUI() {
MyGui.delivery();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Use the GridBagLayout Class. It's for custom designing using Constraints.