Sending variables between classes - java

I have a JFrame class and a JPanel class.
When I click on a button in my JFrame my variable addIp take the entered String.
How can I access to this variable in my JPanel class ?
Here's my JFrame class:
public class Window extends JFrame{
public static void main(String[] args) {
new Window();
}
}
public Window()
{
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
stop = new JButton("STOP");
ListenForButton lForButton = new ListenForButton();
ip.addActionListener(lForButton);
centerPanel.add(start);
centerPanel.add(stop);
north.add(centerPanel, BorderLayout.CENTER);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
this.setContentPane(container);
this.setVisible(true);
}
public class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ip)
{
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
if(!address_t.getText().isEmpty())
{
addIp=address_t.getText();
}
}
}
And I want the addIP variable be accessible in my JPanel class:
public class GraphDisplay extends JPanel implements ActionListener {
double rand, lastrand, max, min, total, degr, average, temp, length;
ArrayList<Double> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
ArrayList<String> dateL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255, 0, 0);
Color green = new Color(0, 200, 0);
Color blue = new Color(0, 0, 200);
Color yellow = new Color(200, 200, 0);
int i, k = 0, inc, j, t;
public GraphDisplay() {
super();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
I copied you just the beginning of the class because the rest isn't interesting for this kind of problem.

You have several options:
Have the object that holds the information "push" it into the other object. To do this, your Window class would need to hold an instance of the GraphDisplay class, and call a method that GraphDisplay has, say, setIPaddress(String ip), passing in the String into GraphDisplay. Note that the instance hold by Window has to be the visualized GraphDisplay instance, and not any old instance.
Or you could have GraphDisplay "pull" the information in. Here Window would notify any listeners that the addIP variable has changed, and so the listeners, here this could be the GraphDisplay instance, could call getAddIP() from Window and thereby get the new value. To do this, you'd have to use Swing's notification mechanism, such as a ChangeListener or a PropertyChangeListener.

Related

Drawing Circles on random JPanels by Pressing a JButton

I got a grid with JPanels, by pressing the Button on top I want a random generator to draw circles on 3 random Panels.
In theory I think I have to overwrite the PaintComponent of every JPanel with a circle, put the flag on false and when I press the button an action listener puts the flag of 3 random JPanels on true.
But I really have no idea how to do this. Is it possible to do it this way ? if yes, could you show me how, if no, could you tell me what else i have to do ? Thanks a lot. Here's my code so far:
package feld;
import javax.swing.*;
import java.awt.*;
public class Spielplan {
public static void main(String[] args) {
JFrame f1 = new JFrame();
f1.setLayout(new BorderLayout());
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setPreferredSize(new Dimension(800, 800));
JButton tokens = new JButton("Spielsteine setzen");
f1.add(tokens, BorderLayout.NORTH);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,3));
f1.add(p1, BorderLayout.CENTER);
JPanel g1 = new JPanel();
g1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g1.setPreferredSize(new Dimension(100, 100));
g1.setVisible(true);
p1.add(g1);
JPanel g2 = new JPanel();
g2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g2.setPreferredSize(new Dimension(100, 100));
g2.setVisible(true);
p1.add(g2);
JPanel g3 = new JPanel();
g3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g3.setPreferredSize(new Dimension(100, 100));
g3.setVisible(true);
p1.add(g3);
JPanel g4 = new JPanel();
g4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g4.setPreferredSize(new Dimension(100, 100));
g4.setVisible(true);
p1.add(g4);
JPanel g5 = new JPanel();
g5.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g5.setPreferredSize(new Dimension(100, 100));
g5.setVisible(true);
p1.add(g5);
JPanel g6 = new JPanel();
g6.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g6.setPreferredSize(new Dimension(100, 100));
g6.setVisible(true);
p1.add(g6);
JPanel g7 = new JPanel();
g7.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g7.setPreferredSize(new Dimension(100, 100));
g7.setVisible(true);
p1.add(g7);
JPanel g8 = new JPanel();
g8.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g8.setPreferredSize(new Dimension(100, 100));
g8.setVisible(true);
p1.add(g8);
JPanel g9 = new JPanel();
g9.setBorder(BorderFactory.createLineBorder(Color.BLACK));
g9.setPreferredSize(new Dimension(100, 100));
g9.setVisible(true);
p1.add(g9);
f1.pack();
f1.setVisible(true);
}
}
The simplest way I could think of is to create s subclass of JPanel with a boolean to determine whether the circle should be drawn. I named it CirclePanel:
public class CirclePanel extends JPanel{
public static final Color circleColor = Color.BLACK;
private boolean drawCircle;
public CirclePanel() {
drawCircle=false;
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setBackground(Color.WHITE);
}
public void setDrawCircle(boolean drawCircle) {
this.drawCircle = drawCircle;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(drawCircle) {
Graphics2D g2d = (Graphics2D) g;
Color tmp = g2d.getColor();
g2d.setColor(circleColor);
g2d.fillOval(0, 0, getWidth(), getHeight());
g2d.setColor(tmp);
}
}
}
Then I created a subclass of JFrame for the frame but you could also do it in a main method. I placed the circle panels in an array to avoid repeating code and placed them in a grid. When the button is clicked, a List of indices are created and three are removed at random. The list is then used to set the boolean variable of the panels. see below:
public class CircleGrid extends JFrame implements ActionListener{
private CirclePanel[] panels;
private JButton button;
public CircleGrid() {
super("Circle test");
setLayout(new BorderLayout());
panels = new CirclePanel[9];
JPanel center = new JPanel();
center.setLayout(new GridLayout(3, 3));
for (int i = 0; i < panels.length; i++) {
panels[i] = new CirclePanel();
center.add(panels[i]);
}
button = new JButton("Color in");
button.addActionListener(this);
this.add(button, BorderLayout.NORTH);
this.add(center, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(800, 800));
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(button)) {
// select three random circle indices -
// https://stackoverflow.com/a/42353488/7015661
ArrayList<Integer> indices = new ArrayList<Integer>();
int numRandom = 3; // three indices
for (int i = 0; i < panels.length; i++) {
indices.add(i);
}
Random r = new Random();
for (int i = 0; i < numRandom; i++) {
int rndPos1 = r.nextInt(indices.size());
indices.remove(rndPos1); // remove three indices from the list
}
// change panel boolean
for (int i = 0; i < panels.length; i++) {
CirclePanel pi = panels[i];
if(indices.contains(i)) {
// no circle
pi.setDrawCircle(false);
}else {
//draw circle
pi.setDrawCircle(true);
}
}
repaint(); // redraw panels
}
}
public static void main(String[] args) {
new CircleGrid();
}
}
I end up with the following:
What you would do is essentially before your draw on your jPanel white out the entire panel then draw your circle apply the code below hopes in helps.
int name=(int) Math.random() * 100;
int name1=(int) Math.random() * 100;
Then you would draw the circle on the JPanels using the graphics method and the appropriate code. Below is the code that draws the circle in a random place:
g.draw/fillOval (name,name1,100,100);

