Why this GUI counter can't display after 9? - java

I wrote this code and it works fine from 1 to 9 but after 9 instead of displaying numbers it displays ...
Can anyone tell me what could be the problem as am I quite new to GUI.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI implements ActionListener {
private int count = 0;
private JLabel label;
private JFrame frame;
private JPanel panel;
public GUI(){
frame = new JFrame();
panel = new JPanel();
JButton button = new JButton("Start");
button.addActionListener(this);
label = new JLabel("Number of Clicks: 0");
panel.setBorder(BorderFactory.createEmptyBorder(100,100,100,100));
panel.setLayout(new GridLayout(0,1));
panel.add(button);
panel.add(label);
frame.add(panel,BorderLayout.CENTER);
frame.setTitle("Clicker");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
#Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Number of Clicks: "+count);
}
}

Related

How to connect a JButton with a group of JRadioButtons?

I am creating a basic GUI frame. The frame has 10 radio buttons and a Submit button. The user selects one option(JRadioButtons) and clicks on the Submit(JButton) button. On clicking the Submit button, the option selected by the user appears on a different frame.
I want the Submit button to recognize the JRadioButton selected by the user.
I have put my bit of code here for reference.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame2 extends JFrame{
private JFrame frame2;
private JLabel label2;
private JButton button2;
private JRadioButton r1;
private JRadioButton r2;
private JRadioButton r3;
private JRadioButton r4;
private JRadioButton r5;
private JRadioButton r6;
private JRadioButton r7;
private JRadioButton r8;
private JRadioButton r9;
private JRadioButton r10;
public ButtonGroup group;
Frame2(){
setLayout(new BorderLayout());
setSize(new Dimension(1304,690));
getContentPane().setBackground(Color.DARK_GRAY);
label2= new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff",Font.BOLD, 14));
label2.setForeground(Color.WHITE);
button2=new JButton("Submit");
add(label2, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new GridLayout(2, 5));
centerPanel.add(r1=new JRadioButton("Introduction"));
centerPanel.add(r2=new JRadioButton("Class and Objects"));
centerPanel.add(r3=new JRadioButton("Object Oriented Programming Concepts"));
centerPanel.add(r4=new JRadioButton("JAVA literals, constants, variables"));
centerPanel.add(r5=new JRadioButton("Loops"));
centerPanel.add(r6=new JRadioButton("Functions/Methods"));
centerPanel.add(r7=new JRadioButton("Strings"));
centerPanel.add(r8=new JRadioButton("Arrays"));
centerPanel.add(r9=new JRadioButton("Time Complexity"));
centerPanel.add(r10=new JRadioButton("Data Structures"));
add(centerPanel, BorderLayout.CENTER);
group= new ButtonGroup();
group.add(r1);
group.add(r2);
group.add(r3);
group.add(r4);
group.add(r5);
group.add(r6);
group.add(r7);
group.add(r8);
group.add(r9);
group.add(r10);
add(button2, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button2) {
Layouts l=new Layouts();
l.main(null);
dispose();
}
}
});
}
public static void main(String[] args) {
Frame2 fr2=new Frame2();
}
}`
Thanks in advance.
It's a lot easier if you put the JRadioButtons in an array.
Here are the changes I made to your code to make it easier to modify and understand.
I added a call to the SwingUtilities invokeLater method to ensure the creation and execution of the Swing components happens on the Event Dispatch Thread.
I created the individual JPanels in methods. By separating the JPanel code, I could more easily focus on one part of the GUI at a time.
The methods to construct a JFrame must be called in the proper order. You have to create all the Swing components before you make the JFrame visible.
Here's one way to connect a JButton with a group of JRadioButtons.
import java.awt.BorderLayout;
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.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioButtonTest {
private JButton button2;
private JRadioButton[] rb;
private ButtonGroup group;
public RadioButtonTest() {
JFrame frame = new JFrame("Java Tutorials");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.DARK_GRAY);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JLabel label2 = new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff", Font.BOLD, 14));
label2.setForeground(Color.WHITE);
panel.add(label2, BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
button2 = new JButton("Submit");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button2) {
for (int i = 0; i < rb.length; i++) {
if (rb[i].isSelected()) {
String text = rb[i].getText();
System.out.println(text);
// Do your second JFrame
}
}
}
}
});
panel.add(button2, BorderLayout.SOUTH);
return panel;
}
private JPanel createButtonPanel() {
JPanel centerPanel = new JPanel(new GridLayout(0, 2));
String[] titles = { "Introduction", "Class and Objects",
"Object Oriented Programming Concepts",
"JAVA literals, constants, variables", "Loops",
"Functions/Methods", "Strings", "Arrays",
"Time Complexity", "Data Structures" };
rb = new JRadioButton[titles.length];
group = new ButtonGroup();
for (int i = 0; i < titles.length; i++) {
rb[i] = new JRadioButton(titles[i]);
group.add(rb[i]);
centerPanel.add(rb[i]);
}
return centerPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RadioButtonTest();
}
});
}
}

why is repaint() not working?

I am trying to add the buttons to the centerPanel that I created, then add that panel to the main center borderlayout. for some reason though my tab will not repaint anymore. It worked fine a while ago when I had the DrawFieldsListener class in the same class file as the MagicSquare, but nothing in the code has changed from my splitting them into two class files. So i really don't know what is going on. When it did repaint before, it would also take a long time. Any help? thanks!
All source for the project is on GitHub if it is easier to read and understand there: https://github.com/andrefecto/Academic-Convivium-Project
MagicSquare Class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MagicSquare extends JPanel {
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
static JButton calculate;
static JButton reset;
static JTextField squareSize;
static JTextField field;
public static ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
public static ArrayList<Integer> inputs = new ArrayList<Integer>();
public static ArrayList<Integer> totals = new ArrayList<Integer>();
public static int squared = 0;
public static int square = 0;
public static JPanel centerPanel = new JPanel();
public static JPanel bottomPanel = new JPanel();
public MagicSquare (){
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JTextField();
squareSize.setColumns(6);
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
}
}
my DrawFieldsListener class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawFieldsListener extends JPanel implements ActionListener {
int square = MagicSquare.square;
int squared = MagicSquare.squared;
JPanel centerPanel = MagicSquare.centerPanel;
JTextField squareSize = MagicSquare.squareSize;
JTextField field = MagicSquare.field;
ArrayList<JTextField> inputFields = MagicSquare.inputFields;
JButton calculate = MagicSquare.calculate;
JButton reset = MagicSquare.reset;
JPanel bottomPanel = MagicSquare.bottomPanel;
public void actionPerformed(ActionEvent e){
square = Integer.parseInt(squareSize.getText());
squared = square*square;
centerPanel.setLayout(new GridLayout(square, square));
for(int i = 0; i < squared; i++){
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons(){
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
calculate.addActionListener(new CalculateListener());
reset.addActionListener(new ResetListener());
}
}
Mistake #1
public static JPanel centerPanel = new JPanel();
Followed by...
class DrawFieldsListener extends JPanel implements ActionListener {
//...
JPanel centerPanel = MagicSquare.centerPanel;
static is not a cross object communication mechanism...and now I have no idea who is suppose to be responsible for managing the centerPanel...
Remember, static is not your friend, beware of how it is used
Mistake #2
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
You are creating two instances of DrawFieldsListener (which is a panel), one is acting as the ActionListener and one is acting as the view, but which one is actually housing MagicSquare.centerPanel as a component can only have one parent...
Mistake #3
Not revalidating the container after you have changed it...
public void actionPerformed(ActionEvent e) {
square = Integer.parseInt(squareSize.getText());
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
Swing is lazy when it comes to container management, it assumes that you will want to do a number of adds or removes, so it won't update the container hierarchy layout until you ask it to, as the operation can be expensive
A better solution...
Isolate responsibility and provide information to your objects in a de-coupled manner.
For example, the DrawFieldsListener shouldn't care about MagicSquare, but should provide a means by which "some body" can tell it how many squares it should create.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MagicSquare extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MagicSquare());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
private JSpinner squareSize;
JTextField field;
public MagicSquare() {
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JSpinner();
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
DrawFieldsListener dfl = new DrawFieldsListener();
setSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int gridSize = (int) squareSize.getValue();
dfl.makeGrid(gridSize);
}
});
add(subPanel, BorderLayout.NORTH);
add(dfl, BorderLayout.CENTER);
}
class DrawFieldsListener extends JPanel {
private JButton calculate;
private JButton reset;
private ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
private ArrayList<Integer> inputs = new ArrayList<Integer>();
private ArrayList<Integer> totals = new ArrayList<Integer>();
private int squared = 0;
private int square = 0;
private JPanel centerPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
public void makeGrid(int gridSize) {
square = gridSize;
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons() {
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
// calculate.addActionListener(new CalculateListener());
// reset.addActionListener(new ResetListener());
}
}
}

Java: How to display card JPanel fully when using CardLayout

I'm having trouble with this JApplet. At the moment I have a CardLayout JPanel which contains two BorderLayout JPanels. Whenever I run it, the components added to each 'card' (a JButton to go back to the other JPanel) don't display unless I use setVisible(true) for each LayoutManager. Furthermore, none of my ActionListeners work. I'm assuming because they only use show() and there's something else I have to do that's alluding me.
Must I use setVisible(true)? It seems from other questions that there's a way of doing this without that. Here's the code I'm having trouble with:
/*
*Java Version: 1.8.0_25
*Author: Peadar Ó Duinnín
*Student Number: R00095488
*/
package As1;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AUIJApplet extends JApplet implements ActionListener {
private final int WIDTH = 600;
private final int HEIGHT = 400;
private int highScore;
private int currentScore;
JPanel panelCont = new JPanel();
JPanel startPanel = new JPanel();
JPanel gamePanel = new JPanel();
JButton newGameButton = new JButton("New Game");
JButton endGameButton = new JButton("End Game");
JLabel highScoreLabel;
JLabel currentScoreLabel;
CardLayout cl = new CardLayout();
BorderLayout bl = new BorderLayout();
public AUIJApplet() {
highScore = 0;
}
#Override
public void init() {
setSize(WIDTH, HEIGHT);
panelCont.setLayout(cl);
startPanel.setLayout(bl);
gamePanel.setLayout(bl);
startPanel.add(newGameButton, BorderLayout.SOUTH);
gamePanel.add(endGameButton, BorderLayout.SOUTH);
startPanel.setBackground(Color.BLUE);
gamePanel.setBackground(Color.GREEN);
panelCont.add(startPanel, "Start Applet Screen");
panelCont.add(gamePanel, "New Game Screen");
newGameButton.addActionListener((e) -> {
newGame();
});
endGameButton.addActionListener((e) -> {
quitGame();
});
cl.show(panelCont, "Start Applet Screen");
this.add(panelCont);
}
public void newGame() {
cl.show(panelCont, "New Game Screen");
showScores(gamePanel);
}
public void quitGame() {
cl.show(panelCont, "Start Applet Screen");
if (currentScore > highScore) {
highScore = currentScore;
}
currentScore = 0;
}
public void showScores(JPanel currentPanel) {
currentPanel.add(new JLabel("High Score:") , BorderLayout.EAST);
currentPanel.add(highScoreLabel, BorderLayout.EAST);
currentPanel.add(new JLabel("Current Score:"), BorderLayout.EAST);
currentPanel.add(currentScoreLabel, BorderLayout.EAST);
}
#Override
public void actionPerformed(ActionEvent ae) {
}
}
I have made the a little similar code to perform same operation it works for me try to write the code from scratch. Here is my code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JApplet;
import javax.swing.*;
public class Example extends JApplet {
JPanel panel1,panel2,mainPanel;
JButton start,stop;
CardLayout cl = new CardLayout();
#Override
public void init() {
panel1 = new JPanel();
panel1.setBackground(Color.red);
panel1.setLayout(new BorderLayout());
panel2 = new JPanel();
panel2.setBackground(Color.blue);
panel2.setLayout(new BorderLayout());
start = new JButton("Start");
stop = new JButton("stop");
panel1.add(start,BorderLayout.SOUTH);
panel2.add(stop,BorderLayout.SOUTH);
mainPanel = new JPanel();
mainPanel.setLayout(cl);
mainPanel.add(panel1,"First Panel");
mainPanel.add(panel2, "Second Panel");
start.addActionListener((ActionEvent e) -> {
newGame();
});
stop.addActionListener((ActionEvent e) ->{
endGame();
});
this.add(mainPanel);
}
public void newGame()
{
cl.show(mainPanel, "Second Panel");
}
public void endGame()
{
cl.show(mainPanel,"First Panel");
}
}

Open new JFrame with JButton Click - Java Swing

I am trying to open a new JFrame window with a button click event. There is lots of info on this site but nothing that helps me because I think it is not so much the code I have, but the order it is executed (however I am uncertain).
This is the code for the frame holding the button that I want to initiate the event:
package messing with swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
public ReportGUI(){
reportInterface();
allReportsBtn();
examinnerFileRead();
courseFileRead();
comboBoxes();
}
private void examinnerFileRead(){
try{
Scanner scan = new Scanner(new File("Examiner.txt"));
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void courseFileRead(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
courseList.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame AllDataGUI = new JFrame();
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = list.toArray(new String[list.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
add(panel, BorderLayout.LINE_START);
}
If you don't want to delve into the above code, the button ActionListener is here:
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
This is the code in the class holding the JFrame I want to open:
package messing with swing;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class ViewCourseGUI extends JFrame{
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Courses taught by this examiner");
private JTextArea textArea = new JTextArea();
public void ViewCoursesGUI(){
panels();
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
Could someone please point me in the right direction?
As pointed out by PM 77-3
I had:
public void ViewCoursesGUI(){
panels();
}
When I should have had:
public ViewCourseGUI(){
panels();
}
A Combination of syntax and spelling errors.
Set the visibility of the JFrame you want to open, to true in the actionListener:
ViewCourseGUI viewCourseGUI = new ViewCourseGUI();
viewCourseGUI.setVisible(true);
This will open the new JFrame window once you click the button.
Let ReportGUI implement ActionListener. Then you will implement actionPerformed for the button click. On button click, create the second frame (if it doesn't exist). Finally, set the second frame visible (if it is currently not visible):
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ReportGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 8679886300517958494L;
private JButton button;
private ViewCourseGUI frame2 = null;
public ReportGUI() {
//frame1 stuff
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setLayout(new FlowLayout());
//create button
button = new JButton("Open other frame");
button.addActionListener(this);
add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReportGUI frame = new ReportGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
if (frame2 == null)
frame2 = new ViewCourseGUI();
if (!frame2.isVisible())
frame2.setVisible(true);
}
}
}
This is a simple example. You'll have to add the rest of your code here.

Centering Swing Components

How do I make my textfields and button centered?
Edit: Updated my post with SSCE. Hopefully that helps.
By the way, I want the left image to look like the right.
package pkg;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel();
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.add(username);
panel.add(password);
panel.add(login);
panel.add(status);
game.add(logout);
frame.add(panel);
frame.setSize(806, 553);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
try {
Client.socketOut.writeUTF("logout");
Client.socketOut.writeUTF(Client.username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
What I want it to look like:
I've tried to use many different layout styles but I can't seem to make it work...
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.setLayout(new GridLayout(0,1,15,15));
panel.setBorder(new EmptyBorder(50,100,50,100));
panel.add(username);
panel.add(password);
panel.add(status);
JPanel logoutConstrain = new JPanel(new FlowLayout(FlowLayout.CENTER));
logoutConstrain.add(logout);
panel.add(logoutConstrain);
frame.setLayout(new GridBagLayout());
frame.add(panel);
//frame.setSize(806, 553); // forget this nonsense, instead..
frame.pack(); // best!
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
}
});
}
}

Categories

Resources