I want to create a jtext field with a definite size, but I would like it to expand like a scroll pane when the input grows. Here is what I have so far:
JButton b,b1;
JLabel j1,j2,j3;
JTextField t1,t2;
public Window(){
super("frame");
//new Thread(this).start();
b=new JButton("Click");
j1=new JLabel("VALUE1");
t1=new JTextField(30);
j2=new JLabel("VALUE2");j3=new JLabel(" ");
t2=new JTextField(30);
j1.setBounds(100, 50, 150, 50);
t1.setBounds(150, 50, 200, 50);
j2.setBounds(200, 150, 250, 150);
t2.setBounds(250, 150, 200, 50);j3.setBounds(300, 150, 250, 150);
b.setBorder(new LineBorder(Color.black));
b.setBackground(Color.black);
b.setForeground(Color.white);
b1=new JButton("Exit");
super.setSize(300,300);
super.setLocation(250,150);
super.setLayout(new FlowLayout());
super.setVisible(true);
add(j1);add(t1);add(j2);add(t2); add(j3);
add(b);add(b1);
b.addActionListener(this);
b1.addActionListener(this);
If you dont want to use JScrollPane this is something you are looking for -
I have created a sample program to auto resize the JTextField size
i.e if text is added its size increases and if text is deleted its size is reduced.
I have used KeyListener's - keyTyped event to detect and update the text field size.
You can add document listener too to do the same thing.
Here is my sample code -
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class AutoResizeTest
{
public AutoResizeTest(){
JFrame frame = new JFrame("Auto-Resizable TextField");
frame.setLayout(null);
MyCustomTextField expandableText = new MyCustomTextField(20);
expandableText.setBounds(10, 10, 200, 30);
expandableText.setPreferredSize(new Dimension(200,30));
expandableText.setMaximumSize(new Dimension(600,30));
frame.add(expandableText);
frame.setBounds(100,100,700,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args)
{
AutoResizeTest test = new AutoResizeTest();
}
class MyCustomTextField extends javax.swing.JTextField{
private int originallimit;
int previousLength;
int length;
public MyCustomTextField(int limit){
previousLength=0;
originallimit = limit;
this.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
length = textField.getText().length();
if(length >= originallimit){
if(length > previousLength){
textField.setSize(new Dimension(textField.getWidth()+10, textField.getHeight()));
}
else{
if(length < previousLength)
textField.setSize(new Dimension(textField.getWidth()-10, textField.getHeight()));
}
previousLength = length;
}else{
textField.setSize(textField.getPreferredSize());
}
}
});
}
}
}
In this code I have increamented/reduced the size by 10. You can put your desired value.
Hope that helps you.
Place the TextArea in a seperate JPanel with BorderLayout and in the center and the panel automatically expands, when the content increases.
textArea = new JTextArea(2, WIDTH);
textArea.setLineWrap(true);
textArea.getDocument().putProperty("filterNewlines", Boolean.TRUE);
The default size of the JTextField will be set and provide a ScrollPane to JTextField which will make field to expand if necessary.
Try the following
JTextField jtext = new JTextField(pane);
JScrollPane scroll = new JScrollPane(jtext);
Related
Recently I've been trying to make a program that takes in a double in the form of a string. It then parses that to a double which goes to another class to be divided to a quarter or a half and then returns that output to a label.
I've been having an issue where when I click a button to actually submit what is inside the text field, the label doesn't change.
I've tried a lot of trial and error and I know I can change the text after doing new JLabel("test") for example. However, there seems to be an issue with my action listener for when the button is pushed. I can't tell if it's not seeing the button as being pushed.
NOTE: I am new to awt event things and swing as a whole, I usually operate just using the output terminal of visual studio code where it's just text and no graphics.
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Dimension;
public class MoneySorterRunner {
private MoneySorter sorter = new MoneySorter();
private String input = "0";
private double money = Double.parseDouble(input);
private static JTextField typeHere = new JTextField();
///labels num1-3 are the labels being changed
private static JLabel num1 = new JLabel(new MoneySorterRunner().sorter.divQuarter(new MoneySorterRunner().money));
private static JLabel num2 = new JLabel(new MoneySorterRunner().sorter.divQuarter(new MoneySorterRunner().money));
private static JLabel num3 = new JLabel(new MoneySorterRunner().sorter.divHalf(new MoneySorterRunner().money));
public static void main(String args[]) {
JFrame frame = new JFrame("Money Calculator - v0.1a");
JPanel panel = new JPanel();
JButton doThing = new JButton("Do a Thing");
doThing.setActionCommand("Do a Thing");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 250);
frame.setLocation(200, 200);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
panel.setLayout(null);
frame.setVisible(true);
JLabel item1 = new JLabel("test");
JLabel item2 = new JLabel("test");
JLabel item3 = new JLabel("test");
item1.setFont(new Font("Arial", Font.PLAIN, 30));
item2.setFont(new Font("Arial", Font.PLAIN, 30));
item3.setFont(new Font("Arial", Font.PLAIN, 30));
num1.setFont(new Font("Arial", Font.PLAIN, 25));
num2.setFont(new Font("Arial", Font.PLAIN, 25));
num3.setFont(new Font("Arial", Font.PLAIN, 25));
Dimension size1 = item1.getPreferredSize();
Dimension size2 = item2.getPreferredSize();
Dimension size3 = item3.getPreferredSize();
panel.add(item1);
panel.add(item2);
panel.add(item3);
panel.add(num1);
panel.add(num2);
panel.add(num3);
panel.add(doThing);
panel.add(typeHere);
item1.setBounds(10, 10, size1.width + 3, size1.height);
item2.setBounds(190, 10, size2.width + 3, size2.height);
item3.setBounds(325, 10, size3.width + 3, size3.height);
num1.setBounds(50, 50, 50, 25);
num2.setBounds(200, 50, 50, 25);
num3.setBounds(350, 50, 50, 25);
doThing.setBounds(250, 150, 100, 25);
typeHere.setBounds(100, 150, 150, 25);
}
public void actionPerformed(ActionEvent event){
String check = event.getActionCommand();
if(check.equals("Do a Thing")){
input = typeHere.getText();
}
if(input != "0"){
num1.setText(sorter.divQuarter(money));
num2.setText(sorter.divQuarter(money));
num3.setText(sorter.divHalf(money));
}
}
}
For those who wanted the MoneySorter.java:
public MoneySorter(){
}
public String divQuarter(double moneyIn){
String answer = Double.toString(moneyIn);
return answer;
}
public String divHalf(double moneyIn){
String answer = Double.toString(moneyIn);
return answer;
}
}
I understand that your program is supposed to do the following.
User enters an amount of money in a JTextField and when she clicks on a JButton the JLabels show the entered amount in dollars, half-dollars and quarters (as per U.S. currency). My answer, below, is based on this understanding.
I don't know if making all the variables static is good or bad but I never use static class member variables in my Swing programs.
Here is my analysis of your code.
private double money = Double.parseDouble(input);
This line of code will be executed precisely once, when you launch class MoneySorterRunner. You want to do this every time the JButton is clicked, hence parsing the text entered into the JTextField should be performed in the actionPerformed method.
JPanel panel = new JPanel();
panel.setLayout(null);
It is almost never needed to set the layout manager to null. You can almost always find an appropriate layout manager or you can place one JPanel within another and use different layout managers for each JPanel in order to get the desired placement of components within the Swing application window.
JButton doThing = new JButton("Do a Thing");
doThing.setActionCommand("Do a Thing");
By default, the text of a JButton is also its action command so no need to explicitly set it.
frame.setLocation(200, 200);
frame.setLocationRelativeTo(null);
These are two different ways to set the location of the JFrame and they do not complement each other. Use one or the other, but not both.
frame.setVisible(true);
Only after you have created all the [GUI] components and added them to the JFrame should you make the JFrame visible. So this should be the last line of the code that creates your GUI.
doThing.setBounds(250, 150, 100, 25);
If you use a layout manager, you never need to call method setBounds.
if(input != "0"){
This is not the way to compare strings. Use method equals as you have done here
if(check.equals("Do a Thing")){
Here is my rewrite of your application. Note that since I could not find the code for class MoneySorter, in your question, I just created my own version of that class. The point is to show how to change the text of the JLabel after clicking on the JButton and not how to create the actual text to display.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MoneySorterRunner implements ActionListener {
private MoneySorter sorter = new MoneySorter();
private JTextField typeHere = new JTextField();
private JLabel num1;
private JLabel num2;
private JLabel num3;
private void createAndShowGui() {
JFrame frame = new JFrame("Money Calculator - v0.1a");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(createLabels(), BorderLayout.PAGE_START);
frame.add(createForm(), BorderLayout.CENTER);
frame.setSize(550, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createForm() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
panel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
typeHere = new JTextField(10);
panel.add(typeHere);
JButton doThing = new JButton("Do a Thing");
doThing.addActionListener(this);
panel.add(doThing);
return panel;
}
private static JLabel createLabel(String text) {
JLabel label = new JLabel(text);
label.setFont(new Font("Arial", Font.PLAIN, 25));
return label;
}
private JPanel createLabels() {
JPanel panel = new JPanel(new GridLayout());
num1 = createLabel("num1");
panel.add(num1);
num2 = createLabel("num2");
panel.add(num2);
num3 = createLabel("num3");
panel.add(num3);
return panel;
}
public static void main(String args[]) {
new MoneySorterRunner().createAndShowGui();
}
public void actionPerformed(ActionEvent event){
String check = event.getActionCommand();
if(check.equals("Do a Thing")){
String text = typeHere.getText();
if (!text.isEmpty()) {
double money = Double.parseDouble(text);
num1.setText(sorter.divQuarter(money));
num2.setText(sorter.divQuarter(money));
num3.setText(sorter.divHalf(money));
}
}
}
}
class MoneySorter {
public String divQuarter(double money) {
return "divQuarter(" + money + ")";
}
public String divHalf(double money) {
return "divHalf(" + money + ")";
}
}
This is how your GUI looked when I ran your original code (as posted in your question).
This is how the GUI looks when running the code in this answer.
After launching
After entering a value and clicking the JButton
It looks like you forgot to set the ActionListener. You should also change your method to another name, because your method has the same name as the actionPerformed of the ActionListener.
doThing.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new MoneySorterRunner().actionPerformedMethod(e);
}
});
You forgot to add the ActionListener.
In order to fix this, you need to do two things:
Add this statement to your code, preferably near where you create the button (so that it is easier to keep track). -
doThing.addActionListener(this);
When you write "public class", you also need this keyword: implements ActionListener - meaning your class (basically the first line) should look like:
public class MoneySorterRunner implements ActionListener
And that should make it work.
Recently I'm writing a mail system client using Java (I chose swing to write the GUI and use IDEA to hardcode my GUI). In the Compose module, I want to show or hide the textfield for CC and Bcc when I click the corresponding buttons.
So I googled and browsed the following questions and doc on the web:
How to make JPanel scrollable in Java?
How to make JPanel scrollable?
Scrolling a JPanel
Doc: JScrollPane
Finally, I chose the JScrollPane to implement it.
My simplified sample code is as follows (the original code is tedious):
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lbl1;
private JTextField txf1;
private JLabel lbl2;
private JTextField txf2;
// container for lbl2 and txf2, which should be able to be shown or hidden
private JPanel pnlContainer2;
private JLabel lbl3;
private JTextField txf3;
// container for lbl3 and txf3
private JPanel pnlContainer3;
private JButton btnShow;
// the container I want to move when I click btnShow
private JPanel pnlBody;
// the panel to hold my "cards"
// In this example, I include it just to show what controls are on my interface.
private JPanel pnlContent;
private JPanel pnlContainer;
// here, I want to use JScrollPane to make my pnlContainer scrollable
// to adapt to my interface
private JScrollPane scrollPane;
public Demo() {
init();
}
private void init() {
pnlContainer = new JPanel(new CardLayout(), true);
pnlContainer.setBounds(0, 0, 200, 180);
pnlContent = new JPanel(null, true);
pnlContent.setBounds(0, 0, 200, 180 + 50);
scrollPane = new JScrollPane(pnlContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(0, 0, 200, 180);
pnlContainer.add(scrollPane);
pnlBody = new JPanel(null, true);
lbl1 = new JLabel("lbl1");
lbl1.setBounds(10, 20, 40, 30);
txf1 = new JTextField();
txf1.setBounds(60, 20, 120, 30);
pnlContent.add(lbl1);
pnlContent.add(txf1);
pnlContainer2 = new JPanel(null, true);
pnlContainer2.setBounds(0, 70, 180, 30);
lbl2 = new JLabel("lbl2");
lbl2.setBounds(10, 0, 40, 30);
txf2 = new JTextField();
txf2.setBounds(60, 0, 120, 30);
pnlContainer2.add(lbl2);
pnlContainer2.add(txf2);
pnlContainer2.setVisible(false);
pnlContent.add(pnlContainer2);
pnlBody = new JPanel(null, true);
pnlBody.setBounds(0, 70, 180, 90);
pnlContainer3 = new JPanel(null, true);
pnlContainer3.setBounds(0, 0, 180, 30);
pnlBody.add(pnlContainer3);
lbl3 = new JLabel("lbl3");
lbl3.setBounds(10, 0, 40, 30);
txf3 = new JTextField();
txf3.setBounds(60, 0, 120, 30);
pnlContainer3.add(lbl3);
pnlContainer3.add(txf3);
btnShow = new JButton("show");
btnShow.setBounds(60, 50, 80, 30);
btnShow.addActionListener(this);
pnlBody.add(btnShow);
pnlContent.add(pnlBody);
this.add(pnlContainer);
this.setLayout(null);
this.setTitle("Demo");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setResizable(false);
// ImageIcon icon = new ImageIcon("E:\\Javarepo\\Hmail\\src\\main\\resources\\assets\\hmail.png");
// this.setIconImage(icon.getImage());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object src = e.getSource();
if (src instanceof JButton) {
JButton btn = (JButton) src;
boolean showSelected = false;
String altText;
if (btn == btnShow) {
showSelected = btnShow.getText() == "show";
altText = showSelected ? "hide" : "show";
btnShow.setText(altText);
}
relayout(showSelected);
}
}
private void relayout(boolean showSelected) {
int x = pnlBody.getX();
int y = pnlBody.getY();
if (showSelected) {
pnlContainer2.setVisible(true);
pnlBody.setBounds(x, y + 50, 180, 90);
} else {
pnlContainer2.setVisible(false);
pnlBody.setBounds(x, y - 50, 180, 90);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Demo());
}
}
However, no matter which JPanel I apply JScrollPane to, I cannot make my interface adaptive to the hide and show of my JContainer2.
How can I modify it, or what control to use to replace JScrollPane? Any suggestions will be welcome.
And here is my platform information:
java -version
java version "1.8.0_212"
Java(TM) SE Runtime Environment (build 1.8.0_212-b10)
Java HotSpot(TM) 64-Bit Server VM (build 25.212-b10, mixed mode)
OS: win10 1909
arch: amd64
I rewrote your code. Explanations appear after it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;
public class Demo2 implements ActionListener, Runnable {
private static final String HIDE = "HIDE";
private static final String SHOW = "SHOW";
private JButton button;
private JLabel lbl2;
private JFrame frame;
private JTextField txf2;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent event) {
boolean visible;
String text;
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case HIDE:
text = SHOW;
visible = false;
break;
case SHOW:
text = HIDE;
visible = true;
break;
default:
text = "???";
visible = false;
}
button.setText(text);
lbl2.setVisible(visible);
txf2.setVisible(visible);
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
button = new JButton(SHOW);
button.addActionListener(this);
buttonsPanel.add(button);
return buttonsPanel;
}
private JScrollPane createForm() {
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel lbl1 = new JLabel("lbl1");
form.add(lbl1, gbc);
gbc.gridx = 1;
JTextField txf1 = new JTextField(6);
form.add(txf1, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
lbl2 = new JLabel("lbl2");
lbl2.setVisible(false);
form.add(lbl2, gbc);
gbc.gridx = 1;
txf2 = new JTextField(6);
txf2.setVisible(false);
form.add(txf2, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel lbl3 = new JLabel("lbl3");
form.add(lbl3, gbc);
gbc.gridx = 1;
JTextField txf3 = new JTextField(6);
form.add(txf3, gbc);
return new JScrollPane(form,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
private void showGui() {
frame = new JFrame("Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(createForm(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
/**
* Start here.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Demo2());
}
}
You should always try to use a layout manager. The code above uses GridBagLayout but there are several other layout managers that are good at handling forms, including GroupLayout and SpringLayout as well as third party layout managers like MiG Layout and FormLayout.
In order to "show" and "hide" the middle row in your form, simply set the visible property to true or false. If the text of the button is SHOW, then when the user clicks on it, I change the button text to HIDE and make lbl2 and txf2 both visible. If the button text is HIDE, then when the user clicks the button I change the text to SHOW and make lbl2 and txf2 not visible.
Because I use a layout manager, it handles resizing the JPanel whenever the contents of the JPanel are changed. When you don't use a layout manager, then you have to write code that handles the resizing and of-course your code does not, hence your problem.
When i created my gui in java, i set the background color to blackish and there seems to be a pixel line of white at the right most and bottom most sections of my gui. However when i resize this gui, that like goes away and the gui is completely black. Does anyone know why this is happening? I need my gui to set resizeable to false so resizing the gui to fix this problem will not work.
package JavaQuizGameTut;
import java.awt.ActiveEvent.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class Quiz implements ActionListener{
String[] questions = {
"Which company created Java?",
"What year was Java created?",
"What was java originally called?",
"Who was credited for making java?"
};
String[][] options = {{"Sun Microsystems", "Starbucks", "Microsoft", "Alphabet"},
{"1989", "1996", "1972", "1492"},
{"Apple", "Latte", "Oak", "Koffing"},
{"Steve Jobs", "Bill Gates", "James Gosling", "Mark Zuckerburg"}
};
char[] answers = {'A', 'B', 'C', 'C'};
char guess;
char answer;
int index;
int correct_guesses = 0;
int total_questions = questions.length;
int result;
int seconds;
JFrame frame = new JFrame();
JTextField textfield = new JTextField();
JTextArea textarea = new JTextArea();
JButton buttonA = new JButton();
JButton buttonB = new JButton();
JButton buttonC = new JButton();
JButton buttonD = new JButton();
JLabel answer_labelA = new JLabel();
JLabel answer_labelB = new JLabel();
JLabel answer_labelC = new JLabel();
JLabel answer_labelD = new JLabel();
JLabel time_label = new JLabel();
JLabel seconds_left = new JLabel();
JTextField number_right = new JTextField();
JTextField percentage = new JTextField();
public Quiz() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 650);
frame.getContentPane().setBackground(new Color(50, 50, 50));
frame.setLayout(null);
// frame.setResizable(false);
textfield.setBounds(0, 0, 650, 50);
textfield.setBackground(new Color(25,25, 25));
textfield.setForeground(new Color(25, 255, 0));
textfield.setFont(new Font("Ink Free", Font.PLAIN, 30));
textfield.setBorder(BorderFactory.createBevelBorder(1));
textfield.setHorizontalAlignment(JTextField.CENTER);
textfield.setEditable(false);
frame.add(textfield);
frame.setVisible(true);
}
public void nextQuestion() {
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void displayAnswer() {
}
public void results() {
}
}
The background color does cover the entire frame only the reason you are seeing a grey bar above it is that you have placed a textfield on top of it and you have set its background colour to be grey.
As in here:
textfield.setBounds(0, 0, 650, 50);
textfield.setBackground(new Color(25,25, 25));
Try changing textfield's color or temporarily commenting it and you'll see whole frame black.
If nothing fixes it then there's something wrong with your system as it is running fine in my system.
You can try running it in another system.
So Im trying to make a little program to calculate the area of a specific shape.
The user should be able to make a input via a textfield (Like the height and stuff of the shapes). The he should press a button and the price should get printed.
But it doesnt show up.
Code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Rechner extends JFrame implements ActionListener{
private static JButton button1;
private static JButton button2;
private static JButton button3;
private static JButton button4;
private static JTextField numberField;
private JPanel jpanel;
public Rechner(String titel){
super(titel);
jpanel = new JPanel();
numberField = new JTextField(1500);
add(numberField, BorderLayout.CENTER);
button1 = new JButton("Rechteck");
button1.setBounds(10, 10, 150, 30);
button1.addActionListener(this);
add(button1);
button2 = new JButton("Dreieck");
button2.setBounds(170, 10, 150, 30);
button2.addActionListener(this);
add(button2);
button3 = new JButton("Trapez");
button3.setBounds(330, 10, 150, 30);
button3.addActionListener(this);
add(button3);
button4 = new JButton("Parallelogramm");
button4.setBounds(490, 10, 150, 30);
button4.addActionListener(this);
add(button4);
setResizable(false);
}
public static void main(String[] args) {
Rechner frame = new Rechner("Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(660, 400);
frame.setLayout(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1){
System.out.println("fff");
}
String numberStr = numberField.getText();
}
}
The default layout manager of a JFrame (well, of its content pane in fact) is BorderLayout.
Without specified constraints , the component is added to BorderLayout.CENTER, so
add(component);
is the same as
add(component, BorderLayout.CENTER);
and each component added this way will replace the last component added to the center.
Also note that setBounds will have no effect if there is a layout manager, and that you create a JPanel that you never use.
Finally, you may want to have a look at this guide : A Visual Guide to Layout Managers
This line is mainly the problem:
add(numberField, BorderLayout.CENTER);
Is causing the TextField to fill the entire space. Then, the next time you add a component to the JFrame with BorderLayout.CENTER, the JTextField gets replaced. To fix this:
super(titel);
jpanel = new JPanel();
add(jpanel, BorderLayout.NORTH); //adding the jpanel
button1 = new JButton("Rechteck");
jpanel.add(button1);
button1.setBounds(10, 10, 150, 30);
//adding the other buttons to the JPanel...
//...
//...
button4.addActionListener(this);
button3.addActionListener(this);
button2.addActionListener(this);
button1.addActionListener(this);
numberField = new JTextField(1500);
add(numberField);//this will cause it to fill the remaining space
setResizable(false);
Explanation:
The buttons should go into the JPanel you created, and the JPanel should go into the JFrame's NORTH. That way they don't cover the JFrame
Been sitting here at my computer for about 13 hours and I think my eyes are bleeding.
I found a little gui editor I love called GuiGenie.
It works perfect for creating the window with the buttons and all that good stuff.
The problem is i want to click a button in my first menu and have it open my other menu i made.
I just starting programming 4 weeks ago so I'm a complete noob.
I have a feeling its messing up because of the main methods but I have no idea and 13 hours of sitting here trying millions of things is making me go crazy : )
here is what i got so far
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
public MyPanel() {
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("How long were you parked?");
jcomp3 = new JLabel ("Minutes");
jcomp4 = new JButton ("openNewWindow");
//adjust size and set layout
setPreferredSize (new Dimension (315, 85));
setLayout (null);
//add components
add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
//set component bounds (only needed by Absolute Positioning)
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setBounds (0, 0, 315, 25);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
When the button is pressed, I want it to open this new window
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPanel2 extends JPanel {
private JButton jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JTextField jcomp4;
public MyPanel2() {
//construct components
jcomp1 = new JButton ("test1");
jcomp2 = new JButton ("test2");
jcomp3 = new JButton ("test3");
jcomp4 = new JTextField (5);
//adjust size and set layout
setPreferredSize (new Dimension (395, 156));
setLayout (null);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (20, 45, 100, 25);
jcomp2.setBounds (135, 60, 100, 25);
jcomp3.setBounds (260, 35, 100, 25);
jcomp4.setBounds (105, 115, 100, 25);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel2());
frame.pack();
frame.setVisible (true);
}
}
If anyone could help I would appreciate it greatly!!
I have a lot of respect for you pros out there because if you are a pro at this, you are probably smarter than 99.9% of the world.
This stuff hurts my brain.
Here is something you can do, for this situation, where you have multiple Forms or Windows what you can do is to use a JPanel which can have this CardLayout set as it's LayoutManager and then you can add the two JPanels to it and access them with the methods provided by the same.
Don't use setBounds() when using Absolute Positioning this is really not the right way of putting components to the parent container. Instead use setLocation(...) and setSize(...) methods. Consider not to use Absolute Positioning as much as possible for you. Certain lines in favour of the before said line taken from Java Docs are as follows :
Although it is possible to do without a layout manager, you should use a
layout manager if at all possible. A layout manager makes it easier to
adjust to look-and-feel-dependent component appearances, to different
font sizes, to a container's changing size, and to different locales.
Layout managers also can be reused easily by other containers, as well as
other programs.
Since the output of your program is really not a soothing experience in any sense. Atleast LayoutManager, can make that work a lot more easier for you, since you need not have to specify position and size for each and every component. Try walking through the Layout Mangers Tutorials, and get accustomed to them as soon as possible. They are the real life savers :-)
Here is a modified code taken from your SOURCE CODE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
panel2 = new MyPanel2();
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("How long were you parked?");
jcomp3 = new JLabel ("Minutes");
jcomp4 = new JButton ("openNewWindow");
//adjust size and set layout
setPreferredSize (new Dimension (315, 85));
setLayout (null);
//set component bounds (only needed by Absolute Positioning)
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
//add components
add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
}
}
class MyPanel2 extends JPanel {
private JButton jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JTextField jcomp4;
public MyPanel2() {
//construct components
jcomp1 = new JButton ("test1");
jcomp2 = new JButton ("test2");
jcomp3 = new JButton ("test3");
jcomp4 = new JTextField (5);
//adjust size and set layout
setPreferredSize (new Dimension (395, 156));
setLayout (null);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (20, 45, 100, 25);
jcomp2.setBounds (135, 60, 100, 25);
jcomp3.setBounds (260, 35, 100, 25);
jcomp4.setBounds (105, 115, 100, 25);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
}
}
Here is the code for myPanel class, use this one:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MyPanel extends JPanel {
private JTextField How;
private JLabel jcomp2;
private JLabel jcomp3;
private JButton jcomp4;
public MyPanel() {
//construct components
How = new JTextField (1);
jcomp2 = new JLabel ("How long were you parked?");
jcomp3 = new JLabel ("Minutes");
jcomp4 = new JButton ("openNewWindow");
jcomp4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel2());
frame.pack();
frame.setVisible (true);
}
});
//adjust size and set layout
setPreferredSize (new Dimension (315, 85));
setLayout (null);
//add components
add (How);
add (jcomp2);
add (jcomp3);
add (jcomp4);
//set component bounds (only needed by Absolute Positioning)
How.setBounds (245, 50, 60, 25);
jcomp2.setBounds (35, 30, 185, 50);
jcomp3.setBounds (250, 30, 60, 20);
jcomp4.setBounds (0, 0, 315, 25);
jcomp4.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
}
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new MyPanel());
frame.pack();
frame.setVisible (true);
}
}