Repaint Isn't doing anything

I am trying to make a rectangle change color with GUI sliders. I know this can be done by changing the background but I'm trying to use repaint.
I know that repaint holds the requests and executes at will almost. I'm trying to find a workaround because I'm stuck.
I've read up on repaint(); and repaintManager and tried manipulating my code but I'm still unable to get my desired output.
Any help would be appreciated.
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
*
*/
public class MyColorChooser2 extends JPanel {
private JFrame frame;
private JLabel redLabel, greenLabel, blueLabel;
private JSlider redSlider, greenSlider, blueSlider;
private JTextField redTextField, greenTextField, blueTextField;
private JPanel redPanel, greenPanel, bluePanel, colorPanel, paintPanel;
private int holdNbr1, holdNbr2, holdNbr3;
DrawPanel rect = new DrawPanel();
public MyColorChooser2() {
JFrame frame = new JFrame();
frame.setTitle("Color Chooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set up labels
redLabel = new JLabel("Red:");
greenLabel = new JLabel("Green:");
blueLabel = new JLabel("Blue:");
// set up sliders and register their event handler:
redSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 50);
redSlider.setMajorTickSpacing(10); // create tick every 10
redSlider.setPaintTicks(true); // paint ticks on slider
greenSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 100);
greenSlider.setMajorTickSpacing(10); // create tick every 10
greenSlider.setPaintTicks(true); // paint ticks on slider
blueSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 200);
blueSlider.setMajorTickSpacing(10); // create tick every 10
blueSlider.setPaintTicks(true); // paint ticks on slider
//slider event handling:
SliderHandler sliderHandler = new SliderHandler();
redSlider.addChangeListener(sliderHandler);
greenSlider.addChangeListener(sliderHandler);
blueSlider.addChangeListener(sliderHandler);
//set up textFields and register their event handler:
redTextField = new JTextField(3);
redTextField.setText("50"); //initialize
redTextField.setEditable(false);
redTextField.setText("" + redSlider.getValue());
greenTextField = new JTextField(3);
greenTextField.setText("100"); //initialize
greenTextField.setEditable(false);
greenTextField.setText("" + greenSlider.getValue());
blueTextField = new JTextField(3);
blueTextField.setText("200"); //initialize
blueTextField.setEditable(false);
blueTextField.setText("" + blueSlider.getValue());
// build colorPanel:
// build redPanel:
redPanel = new JPanel();
redPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
redPanel.add(redLabel);
redPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
redPanel.add(redSlider);
redPanel.add(redTextField);
// build greenPanel:
greenPanel = new JPanel();
greenPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
greenPanel.add(greenLabel);
greenPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
greenPanel.add(greenSlider);
greenPanel.add(greenTextField);
// build bluePanel:
bluePanel = new JPanel();
bluePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bluePanel.add(blueLabel);
bluePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
bluePanel.add(blueSlider);
bluePanel.add(blueTextField);
colorPanel = new JPanel();
colorPanel.add(redPanel);
colorPanel.add(greenPanel);
colorPanel.add(bluePanel);
frame.setLayout(new BorderLayout());
frame.add(rect, BorderLayout.CENTER);
frame.add(colorPanel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(900, 300));
frame.setVisible(true);
frame.pack();
}
public class DrawPanel extends JPanel {
private Color color;
private int red = 50, blue = 100, green = 200;
private Graphics g;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
changeColor();
g.setColor(color);
g.fillRect(10, 10, 880, 200);
g.dispose();
}
public void DrawPanel(Color c) {
color = c;
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
}
void changeColor() {
color = new Color(red, green, blue);
this.color = color;
}
public void setRed(int r) {
red = r;
changeColor();
}
public void setBlue(int b) {
blue = b;
changeColor();
}
public void setGreen(int g) {
green = g;
changeColor();
}
}
private class SliderHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
JSlider change = (JSlider) e.getSource();
DrawPanel draw = new DrawPanel();
int value;
if (change == redSlider) {
value = change.getValue();
redTextField.setText(String.valueOf(value));
draw.setRed(value);
} else if (change == greenSlider) {
value = change.getValue();
greenTextField.setText(String.valueOf(value));
draw.setGreen(value);
} else if (change == blueSlider) {
value = change.getValue();
blueTextField.setText(String.valueOf(value));
draw.setBlue(value);
}
draw.changeColor();
draw.repaint();
}
}
public static void main(String args[]) {
MyColorChooser2 color = new MyColorChooser2();
}
}
It's not that it isn't doing anything. The problem is that you're stuck, because every time you make a change you're trying to update a different component. You're recreating multiple panels in your state changed.
I've added comments about the changes I've done to make it work properly. If you need more help, just ask. Cheers!
Would you care trying this code:
public class MyColorChooser2 extends JPanel {
private JFrame frame;
private DrawPanel drawPanel;
private JLabel redLabel, greenLabel, blueLabel;
private JSlider redSlider, greenSlider, blueSlider;
private JTextField redTextField, greenTextField, blueTextField;
private JPanel redPanel, greenPanel, bluePanel, colorPanel, paintPanel;
private int holdNbr1, holdNbr2, holdNbr3;
private Color initialColor = Color.RED;
public MyColorChooser2() {
JFrame frame = new JFrame();
frame.setTitle("Color Chooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Let DrawPanel choose the initial color. I don't care.
drawPanel = new DrawPanel();
// This way I control what is the initial color
//drawPanel = new DrawPanel(initialColor);
// set up labels
redLabel = new JLabel("Red:");
greenLabel = new JLabel("Green:");
blueLabel = new JLabel("Blue:");
// set up sliders and register their event handler:
redSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, initialColor.getRed());
redSlider.setMajorTickSpacing(10); // create tick every 10
redSlider.setPaintTicks(true); // paint ticks on slider
greenSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, initialColor.getGreen());
greenSlider.setMajorTickSpacing(10); // create tick every 10
greenSlider.setPaintTicks(true); // paint ticks on slider
blueSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, initialColor.getBlue());
blueSlider.setMajorTickSpacing(10); // create tick every 10
blueSlider.setPaintTicks(true); // paint ticks on slider
// slider event handling:
SliderHandler sliderHandler = new SliderHandler();
redSlider.addChangeListener(sliderHandler);
greenSlider.addChangeListener(sliderHandler);
blueSlider.addChangeListener(sliderHandler);
// set up textFields and register their event handler:
redTextField = new JTextField(3);
redTextField.setText("50"); // initialize
redTextField.setEditable(false);
redTextField.setText("" + redSlider.getValue());
greenTextField = new JTextField(3);
greenTextField.setText("100"); // initialize
greenTextField.setEditable(false);
greenTextField.setText("" + greenSlider.getValue());
blueTextField = new JTextField(3);
blueTextField.setText("200"); // initialize
blueTextField.setEditable(false);
blueTextField.setText("" + blueSlider.getValue());
// build colorPanel:
// build redPanel:
redPanel = new JPanel();
redPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
redPanel.add(redLabel);
redPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
redPanel.add(redSlider);
redPanel.add(redTextField);
// build greenPanel:
greenPanel = new JPanel();
greenPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
greenPanel.add(greenLabel);
greenPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
greenPanel.add(greenSlider);
greenPanel.add(greenTextField);
// build bluePanel:
bluePanel = new JPanel();
bluePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
bluePanel.add(blueLabel);
bluePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
bluePanel.add(blueSlider);
bluePanel.add(blueTextField);
colorPanel = new JPanel();
colorPanel.add(redPanel);
colorPanel.add(greenPanel);
colorPanel.add(bluePanel);
frame.setLayout(new BorderLayout());
frame.add(drawPanel, BorderLayout.CENTER);
frame.add(colorPanel, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(900, 300));
frame.setVisible(true);
frame.pack();
}
private class DrawPanel extends JPanel {
private Color color;
private int red = 255, blue = 0, green = 0;
#Override
protected void paintComponent(Graphics g) {
// I've removed the call to changeColor because it was creating
// an infinite loop of revalidates and repaints.
// Now, the paintComponent just finishes the job it was required to.
super.paintComponent(g);
g.setColor(color);
g.fillRect(10, 10, 880, 200);
}
public DrawPanel() {
this(Color.BLUE);
}
public DrawPanel(Color c) {
color = c;
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
// I'm calling this first repaint here just to make
// sure the panel is initiated the way we want with
// the given Color
repaint();
}
void changeColor() {
color = new Color(red, green, blue);
// We just need to change the color and call this repaint here
// so that the paintComponent can do its job
repaint();
}
public void setRed(int r) {
red = r;
changeColor();
}
public void setBlue(int b) {
blue = b;
changeColor();
}
public void setGreen(int g) {
green = g;
changeColor();
}
}
private class SliderHandler implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
JSlider change = (JSlider) e.getSource();
int value;
// I've removed this line of code because you were
// recreating the drawingPanel. That's not what you want.
// You want to reuse the same panel.
// DrawPanel draw = new DrawPanel();
if (change == redSlider) {
value = change.getValue();
redTextField.setText(String.valueOf(value));
drawPanel.setRed(value);
} else if (change == greenSlider) {
value = change.getValue();
greenTextField.setText(String.valueOf(value));
drawPanel.setGreen(value);
} else if (change == blueSlider) {
value = change.getValue();
blueTextField.setText(String.valueOf(value));
drawPanel.setBlue(value);
}
// You don't need to call those methods, because the
// changeColor will be called by the settings
// of Red, Green and Blue
// draw.changeColor();
// draw.repaint();
}
}
public static void main(String args[]) {
MyColorChooser2 color = new MyColorChooser2();
}
}

