I am using the menu to try to change the button number.
But this should not refresh.
How do I solve this?
I want 'file -> modify -> button 10x10 -> 20x20 change. '
To test and modify the source below. Please...
Please give me change the source. TT
package com.test;
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.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MineMain extends JFrame {
private GridLayout grid;
private JPanel jp;
private int rownum, colnum;
private JButton[][] btn = null;
public MineMain(){
super("MINE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Menu_Init();
// grid = new GridLayout();
// jp = new JPanel();
rownum = 10;
colnum = 10;
Init(200, 250);
}
private void setBtn(int row, int col){
btn = new JButton[row][col];
}
public void Init(int w, int h){
if(jp != null)
jp.removeAll();
else
jp = null;
btn = null;
jp = null;
// jp.removeAll();
grid = new GridLayout(rownum, colnum, 0, 0);
jp = new JPanel(grid);
setBtn(rownum, colnum);
for(int i=0;i<btn.length;i++){
for(int j=0;j<btn[i].length;j++){
btn[i][j] = new JButton();
jp.add(btn[i][j]);
}
}
// jp.revalidate();
// jp.repaint();
this.add(jp);
this.setSize(w, h);
this.setLocation(200, 200);
this.setVisible(true);
this.setResizable(false);
}
public void Menu_Init(){
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
JMenu filemenu = new JMenu("File(F)");
filemenu.setMnemonic('F');
JMenuItem startmenu = new JMenuItem("New Game(N)");
startmenu.setMnemonic('N');
startmenu.setActionCommand("NEW START");
startmenu.addActionListener(new MenuActionListener());
filemenu.add(startmenu);
JMenuItem minecntmenu = new JMenuItem("MINE MODIFY(M)");
minecntmenu.setMnemonic('M');
minecntmenu.setActionCommand("MODIFY");
minecntmenu.addActionListener(new MenuActionListener());
filemenu.add(minecntmenu);
JMenuItem close = new JMenuItem("CLOSE(C)");
close.setMnemonic('C');
filemenu.add(close);
bar.add(filemenu); //JMenuBar에 JMenu 부착
}
private class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("START")){
JOptionPane.showMessageDialog(null, "NEW GAME", "MINE", JOptionPane.YES_NO_OPTION);
} else if(e.getActionCommand().equals("MODIFY")){
modify(2);
}
}
}
private void modify(int lvl){
rownum = 20;
colnum = 20;
Init(400, 500);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MineMain();
}
}
I see you are calling Init() again on modify().
Within Init(), I am assuming you are using
if(jp != null)
jp.removeAll();
else
jp = null;
to clear out the JPanel?
You want to remove the existing JPanel (i.e. jp) from the JFrame (i.e. this) before continuing at this point.
So, you could change your code to
if(jp != null) {
// JPanel already exists. so, remove JPanel jp from the JFrame
this.remove(jp);
jp.removeAll();
} else
jp = null;
Related
I have created a 3x3 memory game with colors. The program runs and displays the colors, but the JMenuBar is not working correctly. The button new board, play and end game are not working. Is there something wrong with my Actionlistener?
This is how the code should be working : https://gyazo.com/9bf3e073a9c455e56d9b4403586bfaf5?fbclid=IwAR3Zk1BZvRj49CtAz01h95zic8tk74UmyUcU2HrY3VY8XcARoD14Ke6tcoQ
This is StartPlayer
import gui.MemoryGameWindow;
import gui.ColoredPanel;
import gui.GamePanel;
public class StartPlayer {
public static void main(String[] args) {
new MemoryGameWindow();
}
}
This is ColoredPanel
package gui;
import java.awt.Color;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class ColoredPanel extends JPanel {
private Color thisColor = null;
private Color challenge = null;
public ColoredPanel(Color color) {
this.thisColor = color;
setBackground(color);
}
public void setGameMode(Color c, MouseListener ml) {
setBackground(Color.LIGHT_GRAY);
this.challenge = c;
System.out.println("Coloredpanel says challenge is " + this.challenge);
addMouseListener(ml);
}
public void restoreBackground() {
setBackground(this.thisColor);
}
}
This is GamePanel
package gui;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private Color[] colors = new Color[] { Color.GREEN, Color.YELLOW, Color.MAGENTA };
private Random r = new Random();
private int square = 9;
private Color challenge;
private int countOfPossibleHits = 0;
private int countOfWinnerHits = 0;
private JPanel challengeDisplay;
public GamePanel(JPanel cd) {
this.challengeDisplay = cd;
setLayout(new GridLayout(3, 0, 2, 2));
for (int i = 0; i < this.square; i++)
add(new ColoredPanel(this.colors[this.r.nextInt(this.colors.length)]));
}
public Color startGame() {
Color[] existingColors = new Color[getComponentCount()];
int i;
for (i = 0; i < getComponentCount(); i++)
existingColors[i] = ((ColoredPanel)getComponent(i)).getBackground();
this.challenge = existingColors[this.r.nextInt(existingColors.length)];
this.countOfPossibleHits = 0;
for (i = 0; i < getComponentCount(); i++) {
if (((ColoredPanel)getComponent(i)).getBackground() == this.challenge)
this.countOfPossibleHits++;
}
for (i = 0; i < getComponentCount(); i++)
((ColoredPanel)getComponent(i)).setGameMode(this.challenge, new TheMouselistener());
return this.challenge;
}
class TheMouselistener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
ColoredPanel clickedObject = (ColoredPanel)e.getSource();
clickedObject.restoreBackground();
if (clickedObject.getBackground() != GamePanel.this.challenge) {
clickedObject.add(new JLabel("Game Over!"));
GamePanel.this.challengeDisplay.add(new JLabel("Game Over!"));
System.out.println("Game Over");
GamePanel.this.updateUI();
} else {
GamePanel.this.countOfWinnerHits = GamePanel.this.countOfWinnerHits + 1;
if (GamePanel.this.countOfWinnerHits == GamePanel.this.countOfPossibleHits) {
clickedObject.add(new JLabel("You won!"));
GamePanel.this.challengeDisplay.add(new JLabel("You Won!"));
GamePanel.this.updateUI();
}
}
}
}
}
This is MemoryGameWindow
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class MemoryGameWindow extends JFrame implements ActionListener {
private JMenuItem newgame = null;
private JMenuItem playgame = null;
private JMenuItem exit = null;
private GamePanel gamepanel = null;
private JPanel challengeDisplay;
public MemoryGameWindow() {
setTitle("memory game");
setLayout(new BorderLayout(5, 5));
add(this.challengeDisplay = new JPanel() {
}, "North");
add(this.gamepanel = new GamePanel(this.challengeDisplay));
setJMenuBar(new GameMenubar(this));
setSize(600, 600);
setLocationRelativeTo((Component)null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object s = e.getSource();
if (s == this.newgame) {
remove(this.gamepanel);
remove(this.challengeDisplay);
add(this.challengeDisplay = new JPanel() {
}, "North");
add(this.gamepanel = new GamePanel(this.challengeDisplay));
this.playgame.setEnabled(true);
this.gamepanel.updateUI();
}
if (s == this.playgame) {
Color challenge = this.gamepanel.startGame();
this.challengeDisplay.setBackground(challenge);
this.playgame.setEnabled(false);
this.gamepanel.updateUI();
}
if (s == this.exit)
System.exit(0);
}
class GameMenubar extends JMenuBar {
public GameMenubar(MemoryGameWindow memoryGameWindow) {
JMenu file;
add(file = new JMenu("File"));
MemoryGameWindow.this.newgame = new JMenuItem("new board");
file.add(new JMenuItem("new board"));
MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));
MemoryGameWindow.this.exit = new JMenuItem("end program");
file.add(new JMenuItem("end program"));
MemoryGameWindow.this.newgame.addActionListener(memoryGameWindow);
MemoryGameWindow.this.playgame.addActionListener(memoryGameWindow);
MemoryGameWindow.this.exit.addActionListener(memoryGameWindow);
}
}
}
Have a look at these two lines:
MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));
First, you set the value of playgame to new JMenuItem. Later in the code, you add an ActionListener to it. That is all correct.
The problem is, the JMenuItem with the ActionListener added to it is not what you’re adding to the menu bar. Instead, you’re adding a brand new JMenuItem, which has no ActionListeners added to it.
The fix is as simple as:
file.add(MemoryGameWindow.this.playgame);
Obviously, you will need to do this for your other menu items too.
I need to divide java swing window into many fields, something similar to the table or chess board. Color of each cell should be dependent on the object which this cell represents (each object has coordinates, which are changing during the game, so the color of each cell is not constant).
Additionally, if the user clicks on the empty field (white color), then a new random object is created and this object is assigned to these field (and field color is changing).
Which of java swing controls will be the best for these functionalities?
If I were you I would make 2 panel classes(white and black), the white one with a MouseAdapter, so that when one of the panels is clicked you can pull a random JLabel from an array. Here's an example that might help (roughly 120 lines):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class ScratchPaper extends JFrame {
private static final long serialVersionUID = 1L;
private static final int GRIDSIZE = 8;
private JPanel[][] whitePanel = new WhitePanel[GRIDSIZE][GRIDSIZE];
private JPanel[][] blackPanel = new BlackPanel[GRIDSIZE][GRIDSIZE];
private Random rand = new Random();
JButton b1 = new JButton("Btn1");
JButton b2 = new JButton("Btn2");
JButton b3 = new JButton("Btn3");
JLabel l1 = new JLabel("Lbl1");
JLabel l2 = new JLabel("Lbl2");
JLabel l3 = new JLabel("Lbl3");
JPanel panel = new JPanel();
private JComponent[][] randObjects = {{b1, b2, b3}, {l1, l2, l3}, {panel, panel, panel}};
private Color[] randColors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA};
public ScratchPaper() {
initGUI();
setTitle("EXAMPLE");
pack();
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void initGUI() {
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(GRIDSIZE, GRIDSIZE)); // makes 8*8 grid
add(centerPanel, BorderLayout.CENTER);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Component clickedComp = findComponentAt(e.getPoint());
JPanel target = (JPanel) clickedComp;
panel.setBackground(randColors[rand.nextInt(randColors.length)]);
if (target instanceof WhitePanel){
target.add(randObjects[rand.nextInt(randObjects.length)][rand.nextInt(randObjects[0].length)]);
target.updateUI();
}
}
};
addMouseListener(ma);
for (int row=0; row<GRIDSIZE; row++) {
for (int col=0; col<GRIDSIZE; col++) {
whitePanel[row][col] = new WhitePanel(row, col);
blackPanel[row][col] = new BlackPanel(row, col);
if ((row%2 == 0 && col%2 == 0) || ((row+1)%2 == 0 && (col+1)%2 == 0)) {
centerPanel.add(whitePanel[row][col]);
}
else {
centerPanel.add(blackPanel[row][col]);
}
}
}
}
public static void main(String args[]) {
try {
String className = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(className);
} catch (Exception ex) {
System.out.println(ex);
}
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
new ScratchPaper();
}
});
}
class WhitePanel extends JPanel {
private static final int SIZE = 50;
public WhitePanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.WHITE);
}
}
class BlackPanel extends JPanel {
private static final int SIZE = 50;
public BlackPanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.BLACK);
}
}
}
Try running it! It's actually pretty fun!
In this GUI there are four images which place on array of DefaultComboBoxModel and label which helps to display the image. The default image is 1.png which appear on the frame. But when I select the other image from the combo list then it doesn't appear.
Code
public class Combo extends JFrame {
public Combo() {
super("Combo 2 GUI");
setSize(400, 300);
MethodG();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void MethodG() {
JLabel l1;
JComboBox box;
JPanel p;
Container pane = getContentPane();
p = new JPanel();
box = new JComboBox();
box.setModel(new DefaultComboBoxModel(new String[] { "1.png", "2.png", "3.png", "4.png" }));
box.setMaximumRowCount(3);
String boxoption = (String) box.getSelectedItem();
Icon[] icons = { new ImageIcon(getClass().getResource(boxoption)) };
// Default display
l1 = new JLabel(icons[0]);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
l1.setIcon(icons[box.getSelectedIndex()]);
}
}
});
pane.add(p);
p.add(box);
p.add(l1);
}
}
Main method
public class Main {
public static void main(String[] args) {
Combo obj = new Combo();
}
}
And the second problem what does these two lines do and how to write in if syntax.
JComboBox schemaBox;
String schema = (schemaBox.isEnabled() ? schemaBox.getSelectedItem().toString() : null);
String selectTable = (schema == null ? "" : schema + ".") + tableName;
To the first question: You have (easiest or ways) to get the icon or image icon directly from DefaultComboBoxModel, for example,
.
.
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class ComboBoxModels {
private JComboBox comboBoxDouble;
private JComboBox comboBoxInteger;
private JComboBox comboBoxBoolean;
private JComboBox comboBoxIcon;
private JComboBox comboBoxDate;
private JLabel label = new JLabel();
private Vector<Double> doubleVector = new Vector<Double>();
private Vector<Integer> integerVector = new Vector<Integer>();
private Vector<Boolean> booleanVector = new Vector<Boolean>();
private Vector<Icon> iconVector = new Vector<Icon>();
private Vector<Date> dateVector = new Vector<Date>();
private Icon icon1 = ((UIManager.getIcon("OptionPane.errorIcon")));
private Icon icon2 = (UIManager.getIcon("OptionPane.informationIcon"));
private Icon icon3 = (UIManager.getIcon("OptionPane.warningIcon"));
private Icon icon4 = (UIManager.getIcon("OptionPane.questionIcon"));
private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
public ComboBoxModels() {
doubleVector.addElement(1.001);
doubleVector.addElement(10.00);
doubleVector.addElement(0.95);
doubleVector.addElement(4.2);
comboBoxDouble = new JComboBox(doubleVector);
integerVector.addElement(1);
integerVector.addElement(2);
integerVector.addElement(3);
integerVector.addElement(4);
comboBoxInteger = new JComboBox(integerVector);
booleanVector.add(Boolean.TRUE);
booleanVector.add(Boolean.FALSE);
comboBoxBoolean = new JComboBox(booleanVector);
iconVector.addElement(icon1);
iconVector.addElement(icon2);
iconVector.addElement(icon3);
iconVector.addElement(icon4);
comboBoxIcon = new JComboBox(iconVector);
comboBoxIcon.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
Icon icon = (Icon) comboBoxIcon.getModel().getSelectedItem();
label.setIcon(icon);
}
}
});
dateVector.addElement(parseDate("25.01.2013"));
dateVector.addElement(parseDate("01.02.2013"));
dateVector.addElement(parseDate("03.03.2013"));
dateVector.addElement(parseDate("18.04.2013"));
comboBoxDate = new JComboBox(dateVector);
comboBoxDate.setRenderer(new ComboBoxRenderer());
JFrame frame = new JFrame("");
frame.setLayout(new GridLayout(2, 2, 5, 5));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(comboBoxDouble);
frame.add(comboBoxInteger);
frame.add(comboBoxBoolean);
frame.add(comboBoxIcon);
frame.add(comboBoxDate);
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Date parseDate(String str) {
Date date = new Date();
try {
date = sdf.parse(str);
} catch (ParseException ex) {
}
return date;
}
private class ComboBoxRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
public ComboBoxRenderer() {
setOpaque(true);
setBorder(new EmptyBorder(1, 1, 1, 1));
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (!(value instanceof Date)) {
return this;
}
setText(sdf.format((Date) value));
return this;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxModels comboBoxModel = new ComboBoxModels();
}
});
}
}
Your icons array isn't being initialized as you expect. The code you have is creating an array with only one entry - 1.png. You'll need to initialize your array to contain all the images. Something like this:
Icon[] icons = { new ImageIcon(getClass().getResource("1.png")),
new ImageIcon(getClass().getResource("2.png")),
new ImageIcon(getClass().getResource("3.png")),
new ImageIcon(getClass().getResource("4.png"))};
i am working on a word processor and my hope is to allow the user do what all word processors allow them to do. My issue at the moment is trying to understand how to force text that is being wrote by the user on to the next line once the maximum width has been reached (the size of the frame). For example if i am writing a sentence (or question on stack overflow) once my text hits the boundary of the text area it automatically brings me to the next line without me pressing Enter/return. After doing some research into line wrapping i came across the following
http://www.java-forums.org/awt-swing/59790-line-wrapping-jtextpane.html
Toggling text wrap in a JTextpane
however i cannot seem to get the behavior i want from the JTextPane below is my code, as always i appreciate any assistance offered.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class WordFrame{
private JFrame appFrame;
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, viewMenu;
JMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, fontMenuItem;
JTextPane textArea = new JTextPane();
static final int WIDTH = 1280, HEIGHT = 980;
private JScrollPane scrollBar = new JScrollPane(textArea);
JPanel wordPanel = new JPanel();
JFileChooser fileChooser = new JFileChooser();
private int textHeight = 12;
private Font defaultFont = new Font(Font.SANS_SERIF, 2, textHeight);
public WordFrame(){
appFrame = new JFrame();
setUI();
addMenuBar();
textArea.setFont(defaultFont);
}
public JFrame getAppFrame(){
return appFrame;
}
public void setFrameVisibility(boolean isVisible){
if(isVisible == true){
appFrame.setVisible(true);
}
else{
appFrame.setVisible(false);
}
}
public void setUI(){
appFrame.setTitle("Word Processor");
appFrame.setIconImage(new ImageIcon(this.getClass().getResource("Bridge.jpg")).getImage());
appFrame.setSize(WIDTH, HEIGHT);
appFrame.setLocation(0,0);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// scrollbar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
wordPanel.setLayout(new BorderLayout());
appFrame.add(wordPanel);
textArea.setPreferredSize(new Dimension(400,500));
appFrame.add(scrollBar);
wordPanel.add(textArea);
scrollBar.setViewportView(wordPanel);
}
public void addMenuBar(){
menuBar = new JMenuBar();
fileMenu = new JMenu(" File ");
editMenu = new JMenu("Edit ");
viewMenu = new JMenu("View ");
newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
fileMenu.addSeparator();
fileMenu.setMnemonic('f');
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
saveMenuItem = new JMenuItem("Save");
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
fontMenuItem = new JMenuItem("Font");
editMenu.add(fontMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
appFrame.setJMenuBar(menuBar);
}
public void setFontSize(int i){
this.textHeight = i;
}
public void addListener(ActionListener listener){
openMenuItem.addActionListener(listener);
exitMenuItem.addActionListener(listener);
saveMenuItem.addActionListener(listener);
}
}
After inserting code that i found on the internet. The text wraps once the edge (right) is hit by the text (basically if it goes to the max right of the application screen it automatically drops down to a new line. However a new issue has occurred this involves the JScrollBar, as everyone would expect, once text hits the bottom of the application screen a scrollbar would update to offer the user the ability to scroll up and down the page, this would make sense, however my code doesn't allow this. Here is the ammended code after my attempt to fix the line wrap issue (i still consider this the same question), further more if the following is commented out, text wrapping no longer works
textArea.setPreferredSize(new Dimension(400,500));
the code up there causes text wrap to fail completely.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class WordFrame{
private JFrame appFrame;
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, viewMenu;
JMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, fontMenuItem;
JTextPane textArea = new JTextPane();
static final int WIDTH = 1280, HEIGHT = 980;
private JScrollPane scrollBar = new JScrollPane(textArea);
JPanel wordPanel = new JPanel();
JFileChooser fileChooser = new JFileChooser();
private int textHeight = 12;
private Font defaultFont = new Font(Font.SANS_SERIF, 2, textHeight);
public WordFrame(){
appFrame = new JFrame();
setUI();
addMenuBar();
textArea.setFont(defaultFont);
}
public JFrame getAppFrame(){
return appFrame;
}
public void setFrameVisibility(boolean isVisible){
if(isVisible == true){
appFrame.setVisible(true);
}
else{
appFrame.setVisible(false);
}
}
public void setUI(){
appFrame.setTitle("Word Processor");
appFrame.setIconImage(new ImageIcon(this.getClass().getResource("Bridge.jpg")).getImage());
appFrame.setSize(WIDTH, HEIGHT);
appFrame.setLocation(0,0);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollBar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
wordPanel.setLayout(new BorderLayout());
// appFrame.getContentPane().add(scrollBar, BorderLayout.CENTER);
textArea.setPreferredSize(new Dimension(400,500));
appFrame.add(wordPanel);
appFrame.add(scrollBar);
wordPanel.add(textArea);
// appFrame.add(textArea);
scrollBar.setViewportView(wordPanel);
textArea.setEditorKit(new WrapEditorKit());
}
public void addMenuBar(){
menuBar = new JMenuBar();
fileMenu = new JMenu(" File ");
editMenu = new JMenu("Edit ");
viewMenu = new JMenu("View ");
newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
fileMenu.addSeparator();
fileMenu.setMnemonic('f');
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
saveMenuItem = new JMenuItem("Save");
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
fontMenuItem = new JMenuItem("Font");
editMenu.add(fontMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
appFrame.setJMenuBar(menuBar);
}
public void setFontSize(int i){
this.textHeight = i;
}
public void addListener(ActionListener listener){
openMenuItem.addActionListener(listener);
exitMenuItem.addActionListener(listener);
saveMenuItem.addActionListener(listener);
fontMenuItem.addActionListener(listener);
}
class WrapEditorKit extends StyledEditorKit {
ViewFactory defaultFactory=new WrapColumnFactory();
public ViewFactory getViewFactory() {
return defaultFactory;
}
}
class WrapColumnFactory implements ViewFactory {
public View create(Element elem) {
String kind = elem.getName();
if (kind != null) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new WrapLabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
}
}
class WrapLabelView extends LabelView {
public WrapLabelView(Element elem) {
super(elem);
}
public float getMinimumSpan(int axis) {
switch (axis) {
case View.X_AXIS:
return 0;
case View.Y_AXIS:
return super.getMinimumSpan(axis);
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
}
}
I'm pretty new to programming, and I need to create a GUI for a pethouse program that allows the user to add, delete, and sort the records.
The problem is that for whatever reason my ActionListeners are not working. The GUI opens fine enough, but if I click on a menu item, nothing happens. The Quit MenuItem doesn't do anything, nor does the add animal do anything. The delete doesn't work either (though that may also be a programming error on my part.)
Here's the Code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import scrap.knockoff;
public class knockoff extends JFrame {
private ButtonHandler handler;
static int animals;
static Color Backgroundcolor = Color.red;
private JTable thelist;
private JTextField search, breed, category, buyprice, sellprice;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuAdd, menuDelete, menuQuit;
private JLabel maintitle, breedquery, categoryquery, buypricequery, sellpricequery;
private JButton sortbreed, sortcat, sortdog, sortratios, searchButton, add, delete, modify;
private JPanel animalPane, sortPane, titlePane, searchPane, tablePane, optionPane;
static Container container;
static int recnumber;
static String control[] = new String[100];
static double buyprices, sellprices, profitratios;
static String BreedName, CategoryName;
static String Pets[][] = new String[50][5];
public knockoff() {
super("The Peel Pet House Program"); //This just changes the name at the top there.
setSize(700, 600);
Border paneEdge = BorderFactory.createEmptyBorder(0, 10, 10, 10);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setLocation(0, 30);
tabbedPane.setSize(200, 100);
//These are our panels. The sortPane just keeps the buttons responsible for sorting the animals where they are. The animalPane is for the other functions (add, delete, whatnot) and the title pane
//just holds the title. The AnimalPane is just a constant, it's there just so that the Animals menu process has a place to be. The Table Pane holds the table.
tablePane = new JPanel();
tablePane.setLocation(200, 35);
tablePane.setSize(500, 500);
titlePane = new JPanel();
titlePane.setSize(700, 30);
animalPane = new JPanel();
Border greenline = BorderFactory.createLineBorder((Color.green).darker());
animalPane.setBorder(greenline);
animalPane.setLocation(0, 135);
animalPane.setSize(200, 400);
sortPane = new JPanel();
sortPane.setBorder(paneEdge);
search = new JTextField();
searchButton = new JButton("Search");
searchPane = new JPanel();
FlowLayout searchLayout = new FlowLayout();
searchPane.setLayout(searchLayout);
searchPane.setBorder(paneEdge);
search.setPreferredSize(new Dimension(190, 30));
searchPane.add(search);
searchPane.add(searchButton);
optionPane = new JPanel();
optionPane.setSize(100, 30);
//This establishes our table
String[] columns = {"Breed", "Category", "Buying Price", "Selling Price", "Profit Ratio"};
thelist = new JTable(Pets, columns);
JScrollPane listbrowser = new JScrollPane(thelist);
tablePane.add(listbrowser);
//These establish the buttons for our various sorting sprees.
sortbreed = new JButton("Breed");
sortcat = new JButton("Cat");
sortdog = new JButton("Dog");
sortratios = new JButton("Profit Ratio");
sortPane.add(sortbreed);
sortPane.add(sortcat);
sortPane.add(sortdog);
sortPane.add(sortratios);
//Our ever reliable menu bar maker.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
menu = new JMenu("File");
menuBar.add(menu);
//The items of the file menu.
menuQuit = new JMenuItem("Quit");
menuQuit.addActionListener(handler);
menu.add(menuQuit);
//Animal Menu Creation
menu = new JMenu("Animals");
menuBar.add(menu);
menuAdd = new JMenuItem("Add an Animal");
menuAdd.addActionListener(handler);
menu.add(menuAdd);
menuDelete = new JMenuItem("Delete Animal");
menuDelete.addActionListener(handler);
menu.add(menuDelete);
//Adding everything to the container now.
Container container = getContentPane();
container.setLayout(null);
maintitle = new JLabel("The Piddly Penultimate Peel Pet House Program");
titlePane.add(maintitle);
container.setBackground(Backgroundcolor.darker()); //This just makes a darker version of red to set as the background on the Content Pane. Grey is boring.
container.add(tablePane);
container.add(titlePane);
container.add(tabbedPane);
container.add(animalPane);
container.add(optionPane);
tabbedPane.addTab("Sort By:", null, sortPane, "Sorts the Table");
tabbedPane.addTab("Search", null, searchPane, "The Search Function");
}
public static void main(String args[]) {
knockoff application = new knockoff();
application.setVisible(true);
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.equals("Add an Animal")) {
addananimal();
} else if (event.equals("Delete Animal")) {
deleteanimal();
} else if (event.getSource().equals(add)) //getsource relates to the button, it just makes it so that anybody programming can freely change the text of the button without worrying about this.
{
addanimal();
} else if (event.getSource().equals(delete)) {
deleteanimal();
} else if (event.getSource().equals(sortbreed)) {
breedsort();
} else if (event.getSource().equals(sortcat)) {
} else if (event.getSource().equals(sortdog)) {
} else if (event.getSource().equals(sortratios)) {
} else if (event.equals("Quit")) {
hide();
System.exit(0);
}
}
//Add new Record Method
public void addananimal() {
container = getContentPane();
//Plate cleaner. Or dishwasher.
if (animalPane != null) {
container.remove(animalPane);
}
animalPane = new JPanel();
Border greenline = BorderFactory.createLineBorder((Color.green).darker());
animalPane.setBorder(greenline);
animalPane.setLocation(0, 135);
animalPane.setSize(200, 400);
FlowLayout animalLayout = new FlowLayout();
animalPane.setLayout(animalLayout);
breedquery = new JLabel("Add Animal Name:");
categoryquery = new JLabel("Cat or Dog?");
buypricequery = new JLabel("Buying Price:");
sellpricequery = new JLabel("Selling Price:");
animalPane.add(breedquery);
breed = new JTextField(18);
animalPane.add(breed);
animalPane.add(categoryquery);
category = new JTextField(18);
animalPane.add(category);
animalPane.add(buypricequery);
buyprice = new JTextField(18);
animalPane.add(buyprice);
animalPane.add(sellpricequery);
sellprice = new JTextField(18);
add = new JButton("Add Animal");
//The above list of .add and JComponent things were just to establish the
// contents of our new animalPane.
profitratios = Double.parseDouble(sellprice.getText()) / Double.parseDouble(buyprice.getText());
//This just makes finding the profit ratio an autonomous action.
add.addActionListener(handler);
animalPane.add(add);
container.add(animalPane);
setVisible(true);
}
public void addanimal() {
animals = animals + 1;
Pets[animals][0] = breed.getText();
Pets[animals][1] = category.getText();
Pets[animals][2] = buyprice.getText();
Pets[animals][3] = sellprice.getText();
Pets[animals][4] = profitratios + "";
breed.setText(" ");
category.setText(" ");
buyprice.setText(" ");
sellprice.setText(" ");
thelist.repaint(); //This is supposed to update the JTable in real time.
}
public void deleteanimal() {
removeSelectedRows(thelist);
}
public void removeSelectedRows(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] rows = table.getSelectedRows();
for (int x = 0; x < rows.length; ++x) {
model.removeRow(rows[x] - x);
}
for (int x = 0; x < animals; ++x) {
if (Pets[x][0].equalsIgnoreCase(table.getValueAt(table.getSelectedRow(), 0) + "")) {
Pets[x][0] = null;
Pets[x][1] = null;
Pets[x][2] = null;
Pets[x][3] = null;
Pets[x][4] = null;
}
}
}
public void breedsort() {
for (int x = 0; x < animals; ++x) {
}
}
}
}
You never initialize the ButtonHandler, meaning that every time you call addActionListener(handler) you are essentially calling addActionListener(null)
Try initializing the handler in the constructor BEFORE you add it to anything...
public knockoff() {
super("The Peel Pet House Program"); //This just changes the name at the top there.
handler = new ButtonHandler();
Updated
Better yet, take a look at the Action API instead
You're not instantiating and regstering ButtonHandler anywhere...