Connect jbutton to void class - java

I wanted to connect jcomp1 to the void class somma
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings({ "unused", "serial" })
public class Calcolatrice extends JPanel {
private JButton jcomp1;
public Calcolatrice() {
//construct components
jcomp1 = new JButton ("Somma");
}
void somma(){
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
And I tried with:
jcomp1.addActionListener(new ActionListener() {
public void somma(ActionEvent e) {
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
} );
But it doesn't seem to work...
Any ideas?
I just started coding and I thought this was an easy project but I'm already having troubles. For this reason could you explain as clear as possible please? Thank you.

This is an example of how to create a basic java swing frame with an interactive button.
public class Win extends JFrame implements ActionListener {
private JButton btn;
private JTextField tf;
private JTextField tf1;
private Label label;
private Panel panel;
public Win() {
btn = new JButton("Click");
tf = new JTextField(" ");
tf1 = new JTextField(" ");
label = new Label();
label.setPreferredSize(new Dimension(300,100));
panel = new Panel();
btn.addActionListener(this);
panel.add(btn);
panel.add(tf);
panel.add(tf1);
panel.add(label);
this.add(panel);
this.setSize(500, 500);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
label.setText(tf.getText()+" "+tf1.getText());
System.out.println("clicked");
}
}
You just need to instanciate the win class inside your main method.

Related

Changing panels in gui

What I am trying to do is change the right side of my GUI each time I press a button. First button shows a JLabel second button a JTextField. Expected outcome change in panels. Outcome is that when I press the buttons nothing happens.
package javaapplication37;
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.JLabel;
import javax.swing.*;
public class Gui extends JFrame {
JTextField f1;
JPanel b, p1, p2;
JPanel p3;
JLabel l1;
JButton b2, b1;
String a;
public Gui() {
a="Input here";
setSize(600,600);
l1=new JLabel("8a petuxei");
b = new JPanel();
p3 = new JPanel();
p1 = new JPanel();
p2 = new JPanel();
b.setLayout(new GridLayout(2, 1));
b1 = new JButton("Eleos");
b2 = new JButton("elpizw");
b.add(b1);
b.add(b2);
b.setSize(150,600);
p1.setSize(450,600);
add(b);
add(p1);
ActionListener pou = new Listener(p1);
b1.addActionListener(pou);
p2.add(l1);
f1=new JTextField(a);
a=f1.getText();
p3.add(f1);
}
public class Listener implements ActionListener {
JPanel k;
public Listener(JPanel k) {
this.k = k;
}
#Override
public void actionPerformed(ActionEvent e) {
k.remove(getContentPane());
k.add(p2);
}
}
public class l implements ActionListener {
JPanel k;
public l(JPanel k) {
this.k = k;
}
#Override
public void actionPerformed(ActionEvent e) {
k.remove(getContentPane());
k.add(p3);
}
}
}
You need to be using a CardLayout. If you need help ask me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class Gui extends JFrame implements ActionListener {
private JPanel menu = new JPanel();
private CardLayout contentLayout = new CardLayout();
private JPanel content = new JPanel(contentLayout);
private java.util.List<Card> cardList = new ArrayList<>();
public Gui() {
int i;
for (i = 0; i < 10; i++) {
Card card;
if(i % 2 == 0) card = new TextAreaCard("Card " + i, "this is the content for card #" + i);
else card = new LabelCard("Card " + i, "content for Label Card #" + i);
JButton btn = new JButton(card.name);
menu.add(btn);
btn.addActionListener(this);
content.add(card, card.name);
cardList.add(card);
}
menu.setLayout(new GridLayout(i, 1));
add(menu, BorderLayout.WEST);
add(content, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
contentLayout.show(content, e.getActionCommand());
}
class Card extends JPanel{
final String name;
public Card(String name){
this.name = name;
}
}
class TextAreaCard extends Card implements ActionListener {
JTextArea textArea = new JTextArea();
JButton btn = new JButton("OK");
public TextAreaCard(String name, String text) {
super(name);
textArea.setText(text);
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);
add(btn, BorderLayout.SOUTH);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, textArea.getText(), "click OK", JOptionPane.NO_OPTION);
}
}
class LabelCard extends Card{
JLabel label = new JLabel();
public LabelCard(String name, String text) {
super(name);
label.setText(text);
add(label);
}
}
public static void main(String [] args){
Gui gui = new Gui();
gui.setSize(600, 500);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
}
}

Java Multidemensional Array Loop that inputs data with Button Action

Questions I am pulling my hair out over.
How do I get the array to add data to current index, then increment to the next index to add changed JTextField data for the next button press. currently I'm overwriting the same index.
I have tried to figure out actionlisteners for the button "Submit" that uses a counter with nesting of the loop. played with ideas from question 23331198 and 3010840 and 17829577 many others as a reference but didn't really get it to far. Most searches pull up info on managing buttons with arrays and creating button arrays so I assume I'm not using the correct wording to search with. I have read a few places that an MD array is not the best option to use.
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.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
int arrayIndex = 0;
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < tutArray.length; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
textArea.append("\n");
textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
This is what I was looking for thanks for the help!
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.JTextArea;
import javax.swing.JTextField;
public class GUIandLogicTest extends JFrame
{
// Variable Decloration
private static JFrame mainFrame;
private static JPanel mainPanel;
private static JTextField fieldOne;
private static JTextField fieldTwo;
private static JTextArea textArea;
private static JLabel textFieldOneLabel;
private static JLabel textFieldTwoLabel;
double[][] tutArray = new double[10][2];
int arrayIndex = 0;
// int i =0 ;
// Set GUI method
private void gui()
{
// constructs GUI
mainFrame = new JFrame();
mainFrame.setSize(800, 800);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
textFieldOneLabel = new JLabel("number 1");
mainPanel.add(textFieldOneLabel);
fieldOne = new JTextField(10);
mainPanel.add(fieldOne);
textFieldTwoLabel = new JLabel("number 2");
mainPanel.add(textFieldTwoLabel);
fieldTwo = new JTextField(10);
mainPanel.add(fieldTwo);
textArea = new JTextArea(50, 50);
mainPanel.add(textArea);
JButton Exit = new JButton("Quit");// Quits program
mainPanel.add(Exit);
Exit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JButton submit = new JButton("Enter");
// Reads jfields and set varibles to be submitted to array
mainPanel.add(submit);
submit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
double txtField1 = Double
.parseDouble(fieldOne.getText().trim());
double txtField2 = Double
.parseDouble(fieldTwo.getText().trim());
textArea.setText("");
if (txtField1 < 0)
{
}
if (txtField2 < 0)
{
}
tutArray[arrayIndex][0] = txtField1;
tutArray[arrayIndex][1] = txtField2;
arrayIndex++;
for (int i = 0; i < arrayIndex; i++)
{
textArea.append("Number1: " + tutArray[i][0] + " Number2: "
+ tutArray[i][1]);
// textArea.append("\n");
//textArea.append(String.valueOf(arrayIndex++));
textArea.append("\n");
// textArea.append(String.valueOf(arrayIndex++));
}
}
});
JButton report = new JButton();
// will be used to pull data out of array with formatting and math
mainFrame.setVisible(true);
mainFrame.add(mainPanel);
}
public static void main(String[] arg)
{
GUIandLogicTest GUIandLogic = new GUIandLogicTest();
GUIandLogic.start();
}
public void start()
{
gui();
}
}
You can add the index as a field in your main object:
protected int index;
in your actionPerformed you increase index:
index++;
NOTE:
But why do you extend from JFrame AND use the field mainFrame?
you can use
this.setSize(800,800);
this.add(mainPanel);
Please declare (because of extends JFrame):
private static final long serialVersionUID = 1L;
Please start the name of an object with a lower case letter:
JButton exit = new JButton("Quit");

