This is my program below and I am trying to figure out where my main method should be. I have seen a few examples of it being implemented at the very end of the program but there main is different from mine.
Main method (to be implemented):
public class JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setTitle("Components File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
My Program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Lab_10 extends JFrame
{
private final double EARTHQUAKE_RATE= 8.0;
private final int FRAME_WIDTH= 300;
private final int FRAME_HEIGHT= 200;
private JLabel rLabel;
private JTextField eField;
private JButton button;
private JLabel earthLabel;
public Lab_10()
{
JLabel earthLabel = new JLabel("Most structures fall");
makeTextField();
makeButton();
makePanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void makeTextField()
{
JLabel rLabel = new JLabel("Richter");
final int FIELD_WIDTH = 10;
eField = new JTextField(FIELD_WIDTH);
eField.setText("" + EARTHQUAKE_RATE);
}
class AddLabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
earthLabel.setText("Most structures fall");
}
}
private void makeButton()
{
JButton button = new JButton("Enter");
ActionListener listener = new AddLabelListener();
button.addActionListener(listener);
}
private void makePanel()
{
JPanel panel = new JPanel();
panel.add(rLabel);
panel.add(eField);
panel.add(button);
panel.add(earthLabel);
add(panel);
}
}
Updated Code (which is compiling but and running but with logic errors because it implements an empty frame [guess as much from the main method I have]):
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Lab_10 extends JFrame
{
private final double EARTHQUAKE_RATE= 8.0;
private final int FRAME_WIDTH= 300;
private final int FRAME_HEIGHT= 200;
private JLabel rLabel;
private JTextField eField;
private JButton button;
private JLabel earthLabel;
public Lab_10()
{
JLabel earthLabel = new JLabel("Most structures fall");
makeTextField();
makeButton();
makePanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void makeTextField()
{
JLabel rLabel = new JLabel("Richter");
final int FIELD_WIDTH = 10;
eField = new JTextField(FIELD_WIDTH);
eField.setText("" + EARTHQUAKE_RATE);
}
class AddLabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
earthLabel.setText("Most structures fall");
}
}
private void makeButton()
{
JButton button = new JButton("Enter");
ActionListener listener = new AddLabelListener();
button.addActionListener(listener);
}
private void makePanel()
{
JPanel panel = new JPanel();
panel.add(rLabel);
panel.add(eField);
panel.add(button);
panel.add(earthLabel);
add(panel);
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
#Override
public void run()
{ JFrame frame = new JFrame();
frame.setTitle("Components File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Your 'main' probably looks different because you are not using SwingUtilities.invokeLater(Runnable doRun) ?
Well, to put it simply, you must use it always. So, modify your code and use this:
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
// copy-paste your main() code
}
});
Also, why is your class named JFrame ? Refrain from using names that are already used by Java classes already.
Related
I started codig Java last weekend and I've read most of the basic stuff. I'm trying to separate my frame from main method, and panels from the frame so they are all in separate class files. I have trouble calling ActionLister in "Frame1" class with a button (buttonBack) in the "TheGame" class. The button should trigger the Listener which in turn should remove theGame panel and add mainMenu panel to frame1. I know that CardLayout is better suited for swapping panels but i want to learn the limits and workarounds before i go do it the "easy" way, i feel that you learn much more that way.
Here is some of my code:
Main:
public class Main {
public static void main(String[] args){
Frame1 frame1 = new Frame1();
frame1.frame1();
}
}
Frame1:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
class Frame1 {
private JFrame frame1 = new JFrame("Name");
public void frame1() {
TheGame theGame = new TheGame();
MainMenu mainMenu = new MainMenu();
// Frame options
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLocationRelativeTo(null);
// Creating a top menu
JMenuBar menubar = new JMenuBar();
frame1.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenuItem about = new JMenuItem("About");
help.add(about);
// Creating action for the menuitem "exit".
class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
exit.addActionListener(new exitaction());
// Creating listener for the menuitem "about".
class aboutaction implements ActionListener{
public void actionPerformed (ActionEvent e){
JDialog dialogabout = new JDialog();
JOptionPane.showMessageDialog(dialogabout, "Made by: ");
}
}
about.addActionListener(new aboutaction());
// Add the panels, pack and setVisible
theGame.theGame();
mainMenu.mainMenu();
frame1.add(theGame.getGUI());
// This is the ActionListener i have trouble connecting with the buttonBack in the "theGame" class
class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
frame1.remove(theGame.getGUI());
frame1.add(MainMenu.getGUI());
}
}
frame1.pack();
frame1.setVisible(true);
}
public JFrame getGUI() {
return frame1;
}
}
MainMenu:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class MainMenu {
private JPanel mainMenu = new JPanel (new GridBagLayout());
public void mainMenu() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating Label
JLabel introduction = new JLabel("Name");
grid.gridx = 1;
grid.gridy = 3;
mainMenu.add(introduction, grid);
// Creating buttons Start Game, Highscore and Exit Game
JButton buttonNewGame = new JButton("New Game");
buttonNewGame.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 5;
mainMenu.add(buttonNewGame, grid);
JButton buttonHighscore = new JButton("Highscore");
buttonHighscore.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 6;
mainMenu.add(buttonHighscore, grid);
JButton buttonExit = new JButton("Exit Game");
buttonExit.setPreferredSize(new Dimension(200, 50));
grid.gridx = 1;
grid.gridy = 7;
mainMenu.add(buttonExit, grid);
}
public JComponent getGUI() {
return mainMenu;
}
}
TheGame:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
class TheGame {
private JPanel theGame = new JPanel (new GridBagLayout());
public void theGame() {
// Using the GridBagLayout therefore creating the constraints "grid"
GridBagConstraints grid = new GridBagConstraints();
// Adjusting grid insets
grid.insets = new Insets(10, 10, 10, 10);
// Creating a label
JLabel label1 = new JLabel("Press the BACK button to go back to Main Menu");
label1.setVisible(true);
grid.gridx = 1;
grid.gridy = 0;
theGame.add(label1,grid);
// Creating BACK button
JButton buttonBack = new JButton("BACK");
buttonBack.setVisible(true);
grid.gridx = 1;
grid.gridy = 1;
buttonBack.addActionListener(new --); // This is the button i want to connect with the ActionListener on Frame1 class
theGame.add(buttonBack, grid);
}
public JComponent getGUI() {
return theGame;
}
}
I've tried moving the ActionListener outside of methods, inside the Main, declaring it static, but haven't been able to call it anyways. I've also looked at other posts like this: Add an actionListener to a JButton from another class but have not been able to implement it in to my code.
Any help is appreciated.
The best answer -- use MVC (model-view-controller) structure (and CardLayout) for the swapping of your views. If you don't want to do that, then your listener should have a reference to the container that does the swapping, and so that the listener can notify this container that a swap should occur. The container will then call its own code to do the swapping. To do this you need to pass references around including a reference to the main GUI to wherever it is needed. This can get messy, which is why MVC, which is more work, is usually better -- fewer connections/complexity in the long term.
Side note -- don't pass a JDialog into a JOptionPane as a JOptionPane is a specialized JDialog, and you shouldn't have a top level window displaying a top level window. Instead pass in a JPanel.
For example:
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PassRef {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
MyMain mainPanel = new MyMain();
JFrame frame = new JFrame("Pass Reference");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class MyMain extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
private CardLayout cardLayout = new CardLayout();
private MenuView menuView = new MenuView(this);
private ActionView1 actionView1 = new ActionView1(this);
public MyMain() {
setLayout(cardLayout);
add(menuView, MenuView.NAME);
add(actionView1, ActionView1.NAME);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public void showCard(String key) {
cardLayout.show(this, key);
// or swap by hand if you don't want to use CardLayout
// but remember to revalidate and repaint whenever doing it by hand
}
}
class MenuView extends JPanel {
public static final String NAME = "Menu View";
public MenuView(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder("Menu"));
add(new JButton(new GoToAction("Action 1", ActionView1.NAME, myMain)));
}
}
class ActionView1 extends JPanel {
public static final String NAME = "Action View 1";
public ActionView1(MyMain myMain) {
setName(NAME);
setBorder(BorderFactory.createTitledBorder(NAME));
add(new JButton(new GoToAction("Main Menu", MenuView.NAME, myMain)));
}
}
class GoToAction extends AbstractAction {
private String key;
private MyMain myMain;
public GoToAction(String name, String key, MyMain myMain) {
super(name);
this.key = key;
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
myMain.showCard(key);
}
}
Can someone please tell me why the Timer is trying to Convert an int into a String. Here is the error that keeps coming up.
CurrentTimePrinter.java:48: error: incompatible types: int cannot be
converted to String
time = new Timer(1000,listener);
CurrentTimePrinter.java:49: error: cannot find symbol
time.start();
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Date;
import java.util.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
public class CurrentTimePrinter extends JFrame
{
private JButton Exitbutton;
private JTextField textField;
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 400;
private ActionListener listener;
public Timer time;
public CurrentTimePrinter()
{
//listener = new CtpListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createComponents()
{
Color orange = new Color(255,165,0);
Font font = new Font("Times New Roman", Font.BOLD, 14);
textField = new JTextField(FIELD_WIDTH);
Exitbutton = new JButton("EXIT");
class CtpListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
textField.setText("" + new Date());
Date now = new Date();
System.out.println(now);
}
}
ActionListener listener = new CtpListener();
time = new Timer(1000,listener);
time.start();
Exitbutton.setFont(font);
Exitbutton.setForeground(Color.BLACK);
ExitButtonListener exitListener = new ExitButtonListener();
Exitbutton.addActionListener(exitListener);
JPanel panel1 = new JPanel();
time = new Timer(1000, listener);
time.start();
JPanel panel2 = new JPanel();
panel1.setBackground(orange);
panel1.add(Exitbutton);
panel2.add(textField);
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.SOUTH);
contentPane.add(panel2, BorderLayout.CENTER);
setContentPane(contentPane);
}
class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
public static void main(String[] args)
{
JFrame frame = new CurrentTimePrinter();
frame.setTitle("Current Time");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
You are using java.util.Timer. You want javax.swing.Timer here.
Replace that in the imports, it should be:
import javax.swing.Timer;
I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.
I' making this simple paintbrush-type paint toolbox (some interesting ideas in my previous question)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class MainClass2{
static JLabel colorlabel = new JLabel(" Color ");
public static JLabel xlab = new JLabel("0");
public static JLabel ylab = new JLabel("0");
static JFrame frame1 = new JFrame();
static JButton quitbutton = new JButton("Quit");
static JButton infobutton = new JButton("Info");
static JButton clearbutton = new JButton("Clear");
static JButton savebutton = new JButton("Save");
private static int stroke1 = 4;
static SpinnerNumberModel spinnervals = new SpinnerNumberModel(stroke1,1,15,1);
static JSpinner spinnerbrush = new JSpinner(spinnervals);
static JButton selectcolor = new JButton("Select Color");
static JButton selectbg = new JButton("Select Background");
public static Color col1 = Color.WHITE;
private static Color col2 = Color.WHITE;
static AuxClass4 panel1 = new AuxClass4(col1, col2, stroke1);
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JPanel panel4 = new JPanel();
private static void addPanel1(){
panel1.setPreferredSize(new Dimension(800,500));
}
private static void addPanel2(){
ButtonAction inst1 = new ButtonAction();
xlab.setMinimumSize(new Dimension(30,30));
ylab.setMinimumSize(new Dimension(30,30));
xlab.setBorder(BorderFactory.createLineBorder(Color.BLACK));
ylab.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel2.add(new JLabel(" X: "));
panel2.add(xlab);
panel2.add(new JLabel(" Y: "));
panel2.add(ylab);
panel2.add(savebutton);
panel2.add(clearbutton);
panel2.add(quitbutton);
panel2.add(infobutton);
panel2.setLayout(new FlowLayout());
quitbutton.addActionListener(inst1);
infobutton.addActionListener(inst1);
clearbutton.addActionListener(inst1);
savebutton.addActionListener(inst1);
selectcolor.addActionListener(inst1);
selectbg.addActionListener(inst1);
}
//add to panel3
private static void addPanel3(){
StrokeAction inst2 = new StrokeAction();
spinnerbrush.addChangeListener(inst2);
panel3.add(new JLabel("Stroke size"));
panel3.add(spinnerbrush);
panel3.add(selectcolor);
panel3.add(new JLabel("Current color:"));
colorlabel.setSize(20, 20);
colorlabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
colorlabel.setOpaque(true);
colorlabel.setBackground(Color.WHITE);
colorlabel.setForeground(Color.WHITE);
panel3.add(colorlabel);
panel3.add(selectbg);
}
private static class ButtonAction implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==quitbutton){
System.exit(0);
}
else if(arg0.getSource()==infobutton){
JOptionPane.showMessageDialog(frame1, "Paint Toolbox designed in Java");
}
else if(arg0.getSource()==selectcolor){
panel1.changeColor();
}
else if(arg0.getSource()==selectbg){
panel1.changeBg();
}
else if(arg0.getSource()==clearbutton){
panel1.colfg = panel1.colbg;
colorlabel.setBackground(panel1.colfg);
colorlabel.setForeground(panel1.colfg);
panel1.setForeground(null);
}
else if(arg0.getSource()==savebutton){
panel1.saveImage();
}
}
}
private static class StrokeAction implements ChangeListener{
#Override
public void stateChanged(ChangeEvent arg0) {
if (arg0.getSource()==spinnerbrush){
Object o1 = spinnervals.getValue();
Integer int1 = (Integer) o1;
stroke1 = int1.intValue();
panel1.changeStroke(stroke1);
}
// TODO Auto-generated method stub
}
}
public static void main(String args[]){
addPanel1();
addPanel2();
addPanel3();
frame1.add(panel1, BorderLayout.NORTH);
frame1.add(panel2, BorderLayout.SOUTH);
frame1.add(panel3, BorderLayout.CENTER);
frame1.setTitle("PaintBox v2.2");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.setSize(800,600);
frame1.setResizable(false);
frame1.setLocationRelativeTo(null);
frame1.setVisible(true);
}
}
class AuxClass4 extends JPanel implements MouseMotionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private int xval;
private int yval;
public Color colfg;
public Color colbg;
public int strokesize;
public int fileorder;
public AuxClass4(Color input1, Color input2, int input3){
colfg=input1;
colbg=input2;
strokesize = input3;
this.setBorder(BorderFactory.createLineBorder(Color.CYAN, 10));
this.setBackground(colbg);
//this.setMaximumSize(new Dimension(500,380));
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g1){
super.paintComponent(g1);
g1.setColor(colfg);
g1.fillRect(xval, yval, strokesize, strokesize);
}
#Override
public void mouseDragged(MouseEvent arg0) {
xval = arg0.getX();
yval = arg0.getY();
repaint(xval, yval, strokesize,strokesize);
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent arg0) {
xval = arg0.getX();
yval = arg0.getY();
String xvalret = Integer.toString(xval);
String yvalret = Integer.toString(yval);
MainClass2.xlab.setText(" " + xvalret + " ");
MainClass2.ylab.setText(" " + yvalret + " ");
}
public void changeColor(){
colfg = JColorChooser.showDialog(this, "Select color", colfg);
MainClass2.colorlabel.setBackground(colfg);
MainClass2.colorlabel.setForeground(colfg);
}
public void changeBg(){
colbg=JColorChooser.showDialog(this, "Select color", Color.WHITE);
colfg=colbg;
this.setBackground(colbg);
MainClass1.colorlabel.setBackground(colfg);
MainClass1.colorlabel.setForeground(colfg);
}
public void changeStroke(int inputstroke){
strokesize=inputstroke;
}
public void saveImage(){
final String dir = System.getProperty("user.dir");
JOptionPane.showMessageDialog(this, "File saved under " + dir + "/saveimage" + fileorder +".png");
fileorder+=1;
}
}
It works fine for now, but I started wondering if it is possible to implement undo and redo methods for Graphics objects. Intuitively, there should be some way to add the created objects to some table in a 'historical' order. User then should be able to navigate in this table.
Unfortunately, I have no experience with this approach, especially with graphics, so any suggestion would be massively welcome.
I would recommend UndoManager
http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/UndoManager.html
See also the example
http://www.java2s.com/Code/Java/Swing-JFC/Undomanager.htm
Take a look at the command pattern. I think this javaworld article explains it quite nicely.
In a nutshell you will have to have an interface containing undo and redo. Objects that implement this will be added to a list. As you undo and redo you can navigate through the list calling undo and redo. It means that you may have to write more code becuase for every event you actually draw you will have to write the equivelent to undo it.
I just created an applet
public class HomeApplet extends JApplet {
private static final long serialVersionUID = -7650916407386219367L;
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
// setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
RconSection rconSection = new RconSection();
rconSection.setOpaque(true);
// CommandArea commandArea = new CommandArea();
// commandArea.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setSize(400, 400);
tabbedPane.addTab("Rcon Details", rconSection);
// tabbedPane.addTab("Commad Area", commandArea);
setContentPane(tabbedPane);
}
}
where the fisrt tab is:
package com.rcon;
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.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.Bean.RconBean;
import com.util.Utility;
public class RconSection extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -9021500288377975786L;
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
// private DynamicTree treePanel;
public RconSection() {
// super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new GridLayout(1,3));
panel1.add(testButton);
panel1.add(clearButton);
add(panel);
add(panel1);
// add(panel, BorderLayout.NORTH);
// add(panel1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(TEST_COMMAND)){
String ip = ipText.getText().trim();
if(!Utility.checkIp(ip)){
ipText.requestFocusInWindow();
ipText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Ip!!!");
return;
}
String port = portText.getText().trim();
if(port.equals("") || !Utility.isIntNumber(port)){
portText.requestFocusInWindow();
portText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Port!!!");
return;
}
String pass = rPassText.getText().trim();
if(pass.equals("")){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Enter Rcon Password!!!");
return;
}
RconBean rBean = RconBean.getBean();
rBean.setIp(ip);
rBean.setPassword(pass);
rBean.setPort(Integer.parseInt(port));
if(!Utility.testConnection()){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Rcon!!!");
return;
}else{
JOptionPane.showMessageDialog(this,"Correct Rcon!!!");
return;
}
}
else if(arg0.getActionCommand().equals(CLEAR_COMMAND)){
ipText.setText("");
portText.setText("");
rPassText.setText("");
}
}
}
it appears as
is has cropped some data how to display it full and make the applet non resizable as well. i tried setSize(400, 400); but it didnt helped the inner area remains the same and outer boundaries increases
Here's another variation on your layout. Using #Andrew's tag-in-source method, it's easy to test from the command line:
$ /usr/bin/appletviewer HomeApplet.java
// <applet code='HomeApplet' width='400' height='200'></applet>
import java.awt.BorderLayout;
import java.awt.GridLayout;
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;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class HomeApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private void createGUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Rcon1", new RconSection());
tabbedPane.addTab("Rcon2", new RconSection());
this.add(tabbedPane);
}
private static class RconSection extends JPanel implements ActionListener {
private static final String TEST_COMMAND = "test";
private static final String CLEAR_COMMAND = "clear";
private JTextField ipText = new JTextField();
private JTextField portText = new JTextField();
private JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel buttons = new JPanel(); // default FlowLayout
buttons.add(testButton);
buttons.add(clearButton);
add(panel, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
}
}
As I mentioned in a comment, this question is really about how to layout components in a container. This example presumes you wish to add the extra space to the text fields and labels. The size of the applet is set in the HTML.
200x130 200x150
/*
<applet
code='FixedSizeLayout'
width='200'
height='150'>
</applet>
*/
import java.awt.*;
import javax.swing.*;
public class FixedSizeLayout extends JApplet {
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initGui();
}
});
}
private void initGui() {
JTabbedPane tb = new JTabbedPane();
tb.addTab("Rcon Details", new RconSection());
setContentPane(tb);
validate();
}
}
class RconSection extends JPanel {
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout(3,3));
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
panel1.add(testButton);
panel1.add(clearButton);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container c = new RconSection();
JOptionPane.showMessageDialog(null, c);
}
});
}
}
Size of applet viewer does not depend on your code.
JApplet is not window, so in java code you can't write japplet dimensions. You have to change run settings. I don't know where exactly are in other ide's, but in Eclipse you can change dimensions in Project Properties -> Run/Debug settings -> click on your launch configurations file (for me there were only 1 - main class) -> edit -> Parameters. There you can choose width and height for your applet. save changes and you are good to go