Why is my java applet not visible? - java

I converted a simple java application to a java applet, but it just shows a black grey square instead of my application. The app consists of a poolframe.java, ball.java, poolapplet.java.
package pool;
import java.awt.Graphics;
import java.util.Timer;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class PoolApplet extends JApplet
{
private JFrame appletFrame;
#Override
public void init()
{
appletFrame = new PoolFrame(this);
appletFrame.setVisible (true);
appletFrame.setEnabled (true);
}//End of main
public void close()
{
appletFrame.dispose();
appletFrame=null;
}
}
//pooframe.java
package pool;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JTextField;
public class PoolFrame extends JFrame
{
//variables
double angle = 0;
//objects
public ball b;
private JButton newGame, go, pause, exit;
private JLabel NewGame, Speed, Direction, Table;
private JTextField speed, direction;
private Timer timer;
//layout managers
private GridBagLayout grid;
private FlowLayout field;
private FlowLayout global;
//panels
private JPanel GameField, input,spacer;
private ActionListener actionlistener;
private PoolApplet myapplet;
public PoolFrame(PoolApplet mainapp)
{
super("Pool by William Murmann");
myapplet = mainapp;
grid = new GridBagLayout();
global = new FlowLayout(FlowLayout.CENTER,0,0);
setLayout(global);
timer = new Timer();
GridBagConstraints c = new GridBagConstraints();
Font gen = new Font("Sans-Serif", Font.PLAIN, 18);
//Input fields
b = new ball();
b.setPreferredSize(new Dimension(600,300));
b.setSize(600,300);
b.setBackground(Color.black);
spacer = new JPanel();
spacer.setPreferredSize(new Dimension(1200,5));
JPanel input = new JPanel();
input.setLayout(grid);
Speed = new JLabel("Speed");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,10,20,0);
input.add(Speed, c);
speed = new JTextField();
speed.setPreferredSize(new Dimension(75,30));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0,10,20,0);
input.add(speed, c);
Direction = new JLabel("Direction");
c.gridx = 2;
c.gridy = 0;
c.insets = new Insets(0,10,20,0);
input.add(Direction, c);
direction = new JTextField();
direction.setPreferredSize(new Dimension(75,30));
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0,10,20,0);
input.add(direction, c);
newGame = new JButton("New");
c.gridx = 0;
c.gridy = 3;
input.add(newGame, c);
go = new JButton("Go");
c.gridx = 1;
c.gridy = 3;
input.add(go, c);
pause = new JButton("Pause");
c.gridx = 2;
c.gridy = 3;
input.add(pause, c);
exit = new JButton("Exit");
c.gridx = 3;
c.gridy = 3;
input.add(exit, c);
buttonhandler action = new buttonhandler();
newGame.addActionListener(action);
go.addActionListener(action);
pause.addActionListener(action);
exit.addActionListener(action);
add(b);
add(spacer);
add(input);
setSize(600,900);
setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
}
private class buttonhandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == newGame)
{
angle = 0;
b.changePosition(300, 130);
timer.cancel();
speed.setText("");
direction.setText("");
}
else if(event.getSource() == go)
{
timer.cancel();
if(!"".equals(speed.getText()) && !"".equals(direction.getText()))
{
angle = Double.parseDouble(direction.getText());
startTimer(Integer.parseInt(speed.getText()));
}
}
else if(event.getSource() == pause)
{
timer.cancel();
}
else if(event.getSource() == exit)
{
myapplet.close();
}
}
public void startTimer(int HSeconds)
{
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
move();
}
}, 0, HSeconds);
}
public void move()
{
if(b.x < 0 || b.x > 600)
{
timer.cancel();
b.changePosition(300, 130);
speed.setText("");
direction.setText("");
}
if(b.y <= 0 || b.y >= 280)
{
angle = 180 - angle;
}
double X = Math.sin(Math.toRadians(angle));
double Y = Math.cos(Math.toRadians(angle));
b.changePosition(b.x + X,b.y + Y);
}
}
}//end
//html
<html>
<body>
<br>
</br>
<applet code = "pool.PoolApplet.class" width = "1000" height = "900">
</applet>
</body>
</html>
At one point I had the the app opening in a separate window but I can't get back to that point.
Edit::
here is a github page for it https://github.com/wmurmann/applet
along with https://rawgithub.com/wmurmann/applet/master/runapplet.html to run the app.

