Working with JFrames - java

hi I'm basically give up. Ok so this is what I am trying to do. So far I have written code to create a JFrame which contains a text field and combo box. The code is supposed to calculate the area of an input in the text field depending on what shape is selected from the combo box and output the result on the JFrame!
Here's is what the output should look like
And here is my code so far. it's a bit messed up but any help would be much appreciated. Thanks in advance
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;
import java.lang.Math;
public class AreaFrame3 extends JFrame
{
double Area;
double input;
public static void main(String[]args)
{
//Create array containing shapes
String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};
//Use combobox to create drop down menu
JComboBox comboBox=new JComboBox(shapes);
JLabel label1 = new JLabel("Select shape:");
JPanel panel1 = new JPanel(new FlowLayout()); //set frame layout
JLabel label2 = new JLabel("(select shape first)");
JTextField text = new JTextField(10); //create text field
text.setEnabled(false);
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text);
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text);
//JButton button = new JButton("GO"); //create GO button
//frame.add(button);
//set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
//set JFrame ssize
frame.setSize(400,250);
//make JFrame visible. So we can see it
frame.setVisible(true);
// public void actionPerformed(ActionEvent e)
//{
}
public void AreaCalc()
{
JButton button = new JButton("GO"); //create GO button
frame.add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int input = double.parseDouble(text.getText());
if(e.getSource() == button)
{
String shape = (String).comboBox.getSelectedItem();
if(shape == "(no shape selected)")
{
text.setEnabled(false);
}
else{
text.setEnabled(true);
}
if(input > 1 && shape == "Circle")
{
// label2.getText() = "Enter the radius of the circle: ";
Area = (Math.PI * (input * input));
}
}
else{}
}
}
);
}
}

I try to understand what you did here:
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text); // <---
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text); // <---
Especially frame.add(text); and panel1.add(text);. Don't add text to JFrame. Use JPanel.
Further,
public class AreaFrame3 extends Frame
Use public class AreaFrame3 extends JFrame so you don't need create additional JFrame:
JFrame frame=new JFrame("Area Calculator Window");
Something like:
super.setLayout(new FlowLayout()); //set layout
super.add(panel1);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.pack();
//set JFrame ssize
super.setSize(400,250);
//make JFrame visible. So we can see it
super.setVisible(true);
At last Ill give you some tamplate to start with (that will help you):
public class FrameExmpl extends JFrame{
private static final long serialVersionUID = 1L;
private JTabbedPane tabbedPane;
private JPanel topPanel;
private JTextField txtf_loadDS_;
public static int valueInt = 0; // responsible for Task status updating
public static Boolean isFinish = false;
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
FrameExmpl UI_L = new FrameExmpl();
UI_L.buildGUI();
UI_L.setVisible(true);
}
public void buildGUI(){
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(435, 225);
setLocation(285, 105);
setResizable(false);
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
txtf_loadDS_ = new JTextField();
txtf_loadDS_.setBounds(22, 22, 382, 25);
topPanel.add(txtf_loadDS_);
finishBuildGUI();
}
public void finishBuildGUI(){
tabbedPane = new JTabbedPane();
topPanel.add(tabbedPane, BorderLayout.CENTER);
}
}

There are multiple issues with this application such as extending from Frame rather than JFrame & attempting to assign an int from Double.parseDouble. I would recommend that you start again building a small but working application and incrementally add functionality, this way errors are easier to fix.

Related

Java Swing: Components automatically change position when a certain component updates

I made a Java program and part of the program's function is to track the user's mouse X and Y coordinates.
The tracking works nicely but there's a small problem that bothers me.
When I move my mouse around the screen, the other components automatically change position.
Here's a MRE(Minimal Reproducible Example):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class Test {
static Timer t;
static JLabel label1;
static InnerTest inner;
static int mouseX;
static int mouseY;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
buildFrame();
runTimer();
}
});
}
public static void buildFrame() {
JFrame frame = new JFrame();
label1 = new JLabel("Test1");
JLabel label2 = new JLabel("Test Test");
JLabel label3 = new JLabel("Test Label Label");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label1);
panel.add(label2);
panel.add(label3);
label1.setAlignmentX(Component.CENTER_ALIGNMENT);
label2.setAlignmentX(Component.CENTER_ALIGNMENT);
label3.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.getContentPane().add(panel);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void runTimer() {
inner = new InnerTest();
t = new Timer(20, inner);
t.start();
}
static class InnerTest implements ActionListener {
public void actionPerformed(ActionEvent e) {
mouseX = MouseInfo.getPointerInfo().getLocation().x * 100;
mouseY = MouseInfo.getPointerInfo().getLocation().y * 100;
label1.setText(" ( "+String.valueOf(mouseX)+" , "+String.valueOf(mouseY)+" )");
}
}
}
How do I keep the components still when another component is updating?
The components are added to the same panel so each is centered based on the maximum width of all three components. As the width of the top label changes the others are also adjusted.
The solution is to separate the top label from the other two labels.
One way would be:
//panel.add(label1);
panel.add(label2);
panel.add(label3);
//label1.setAlignmentX(Component.CENTER_ALIGNMENT);
label1.setHorizontalAlignment(JLabel.CENTER); // added
label2.setAlignmentX(Component.CENTER_ALIGNMENT);
label3.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.add(label1, BorderLayout.PAGE_START); // added
frame.getContentPane().add(panel);