paintComponent is not erasing JPanel

The program is to display 3 buttons on the JPanel. The program is compiled successfully. The GUI Window then appears and is empty. When I minimise the window and then maximise it again the Buttons appear. On doing this again another set of Buttons appear. The button keeps on appearing when the window is refreshed and the older data is kept intact.
JPanel Class
class MyJPanel extends JPanel {
JButton jb1, jb2, jb3;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
jb1 = new JButton();
jb2 = new JButton("Green");
jb3 = new JButton("Blue");
//g.drawString("Welcome!", 100, 100);
ImageIcon img = new ImageIcon("next.png");
jb1.setIcon(img);
jb1.setToolTipText("Button 1");
this.add(jb1);
this.add(jb2);
this.add(jb3);
}
}
JFrame Class
class MyJFrame extends JFrame {
MyJPanel mjp;
public MyJFrame(String title) {
super(title);
mjp = new MyJPanel();
Container ct = getContentPane();
ct.add(mjp);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Driver Class
class Gui5JButton {
public static void main(String[] args) {
MyJFrame mjf = new MyJFrame("Prakhar");
mjf.repaint();
}
}
paintComponent is called everytime your panel needs to be redraw, so everytime you minimize the window it will put the button again. If I understood what you want to do correctly, you need to remove the override and put this code :
jb1 = new JButton();
jb2 = new JButton("Green");
jb3 = new JButton("Blue");
//g.drawString("Welcome!", 100, 100);
ImageIcon img = new ImageIcon("next.png");
jb1.setIcon(img);
jb1.setToolTipText("Button 1");
this.add(jb1);
this.add(jb2);
this.add(jb3);
in the constructor of your MyJPanel class.

Can't seem to update my GridLayout in my JFrame. Right now it adds more and more to the frame and I just want to update it

So this is my runner that runs my entire game. CharacterGame, CharacterChoice and CharacterHead are all classes that contain graphics and paint. I was hoping to be able to call separate parts from these classes into the graphics by the remove and repaint located in one of my button's code. Right now its just updating the Frame with more and more panels instead of removing the old panels and adding these panels into the old panels place. I hope this makes sense as I am a bit new to graphics and may not have thought of the best way to do this. If anyone can shed some light into how to do this, I will be very grateful. Thanks! I've tried everything I can think of... from removeAll methods to repaint. I can't think of anything else to do.
The part not working is located in the ShowButtonDemo() in the choice1Button listener.
public class GraphicsRunner extends JFrame
{
private static final int WIDTH = 1280;
private static final int HEIGHT = 980;
private JFrame mainframe;
private JPanel controlPanel;
private JPanel headPanel;
private JPanel gamePanel;
private JPanel choicePanel;
private int gameInt = 0;
private int choiceInt = 0;
private int endGame = 0;
public GraphicsRunner()
{
super("Stranded...");
mainframe = new JFrame();
mainframe.setBackground(Color.BLACK);
mainframe.setSize(WIDTH,HEIGHT);
mainframe.setLayout(new GridLayout(4, 0));
mainframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headPanel = new JPanel();
gamePanel = new JPanel();
choicePanel = new JPanel();
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
headPanel = new CharacterHeading();
gamePanel = new CharacterGame(gameInt);
choicePanel = new CharacterChoice(choiceInt);
mainframe.add(headPanel);
mainframe.add(gamePanel);
mainframe.add(choicePanel);
mainframe.add(controlPanel);
mainframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainframe.setVisible(true);
}
public static void main( String args[] )
{
GraphicsRunner run = new GraphicsRunner();
run.showButtonDemo();
}
private void showButtonDemo(){
JButton choice1Button = new JButton("Choice #1");
JButton choice2Button = new JButton("Choice #2");
JButton choice3Button = new JButton("Choice #3");
choice3Button.setHorizontalTextPosition(SwingConstants.LEFT);
choice1Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gameInt = gameInt + 1;
choiceInt = choiceInt + 1;
gamePanel = new CharacterGame(gameInt);
//This is the part I am currently working on and I was hoping
//it would remove the panel instead of just removing the
//content on the panel...
mainframe.remove(headPanel);
mainframe.remove(gamePanel);
mainframe.remove(choicePanel);
mainframe.remove(controlPanel);
mainframe.add(headPanel, 0);
mainframe.add(gamePanel, 1);
mainframe.add(choicePanel, 2);
mainframe.add(controlPanel, 3);
mainframe.revalidate();
mainframe.repaint();
System.out.println(gameInt);
}
});
controlPanel.setBackground(Color.BLACK);
controlPanel.add(choice1Button);
controlPanel.add(choice2Button);
controlPanel.add(choice3Button);
mainframe.setVisible(true);
}
}