Related

Put space between label in GridLayout

package committeeGUI;
import static committeeGUI.CommitteeGUI.comList;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class StudentMemberFrame extends JFrame {
public StudentMemberFrame() {
super("Add Student");
setSize(450, 500);
setLocation(561, 150);
super.setResizable(false);
addStudentMember();
}
public void addStudentMember() {
CommitteeGUI.frame.setEnabled(false);
final JPanel showConsoleArea = new JPanel(new FlowLayout(FlowLayout.LEFT));
showConsoleArea.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//creating border and size of the border
showConsoleArea.setBorder(BorderFactory.createLineBorder(Color.black, 3));
add(showConsoleArea); //, BorderLayout.CENTER);
//setting a size to showConsoleArea.
showConsoleArea.setSize(500, 500);
final JLabel lblheading = new JLabel("STUDENT");
// showConsoleArea.add(lblheading,BorderLayout.CENTER);
/*
* creating components of company form
*/
final JLabel lblCommitteeName = new JLabel("Committee name");
final JTextField txtName = new JTextField(15);
final JLabel lblMemberName = new JLabel("Student name");
final JTextField txtMemberName = new JTextField(15);
final JLabel lblMemberNumber = new JLabel("Student number");
final JTextField txtMemberNumber = new JTextField(15);
final JLabel lblMemberCourse = new JLabel("Student course");
final JTextField txtMemberCourse = new JTextField(15);
final JButton buttAdd = new JButton("SAVE");
final JButton buttCancel = new JButton("CANCEL");
// adding components to the display area
c.gridx = 1;
c.gridy = 0;
showConsoleArea.add(lblheading, c);
c.gridx = 0;
c.gridy = 1;
showConsoleArea.add(lblCommitteeName, c);
c.gridx = 1;
c.gridy = 1;
showConsoleArea.add(txtName, c);
c.gridx = 0;
c.gridy = 2;
showConsoleArea.add(lblMemberName, c);
c.gridx = 1;
c.gridy = 2;
showConsoleArea.add(txtMemberName, c);
c.gridx = 0;
c.gridy = 3;
showConsoleArea.add(lblMemberNumber, c);
c.gridx = 1;
c.gridy = 3;
showConsoleArea.add(txtMemberNumber, c);
c.gridx = 0;
c.gridy = 4;
showConsoleArea.add(lblMemberCourse, c);
c.gridx = 1;
c.gridy = 4;
showConsoleArea.add(txtMemberCourse, c);
c.gridx = 0;
c.gridy = 5;
showConsoleArea.add(buttAdd, c);
c.gridx = 1;
c.gridy = 5;
showConsoleArea.add(buttCancel, c);
/*
* able to displaying the company frame
*/
this.show();
buttAdd.addActionListener((ActionEvent e) -> {
if (txtName.getText().equals("")
|| txtMemberName.getText().equals("")
|| txtMemberNumber.getText().equals("")
|| txtMemberCourse.getText().equals("")) //validating the data
{
CommitteeGUI.frame.setEnabled(false);
setEnabled(false);
messagebox("Enter a valid data", 0);
return;
}
if (!txtMemberNumber.getText().matches("\\d+")) {
CommitteeGUI.frame.setEnabled(false);
setEnabled(false);
messagebox("Member number must be a integer", 0);
return;
}
for (Committee com : comList) {
if (com.getName().equals(txtName.getText())) {
Student st = new Student();
st.setName(txtMemberName.getText());
st.setAcademicNo(Integer.parseInt(txtMemberNumber.getText()));
st.setCourse(txtMemberCourse.getText());
com.memberList.add(st);
messagebox("Member added successfully", 1);
setEnabled(false);
return;
}
}
messagebox("No Committee found with given name", 1);
});
//creating ActionListner to Cancel button
buttCancel.addActionListener((ActionEvent e) -> {
//frame is enabled for user.
CommitteeGUI.frame.setEnabled(true);
dispose(); //disposing the frame
} //pass the action to actionPerformed method and perform it.
);
}
#SuppressWarnings("deprecation")
public void messagebox(String label, final int conform) {
final JDialog infoBox = new JDialog();//message box
infoBox.setSize(400, 90);
infoBox.setAlwaysOnTop(true);
infoBox.setResizable(false);
infoBox.setLocation(675, 258);
JLabel space = new JLabel(" ");
JLabel label1 = new JLabel(label);
JButton buttOk = new JButton("Ok");
buttOk.addActionListener((ActionEvent e) -> {
if (conform == 1) {
// making frame operation enable.
CommitteeGUI.frame.setEnabled(true);
dispose();
}
setEnabled(true);
infoBox.hide();
});
JPanel holder = new JPanel(new FlowLayout());
holder.add(label1);
holder.add(buttOk);
infoBox.add(holder);
infoBox.show();
}
}
Above is my code. I want to put space between the heading (STUDENT) and the fields.
Attached is the snapshot of the frame:
I am not familiar with this layout. Help is much appreciated.
public void addStudentMember() {
final JPanel showConsoleArea = new JPanel(new FlowLayout(FlowLayout.LEFT));
showConsoleArea.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Add below line of code change appropriate spacing
c.insets = new Insets(10, 10, 10, 10);

How to keep GridBagLayout from changing the size of a button

In my FlashCardPanel class, I have a subpanel,LabelPanel, with a Grid Bag Layout. It consists of a constructor with an edit button, a button to "flip" the card, and the label to display the term/definition. My problem is that every time I click my "Flip" Button to display the definition of my term, the flip button will change size, usually matching the length of the definition.
Images of the problem
http://postimg.org/gallery/ymww3axq/
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class FlashCardPanel extends JPanel{
private String term;
private String definition;
// shows the current text whether it is a term or definition
private JLabel currentLabel;
private static String NO_CARDS = "This set is empty";
//current card being displayed
private FlashCard currentCard;
//new card that is added to the deck
private FlashCard newCard;
// true = term is showing; false = definition is showing
private boolean termShowing = true;
private AddNewCard frame;
private CardSet cardSet;
private int cardIndex = 0;
private ButtonPanel bPanel;
private LabelPanel lPanel;
private static JButton flipButton;
private static JButton nextButton;
private static JButton prevButton;
private static JButton addCard;
private static JButton deleteCard;
private static JButton editButton;
public FlashCardPanel(CardSet cardSet) {
this.cardSet = cardSet;
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
term = cardSet.get(0).getTerm();
definition = cardSet.get(0).getDefintion();
currentCard = cardSet.get(0);
createButtons();
lPanel = new LabelPanel();
bPanel = new ButtonPanel();
add(lPanel);
add(bPanel);
}
public FlashCardPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(lPanel);
add(bPanel);
}
private class LabelPanel extends JPanel {
public LabelPanel() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(15,15,15,15);
currentLabel = new JLabel(term);
currentLabel.setText(cardSet.get(0).getTerm());
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 0;
c.gridy = 0;
add(editButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.gridwidth = 0;
c.weightx = 0;
c.gridx = 2;
c.gridy = 0;
add(flipButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40;
c.weightx = 0;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 3;
add(currentLabel,c);
}
}
private class ButtonPanel extends JPanel {
public ButtonPanel() {
this.setLayout(new GridLayout(2,2));
add(prevButton);
add(nextButton);
add(addCard);
add(deleteCard);
}
}
/*
* creates buttons for the panel. Should be called before
* any subpanel is created.
*/
private void createButtons()
{
flipButton = new JButton(" Flip Card ");
flipButton.addActionListener(new ButtonListener());
flipButton.setActionCommand("1");
nextButton = new JButton(" Next Card ");
nextButton.addActionListener(new ButtonListener());
nextButton.setActionCommand("2");
prevButton = new JButton(" Previous Card ");
prevButton.addActionListener(new ButtonListener());
prevButton.setActionCommand("3");
addCard = new JButton(" Add Card ");
addCard.addActionListener(new ButtonListener());
addCard.setActionCommand("4");
deleteCard = new JButton(" Delete Card ");
deleteCard.addActionListener(new ButtonListener());
deleteCard.setActionCommand("5");
editButton = new JButton("Edit");
editButton.addActionListener(new ButtonListener());
editButton.setActionCommand("6");
}
private class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
switch(action){
case 1:
flipCard();
break;
case 2:
nextCard();
break;
case 3:
previousCard();
break;
case 4:
createFrame();
break;
case 5:
deleteCard();
case 6:
createFrame(term,definition);
}
}
}
private void flipCard()
{
if (!cardSet.isEmpty()) {
if (termShowing) {
termShowing = false;
currentLabel.setText(definition);
}
else {
termShowing = true;
currentLabel.setText(term);
}
}
else {
currentLabel.setText(NO_CARDS);
term = "";
definition = "";
JOptionPane.showMessageDialog(this, "This set is empty");
}
}
private void nextCard()
{
if (!cardSet.isEmpty()) {
if (cardIndex == cardSet.size()-1)
cardIndex = 0;
else
cardIndex++;
term = cardSet.get(cardIndex).getTerm();
definition = cardSet.get(cardIndex).getDefintion();
if(termShowing)
currentLabel.setText(term);
else
currentLabel.setText(definition);
currentCard = cardSet.get(cardIndex);
}
else JOptionPane.showMessageDialog(this, "This set is empty");
}
private void previousCard()
{
if (!cardSet.isEmpty()) {
if (cardIndex == 0)
cardIndex = cardSet.size()-1;
else
cardIndex--;
term = cardSet.get(cardIndex).getTerm();
definition = cardSet.get(cardIndex).getDefintion();
if(termShowing)
currentLabel.setText(term);
else
currentLabel.setText(definition);
currentCard = cardSet.get(cardIndex);
}
else JOptionPane.showMessageDialog(this, "This set is empty");
}
/*
* adding a card
*/
private void createFrame() {
frame = new AddNewCard(100,100,this);
}
/*
* editing an existing card
*/
private void createFrame(String t, String d)
{
frame = new AddNewCard(100,100,this,t,d);
}
public void addNewCard(String t, String d) {
newCard = new FlashCard(t,d);
cardSet.add(newCard);
if (cardSet.isEmpty()) currentLabel.setText(newCard.getTerm());
}
public void editCard(String t, String d) {
currentCard.setTerm(t);
currentCard.setDefinition(d);
if (termShowing) currentLabel.setText(t);
else currentLabel.setText(d);
}
/*
* Deletes current card on display
*/
private void deleteCard()
{
if (!cardSet.isEmpty()) {
// if on the last card of the set
if (cardIndex == cardSet.size()-1) cardIndex--;
cardSet.remove(currentCard);
if (!cardSet.isEmpty()) {
currentCard = cardSet.get(cardIndex);
currentLabel.setText(cardSet.get(cardIndex).getTerm());
}
else currentLabel.setText(NO_CARDS);
}
else JOptionPane.showMessageDialog(this, "This set is empty");
}
}
You have several options including:
using a nested JPanels each with its own layout. For instance the buttons could be placed into a GridLayout JPanel, and this placed into a BorderLayout JPanel with the label BorderLayout.CENTER
I suggest that the long definition text be displayed within a JTextArea, not a JLabel. If you make it non-editable and remove borders, it could look like a JLabel.
If you go this route, you will want to turn on word wrap on the JTextArea.
You could swap JTextArea with JLabel (for the term) using a CardLayout.
Note, for future questions, please pare down your problem. For instance, if this were my question, I'd create something like the code below, small, self contained, runnable and demonstrates the problem:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FlashCardPanel2 extends JPanel {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private JLabel currentLabel;
private String term = "Term";
private String definition = "Definition: This will be a very long String to "
+ "illustrate the problem that you are having, and to try to help you get "
+ "a solution";
private JButton editButton = new JButton("Edit");
private JButton flipButton = new JButton(new FlipAction("Flip"));
public FlashCardPanel2() {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(15, 15, 15, 15);
currentLabel = new JLabel(term);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.gridx = 0;
c.gridy = 0;
add(editButton, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.gridwidth = 0;
c.weightx = 0;
c.gridx = 2;
c.gridy = 0;
add(flipButton, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40;
c.weightx = 0;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 3;
add(currentLabel, c);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class FlipAction extends AbstractAction {
public FlipAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String text = currentLabel.getText();
text = (text.equals(term)) ? definition : term;
currentLabel.setText(text);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FlashCardPanel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FlashCardPanel2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
And here's a potential solution with CardLayout and GridLayout and BorderLayout:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FlashCardPanel3 extends JPanel {
private static final long serialVersionUID = 1L;
private static final String CURRENT_LABEL = "current label";
private static final String DEFINITION = "definition";
private JLabel currentLabel;
private JTextArea currentDefinitionArea = new JTextArea(6, 20);
private CardLayout cardLayout = new CardLayout();
private JPanel cardHolder = new JPanel(cardLayout);
private String term = "Term";
private String definition = "Definition: This will be a very long String to "
+ "illustrate the problem that you are having, and to try to help you get "
+ "a solution";
private JButton editButton = new JButton("Edit");
private JButton flipButton = new JButton(new FlipAction("Flip"));
public FlashCardPanel3() {
currentDefinitionArea.setOpaque(false);
currentDefinitionArea.setText(definition);
currentDefinitionArea.setWrapStyleWord(true);
currentDefinitionArea.setLineWrap(true);
currentDefinitionArea.setEditable(false);
currentDefinitionArea.setFocusable(false);
currentLabel = new JLabel(term, SwingConstants.CENTER);
cardHolder.add(currentLabel, CURRENT_LABEL);
cardHolder.add(new JScrollPane(currentDefinitionArea), DEFINITION);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 0));
buttonPanel.add(editButton);
buttonPanel.add(flipButton);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(buttonPanel, BorderLayout.PAGE_START);
add(cardHolder);
}
private class FlipAction extends AbstractAction {
public FlipAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// String text = currentLabel.getText();
// text = (text.equals(term)) ? definition : term;
// currentLabel.setText(text);
cardLayout.next(cardHolder);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FlashCardPanel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FlashCardPanel3());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

I can't seem to get this inheritance to work

I have a tabbed application. One of the tabs you can enter the name of the company and it should change it to whatever you typed into the other tab. Here are both classes.
On this code its telling me to change About.setCompanyName(str); to static
The error that I am seeing is "Cannot make a static reference to the non-static method SetCompanyName(String) from the type About"
package CourseProject;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class Options extends JPanel{
private JLabel changeLabel;
private JTextField changeName;
private JButton setName;
private JButton exitButton;
public Options(){
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
c.insets = new Insets(10, 10, 10, 10);
changeLabel = new JLabel("Change Company Name:");
changeName = new JTextField("", 10);
setName = new JButton("Set New Name");
exitButton = new JButton("Exit");
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
add(changeLabel, c);
c.gridx = 0;
c.gridy = 1;
add(changeName, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
add(setName, c);
setName.addActionListener(new setNameAction());
c.gridx = 1;
c.gridy = 2;
add(exitButton, c);
exitButton.addActionListener(new exitApp());
exitButton.setSize(40,40);
}
class setNameAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str;
str = changeName.getText();
About.SetCompanyName(str);
changeName.setText("");
}
}
class exitApp implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
And here is "About" which contains my setter. It asks me to make the method and variable static but I know this wont work because I am wanting to change it
package CourseProject;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JPanel{
private JLabel programInfoLabel;
private JLabel programInfo;
private JLabel programmerLabel;
private JLabel programmer;
private JLabel companyLabel;
JLabel company;
public String companyName = "enter a company name in options";
public About() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
c.insets = new Insets(10, 10, 10, 10);
programInfoLabel = new JLabel("Program Information:");
programInfo = new JLabel("This is the CIS355A course project application");
programmerLabel = new JLabel("Programmer:");
programmer = new JLabel("Kevin Rankin");
companyLabel = new JLabel("Company Name:");
company = new JLabel(companyName);
c.gridx = 0;
c.gridy = 0;
add(programInfoLabel, c);
c.gridx = 1;
c.gridy = 0;
add(programInfo, c);
c.gridx = 0;
c.gridy = 1;
add(programmerLabel, c);
c.gridx = 1;
c.gridy = 1;
add(programmer, c);
c.gridx = 0;
c.gridy = 2;
add(companyLabel, c);
c.gridx = 1;
c.gridy = 2;
add(company, c);
}
public void SetCompanyName(String str){
company.setText(str);
}
}
On this line
About.SetCompanyName(str);
You're calling SetCompanyName statically (by using the class name "About"). You should either make the method static (which is not the same as "final"; you seem to be confused about this) or create an instance of the About class first, like so:
About myAboutObject = new About();
myAboutObject.SetCompanyName(str);

Trying to use GridBagConstraints in a standalone frame class

The following code is going to end up being one of the panels for a tabbed panel. I've only used GridBagConstraints once and it was easier because I had a Pane. I would just use something like
mainFrame.getContentPane().add(panel, BorderLayout.NORTH);
What if I wanted to us the gridbaglayout for this code. I don't have a pane. How could I accomplish adding GridBagConstraints?
package Week4;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class OfficeAreaCalculator extends JPanel{
private JButton calculateButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator(){
setBackground(Color.white);
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
lengthField = new JTextField(5);
widthField = new JTextField(5);
areaField = new JTextField(5);
areaField.setEditable(false);
calculateButton = new JButton("Calculate");
add(lengthLabel);
add(lengthField);
add(widthLabel);
add(widthField);
add(areaLabel);
add(areaField);
add(calculateButton);
calculateButton.setMnemonic('C');
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try{
DecimalFormat num = new DecimalFormat(",###.##");
double width, length, area;
String instring;
instring = lengthField.getText();
if (instring.equals(""))
{
instring = ("0");
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if (instring.equals(""))
{
instring = "0";
widthField.setText("0");
}
width = Double.parseDouble(instring);
area = length * width;
areaField.setText(num.format(area));
}
catch( Exception d){
lengthField.setText("Invalid");
widthField.setText("Invalid");
}
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if (e.getSource() == lengthField || e.getSource() == widthField)
{
areaField.setText("");
}
else if (e.getSource() == areaField)
{
calculateButton.requestFocus();
}
}
public void focusLost(FocusEvent e)
{
if (e.getSource() == widthField)
{
calculateButton.requestFocus();
}
}
}
}
I think I may have figured out the answer to my own question. Before I start messing with the grid coordinates I need to do it like this:
package Week6;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Index extends JPanel{
private JLabel searchLabel;
private JTextField searchField;
private JLabel charLabel;
private JTextField charField;
public Index(){
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
searchLabel = new JLabel("Enter text to be searched:");
searchField = new JTextField("");
charLabel = new JLabel("Exter a character:");
charField = new JTextField("");
c.insets = new Insets(10, 10, 10, 10);
c.gridx = 0;
c.gridy = 0;
add(searchLabel, c);
c.gridx = 1;
c.gridy = 0;
add(searchField, c);
c.gridx = 0;
c.gridy = 1;
add(charLabel, c);
c.gridx = 1;
c.gridy = 1;
add(charField, c);
}
}

JCheckboxes and JButton not showing randomly

I have a basic gui (it doesn't need to look pretty, it just needs to work. It's a gui to display several algorithms I'm implementing for my thesis.) but the checkboxes and button won't show up randomly. Sometimes they appear, sometimes they don't. I honestly have no clue why this could be happening and I'm pretty scrub at swing, so I'm lost.
EDIT: Here's what i want my gui to look like:
//import java.awt.*;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.ButtonGroup;
import javax.swing.*; //notice javax
public class MapWindowController extends JFrame implements ActionListener, ItemListener
{
private static final int WIDTH = 600, HEIGHT = 800;
private static final int SETTINGS_WIDTH = 600, SETTINGS_HEIGHT = 200;
private static final int NUM_MAP_TYPE = 2;
private static final int NUM_ALGORITHM_TYPE = 4;
private static final int MAP_IMAGE_SIZE = 400, ACTUAL_MAP_SIZE = 10;
private JButton run;
private JCheckBox[] map_type;
private JCheckBox[] algorithm_type;
JPanel panel = new JPanel();
JPanel settings_panel = new JPanel();
MapView map_view = new MapView(MAP_IMAGE_SIZE);
SettingsButtonsPanel settings = new SettingsButtonsPanel();
MapModel map_model = new MapModel(ACTUAL_MAP_SIZE, map_view);
ButtonGroup bgMap;
ButtonGroup bgAlgorithm;
public MapWindowController()
{
setLocationRelativeTo(null);
setTitle("HPA* Test");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel);
panel.setBounds(0, 0, 600, 800);
panel.setLayout(null);
/*GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;*/
instantiateSettingsPanel();
//panel.add(settings);
/*c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;*/
panel.add(map_view);
map_view.setBounds(0,200,600,600);
//button_panel.setBounds(0,0);
map_view.repaint();
}
public void instantiateSettingsPanel() {
settings_panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//this.setLayout(null);
map_type = new JCheckBox[NUM_MAP_TYPE];
map_type[0] = new JCheckBox("Sparse");
map_type[0].setSelected(true);
map_type[1] = new JCheckBox("Maze");
map_type[1].setSelected(false);
algorithm_type = new JCheckBox[NUM_ALGORITHM_TYPE];
algorithm_type[0] = new JCheckBox("A*");
algorithm_type[0].setSelected(true);
algorithm_type[1] = new JCheckBox("HPA*");
algorithm_type[1].setSelected(false);
algorithm_type[2] = new JCheckBox("TA*");
algorithm_type[2].setSelected(true);
algorithm_type[3] = new JCheckBox("PTHPA*");
algorithm_type[3].setSelected(false);
bgMap = new ButtonGroup( );
bgAlgorithm = new ButtonGroup( );
settings_panel.setMaximumSize(new Dimension(600,200));
for(int i = 0; i < NUM_MAP_TYPE; i++)
{
bgMap.add(map_type[i]);
map_type[i].addItemListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = i+1;
settings_panel.add(map_type[i], c);
}
for(int i = 0; i < NUM_ALGORITHM_TYPE; i++)
{
bgAlgorithm.add(algorithm_type[i]);
algorithm_type[i].addItemListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = i+1;
settings_panel.add(algorithm_type[i], c);
}
run = new JButton("Run");
run.addActionListener(this);
settings_panel.add(run);
panel.add(settings_panel);
settings_panel.setBounds(0,0,SETTINGS_WIDTH,SETTINGS_HEIGHT);
}
public void itemStateChanged(ItemEvent e)
{
Object source = e.getItemSelectable();
//if(source == )
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String algorithm = "A*";
String map = "Sparse";
for(int i = 0; i < algorithm_type.length; i++) {
if(algorithm_type[i].isSelected()) {
algorithm = algorithm_type[i].getText();
break;
}
}
for(int i = 0; i < map_type.length; i++) {
if(map_type[i].isSelected()) {
map = map_type[i].getText();
break;
}
}
if(source == run) {
if(map.equals("Sparse"))
map_model.createRandomObstaclesSparse(10, 1);
else
map_model.createRandomObstaclesMaze(1);
map_model.startPathfinding(algorithm, 0, true);
map_view.setMapScale(ACTUAL_MAP_SIZE);
map_view.setMapModel(map_model);
}
}
}
Your first mistake is using a null layout, your second mistake is calling setVisible before the UI is completed.
Your basic idea is sound, separating the various areas of responsibility into separate components, this will make you life much easier.
Basically, I used a GridBagLayout as it allows you to define fill weights for each component, providing a 1/4 of the vertical space to the buttons and the remainder to the map...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MapWindowController extends JFrame implements ActionListener, ItemListener {
private static final int WIDTH = 600, HEIGHT = 800;
private static final int SETTINGS_WIDTH = 600, SETTINGS_HEIGHT = 200;
private static final int NUM_MAP_TYPE = 2;
private static final int NUM_ALGORITHM_TYPE = 4;
private static final int MAP_IMAGE_SIZE = 400, ACTUAL_MAP_SIZE = 10;
private JButton run;
private JCheckBox[] map_type;
private JCheckBox[] algorithm_type;
JPanel content = new JPanel();
JPanel settings_panel = new JPanel();
private JPanel mapPane = new JPanel(new BorderLayout());
ButtonGroup bgMap;
ButtonGroup bgAlgorithm;
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) {
}
new MapWindowController();
}
});
}
public MapWindowController() {
setLocationRelativeTo(null);
setTitle("HPA* Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
content.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 0.25;
gbc.weightx = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
content.add(settings_panel, gbc);
gbc.gridy++;
gbc.weighty = 0.75;
content.add(mapPane, gbc);
try {
mapPane.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Map.png")))));
} catch (IOException ex) {
ex.printStackTrace();
}
add(content);
/*GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;*/
instantiateSettingsPanel();
//panel.add(settings);
/*c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;*/
pack();
setLocationByPlatform(true);
setVisible(true);
}
public void instantiateSettingsPanel() {
settings_panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//this.setLayout(null);
map_type = new JCheckBox[NUM_MAP_TYPE];
map_type[0] = new JCheckBox("Sparse");
map_type[0].setSelected(true);
map_type[1] = new JCheckBox("Maze");
map_type[1].setSelected(false);
algorithm_type = new JCheckBox[NUM_ALGORITHM_TYPE];
algorithm_type[0] = new JCheckBox("A*");
algorithm_type[0].setSelected(true);
algorithm_type[1] = new JCheckBox("HPA*");
algorithm_type[1].setSelected(false);
algorithm_type[2] = new JCheckBox("TA*");
algorithm_type[2].setSelected(true);
algorithm_type[3] = new JCheckBox("PTHPA*");
algorithm_type[3].setSelected(false);
bgMap = new ButtonGroup();
bgAlgorithm = new ButtonGroup();
settings_panel.setMaximumSize(new Dimension(600, 200));
for (int i = 0; i < NUM_MAP_TYPE; i++) {
bgMap.add(map_type[i]);
map_type[i].addItemListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = i + 1;
settings_panel.add(map_type[i], c);
}
for (int i = 0; i < NUM_ALGORITHM_TYPE; i++) {
bgAlgorithm.add(algorithm_type[i]);
algorithm_type[i].addItemListener(this);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = i + 1;
settings_panel.add(algorithm_type[i], c);
}
run = new JButton("Run");
run.addActionListener(this);
settings_panel.add(run);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
//if(source == )
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String algorithm = "A*";
String map = "Sparse";
for (int i = 0; i < algorithm_type.length; i++) {
if (algorithm_type[i].isSelected()) {
algorithm = algorithm_type[i].getText();
break;
}
}
for (int i = 0; i < map_type.length; i++) {
if (map_type[i].isSelected()) {
map = map_type[i].getText();
break;
}
}
if (source == run) {
// if (map.equals("Sparse")) {
// map_model.createRandomObstaclesSparse(10, 1);
// } else {
// map_model.createRandomObstaclesMaze(1);
// }
// map_model.startPathfinding(algorithm, 0, true);
// map_view.setMapScale(ACTUAL_MAP_SIZE);
// map_view.setMapModel(map_model);
}
}
}
Don't use setSize of setBounds on a window, instead, use pack to automatically set the optimal size of the window based on it's contents preferred size.

Categories

Resources