How to close JDialog and save the setting ?

Hi I'm working on a program and I faced a problem when I choose some settings from JDialog then click "ok", which is that the setting didn't save but come back to the original settings.
PS : I'm not English speaker so maybe you observe some mistakes in my text above.
picture
enter image description here
class DrawingSettingWindow extends JDialog {
public DrawingSettingWindow() {
this.setTitle("Drawing Setting Window");
this.setSize(550, 550);
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
this.setVisible(true);
}
The information is there, you just have to extract it from the dialog after the user is done using it. I would give the code above at least two new methods, one a public getColor() method that returns colorsList.getSelectedItem();, the color selection of the user (I'm not sure what type of object this is, so I can't show the method yet). Also another one that gets the user's filled setting, perhaps
public boolean getFilled() {
return filled.isSelected();
}
Since the dialog is modal, you'll know that the user has finished using it immediately after you set it visible in the calling code. And this is where you call the above methods to extract the data.
In the code below, I've shown this in this section: drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
For example (see comments):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class UseDrawingSettings extends JPanel {
private JTextArea textArea = new JTextArea(20, 40);
private DrawingSettingWindow drawingSettings;
public UseDrawingSettings() {
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new ShowDrawSettings()));
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
add(topPanel, BorderLayout.PAGE_START);
}
private class ShowDrawSettings extends AbstractAction {
public ShowDrawSettings() {
super("Get Drawing Settings");
}
#Override
public void actionPerformed(ActionEvent e) {
if (drawingSettings == null) {
Window win = SwingUtilities.getWindowAncestor(UseDrawingSettings.this);
drawingSettings = new DrawingSettingWindow(win);
}
drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
UseDrawingSettings mainPanel = new UseDrawingSettings();
JFrame frame = new JFrame("UseDrawingSettings");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class DrawingSettingWindow extends JDialog {
private static final String TITLE = "Drawing Setting Window";
private JComboBox<String> colorsList;
private JRadioButton normal;
private JRadioButton filled;
// not sure what colors is, but I'll make it a String array for testing
private String[] colors = {"Red", "Orange", "Yellow", "Green", "Blue"};
public DrawingSettingWindow(Window win) {
super(win, TITLE, ModalityType.APPLICATION_MODAL);
// this.setTitle("Drawing Setting Window");
this.setSize(550, 550); // !! this is not recommended
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
// this.setVisible(true); // this should be the calling code's responsibility
}
public Object getColor() {
return colorsList.getSelectedItem();
}
public boolean getFilled() {
return filled.isSelected();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
}
}
Side notes:
I've changed your class's constructor to accept a Window parameter, the base class for JFrame, JDialog, and such, and have added a call to the super's constructor. This way, the dialog is a true child window of the calling code (or you can pass in null if you want it not to be).
I recommend not making the dialog visible within its constructor. It is the calling code's responsibility for doing this, and there are instances where the calling code will wish to not make the dialog visible after creating it, for example if it wanted to attach a PropertyChangeListener to it before making it visible. This is most important for modal dialogs, but is just good programming practice.
I didn't know the type of objects held by your combo box, and so made an array of String for demonstration purposes.

Bar Chart from different class in to GUI class

I have Gui class with a JPanel and JButton. When the button is clicked i would like to display the graph in my JPanel. The Graph is in different class. Can someone help me do this please?
GUI CLASS:
public class Gui extends JFrame implements ActionListener{
JButton showGraph;
public Gui() {
super("GUI");
setSize(1200,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
showGraph = new JButton("SHOW GRAPH");
JPanel mainPanel = new JPanel();
add(mainPanel);
mainPanel.setLayout(new GridLayout(2,0,10,10));
mainPanel.setBorder(new EmptyBorder(10,10,10,10));
mainPanel.add(showGraph);
JPanel graphPanel = new JPanel();
graphPanel.setBackground(Color.yellow);
mainPanel.add(graphPanel);
showGraph.addActionListener(this);
}
public static void main (String[] args){
new Gui().setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showGraph) {
SimpleBarChart b = new SimpleBarChart();
b.getGraph();
}
}
}
Change your getGraph() method to take a JFrame and pass in this.
public void getgraph(JFrame f) {
//JFrame f = new JFrame();
f.setSize(400, 300);
... as before ...
}
Then call in actionPerformed
if (e.getSource() == showGraph) {
SimpleBarChart b = new SimpleBarChart();
b.getGraph(this);
}
You can't have a frame inside a frame. Another option would be to make getGraph() return a JPanel and then you could put the panel in your existing frame instead of updating the whole frame.

How to change the color of a JSplitPane

I have written a small program, while reading a book about swing, that creates a JSplitPane between two labels.
The problem is that the JSplitPane can barely be seen (at least in my operating system - MAC OS Lion) and setting some properties on it (like foreground color) does not seem to work.
Here is the code :
//Demonstrate a simple JSplitPane
package swingexample4_6;
import javax.swing.*;
import java.awt.*;
public class SplitPaneDemo {
//constructor
public SplitPaneDemo()
{
//Create a new JFrame container.
//Use the default border layout
JFrame jfrm = new JFrame("Split Pane Demo");
//Give the frame an initial size
jfrm.setSize(380, 150);
//Terminate the program when the user closes the application
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//--Make two labels to show the split pane
JLabel jlab = new JLabel(" Left side: ABCDEFGHIJKLMNOPQRSTUVWXYZ");
JLabel jlab2 = new JLabel(" Right side: ABCDEFGHIJKLMNOPQRSTUVWXYZ");
//Set the minimum size for each label
//This step is not technically needed to use a split pane,
//but it enables the split pane resizing features to be
//used to their maximum extent
jlab.setMinimumSize(new Dimension(90, 30));
jlab2.setMinimumSize(new Dimension(90, 30));
//--Create a split pane
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, jlab, jlab2);
//Code to get a list of component names in the console
Component[] listComponents = jsp.getComponents();
String theList;
for (Component myComponent: listComponents)
{
theList = myComponent.toString();
System.out.println(theList);
}
//Add the split pane to the content pane
jfrm.getContentPane().add(jsp);
//Display the frame
jfrm.setVisible(true);
}
public static void main(String[] args) {
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new SplitPaneDemo();
}
});
}
}
Is there any way I can change its color , so that it can really stand out?
Thank you.
You can use the SplitPane.background property, as shown below.
import javax.swing.*;
import java.awt.*;
/** #see http://stackoverflow.com/a/10110232/230513 */
public class SplitPaneDemo {
//constructor
public SplitPaneDemo() {
JFrame jf = new JFrame("Split Pane Demo");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//--Make two labels to show the split pane
JPanel left = content("Left side: ");
JPanel right = content("Right side: ");
//--Create a split pane
JSplitPane jsp = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT, true, left, right);
jsp.setDividerLocation(0.5f);
//Add the split pane to the frame's content pane
jf.add(jsp);
jf.pack();
//Display the frame
jf.setLocationRelativeTo(null);
jf.setVisible(true);
//Code to get a list of component names in the console
for (Component myComponent : jsp.getComponents()) {
System.out.println(myComponent);
}
}
private JPanel content(String s) {
final JLabel label = new JLabel(s + "Some text.", JLabel.CENTER);
JPanel panel = new JPanel(new GridLayout()) {
#Override
public Dimension getPreferredSize() {
Dimension d = label.getPreferredSize();
return new Dimension(d.width * 2, d.height * 3);
}
};
panel.setOpaque(true);
panel.setBackground(new Color(0xffffffc0));
panel.add(label);
return panel;
}
public static void main(String[] args) {
UIManager.put("SplitPane.background", new Color(0xff8080ff));
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SplitPaneDemo();
}
});
}
}
JLabel is by default NON_Opaque, simple is transparent, you can
change JLabels to the JComponent or JPanel could be better
change opacity by JLabel#setOpaque(true)