(Java) Why is this tabbed pane not working correctly?

Note: I've searched all over the web (this site and others) and cannot answer this myself.
Ok guys. I am a new Java programmer, and we just got done covering tabbed panes. This is the state in which I turned in my assignment: it doesn't work, and I can't figure out why. I've changed so much crap around, I can't keep it straight in my head anymore, but I know it's probably something incredibly simple.
I apologize for the length of the code, but I'm trying to give you the entirety of my code so you can tell me where I jacked it up.
Thanks in advance. -- Also, I'm aware there are other Warnings (i.e. unused imports), but I'm not worried about those. And, this will not affect my grade (as I said, already submitted), but I want to know wtf I did wrong!
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.awt.Color;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JComponent;
public class TabbedPane1 extends JPanel
{
public TabbedPane1()
{
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
}
public static void main(String[] args)
{
JFrame myFrame = new JFrame("Tabbed Programs");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(new TabbedPane1(), BorderLayout.CENTER);
myFrame.pack();
myFrame.setVisible(true);
}
class DayGui extends JPanel
{
private JPanel mainFrame;
private JButton cmdGood;
private JButton cmdBad;
public DayGui()
{
mainFrame = new JPanel();
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container myContainer = mainFrame;
myContainer.setLayout(new FlowLayout());
myContainer.add(cmdGood);
myContainer.add(cmdBad);
cmdGood.setMnemonic('G');
cmdBad.setMnemonic('B');
mainFrame.setSize(300, 100);
myContainer.setBackground(Color.blue);
cmdGood.setBackground(Color.cyan);
cmdBad.setBackground(Color.cyan);
/*mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
//mainFrame.setVisible(true);
}
class ButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == cmdGood)
JOptionPane.showMessageDialog(null, "Today is a good day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
if(e.getSource() == cmdBad)
JOptionPane.showMessageDialog(null, "Today is a bad day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
class OfficeAreaCalculator extends JPanel
{
private JPanel mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator()
{
mainFrame = new JPanel();
exitButton = new JButton("Exit");
calculateButton = new JButton("Calculate");
lengthField = new JTextField(5);
widthField = new JTextField(5);
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
areaField = new JTextField(5);
areaField.setEditable(false);
Container c = mainFrame;
c.setLayout(new FlowLayout());
c.setBackground(Color.green);
c.add(lengthLabel);
c.add(lengthField);
c.add(widthLabel);
c.add(widthField);
c.add(areaLabel);
c.add(areaField);
c.add(calculateButton);
c.add(exitButton);
calculateButton.setMnemonic('C');
exitButton.setMnemonic('x');
mainFrame.setSize(260, 150);
/*mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
//mainFrame.setVisible(true);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
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));
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
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();
}
}
}
}
}
You added your JTabbedPane on JPanel.
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
Since JPanel has a FlowLayout as a default, you have this issue. Set layout of your JPanelto BorderLayout and problem will be solved.
setLayout(new BorderLayout()); //Here
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
EDIT:
Also, avoid extending your classes with swing components if you don't want to override methods or define new ones. Prefer composition instead of that. I had that same bad habbit.
For example, instead of extending tour TabbedPane1 class with JPanel, it would be better to just create a method which returns customized JTabbedPane. Something like this:
public JTabbedPane getTabbedPane() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
return tabbedPane;
}
To call it:
myFrame.add(new TabbedPane1().getTabbedPane(), BorderLayout.CENTER);
This way your class will be "opened" for inheritance.

Undo and redo methods for awt `Graphics` objects

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.

Applet not appearing full

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

Categories

Resources