Java function pack(), JFrame size

I'm having some problems with function pack(), as I know it should set size of JFrame to minimum.
Here is my masterpiece:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Okno extends JFrame{
public Okno(String naslov){
setTitle(naslov);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int sirina = d.width;
int visina = d.height;
setBounds(sirina/4,visina/4,sirina/2,visina/2);
}
}
public class Pretvori{
public static class Plosca extends JPanel implements ActionListener{
JTextField vnesiC , izracunajF;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
public void actionPerformed(ActionEvent e) {
String c = vnesiC.getText();
Double dc = Double.parseDouble(c);
Double df = 1.80 * dc + 32.0;
String f = String.format("%f", df);
izracunajF.setText(f);
}
}
public static void main(String[] args){
Okno okno = new Okno("Pretvornik");
okno.setLayout(new BorderLayout());
Plosca p = new Plosca();
okno.add(p);
okno.pack();
okno.setResizable(false);
okno.setVisible(true);
}
}
Download link: http://pastebin.com/download.php?i=kGkpCrHe
And I am sorry for bad language.
One big problem is that you are adding components to your Plosca instance during each call to paintComponent. You should add your components in a Plosca constructor instead. Then when you call pack() it will have components so its preferred size won't be so small.
public static class Plosca extends JPanel implements ActionListener{
JTextField vnesiC , izracunajF;
public Plosca() {
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
// do not need paintComponent()
public void actionPerformed(ActionEvent e) {
. . .
}
}
No, pack sizes the frame to its contents preferred size (based on the requirements of the layout managers), but since your Plosca doesn't have a preferred size, it's returning 0x0, therefore your frame thinks the preferred size is 0x0
This...
protected void paintComponent(Graphics g) {
super.paintComponent(g);
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
isn't how you should prepare your UI, paintComponent is used for performing custom painting, not adding to or changing the UI.
Instead, you should start adding your components from within the constructor
public Plosca() {
vnesiC = new JTextField(8);
add(vnesiC);
add(new JLabel("\u00b0C"));
JButton pretvori = new JButton(" = ");
add(pretvori);
pretvori.addActionListener(this);
izracunajF = new JTextField(8);
izracunajF.setEditable(false);
add(izracunajF = new JTextField(8));
add(new JLabel("F"));
}
Take a look at How to create a GUI with Swing for more details...

Categories

Resources