Adding label and text box control to GUI

I would like to know what code to insert and where to add a simple label that can just say the word "Label" and a input text box that I can enter a number.
public CalculateDimensions() {
JTabbedPane Tab = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("First Tab");
Tab.addTab("One", jplInnerPanel1);
Tab.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("Second Tab");
Tab.addTab("Two", jplInnerPanel2);
JPanel jplInnerPanel3 = createInnerPanel("Third Tab");
Tab.addTab("Three", jplInnerPanel3);
JPanel jplInnerPanel4 = createInnerPanel("Fourth Tab");
Tab.addTab("Four", jplInnerPanel4);
JPanel jplInnerPanel5 = createInnerPanel("Fifth Tab");
Tab.addTab("Five", jplInnerPanel5);
setLayout(new GridLayout(1, 1));
add(Tab);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculations");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(new CalculateDimensions(),
BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
The Swing tutorial is an excellent resource for building GUIs.
Take a look at the visual guide and click on the components you want for detailed how to guides for creating text boxes, and other items.
http://download.oracle.com/javase/tutorial/ui/features/components.html
in your public static void main() method you should not instantiate JFrame frame = new JFrame("Calculations");
This is where you are going wrong!
That line should read:
CalculateDimensions frame = new CalculateDimensions("Calculations");
You will also need to change the line says
public class CalculateDimensions {
(it's near the top) says
public class CalculateDimensions extends JFrame {
then inside the method called public class CalculateDimensions { you need to add a line after JPanel jplInnerPanel1 = createInnerPanel("First Tab"); which says
jplInnerPanel1.add(new JLabel("Label");

Categories

Resources