When I try to add a JButton and a JLabel into a JFrame, they both conflict each other in which all the JButtons would disappear and only the JLabel would be visible. The JLabel for some reason would go to the left most side of the JFrame instead of the desired location I set it to go. I'm new to GUI related material and I'm willing to learn from these mistakes.
Here is my code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Windowb extends JFrame{
static String title = "This is a JFrame";
static int width = 500;
static int height = 400;
private static final int BUTTON_LOCATION_X = 46;
private static final int BUTTON_LOCATION_Y = 80;
public static void main(String[]args){
Windowb simple = new Windowb(title, width, height);
JPanel p = new JPanel();
p.setLayout(null);
JLabel c1 = new JLabel("Name: ");
JButton b1 = new JButton("Name:");
JButton b2 = new JButton("Grade:");
JButton b3 = new JButton("GPA");
b1.setBounds(BUTTON_LOCATION_X, BUTTON_LOCATION_Y, 90, 20);
b2.setBounds(50, 170, 90, 20);
b3.setBounds(50, 240, 90, 20);
c1.setLocation(100, 250);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "ActionListener is working!");
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "The second one works too!");
}
});
b3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "Surprise!");
}
});
p.add(b1);
p.add(b2);
p.add(b3);
simple.add(p);
simple.add(c1);
}
public Windowb(String t, int w, int h){
setVisible(true);
setResizable(true);
setSize(w, h);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(500, 100);
setTitle(t);
}
}
You probably should use a LayoutManager. See the layout manager tutorial: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
setBounds() is used by the layout manager to position components. You can set the LayoutManager to null and position the components yourself but stuff like window resizing isn't handled for you that way (ie. components and space aren't scaled accordingly). If you want to maintain your sanity then don't use the build in GridBag layout! It will drive you insane! For more complex layouts use http://www.miglayout.com/ or http://www.jgoodies.com/freeware/libraries/forms/ . For simple layouts use layoutmanagers like BorderLayout.
If you really don't want to use a layoutmanager then use a JPanel. A JFrame can only hold a single component so thats your problem. Put a JPanel inside the JFrame and put your components in the JPanel.
Related
While building a simple currency converter app setText is not setting the value in JLabel.(I am using eclipse ide in windows).I have called Action Listener for setting button and also had converted the getText to int with the help of parseInt.
My code is given below.
import java.awt.Color;
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.JTextField;
public class CurrencyConverter implements ActionListener {
JButton button1,button2;
JLabel display2,display3;
JTextField display;
public CurrencyConverter() {
var frame=new JFrame();
frame.setLayout(null);
frame.setBounds(300, 300, 400, 300);
frame.getContentPane().setBackground(Color.BLACK);
display=new JTextField();
display.setBounds(50, 30, 300, 50);
display.setBackground(Color.yellow);
display.setForeground(Color.black);
frame.add(display);
button1=new JButton("TO INR");
button1.setBounds(50, 100, 135, 50);
frame.add(button1);
button2=new JButton("TO USD");
button2.setBounds(215, 100, 135, 50);
frame.add(button2);
display2=new JLabel();
display2.setBounds(50, 170, 300, 50);
display2.setBackground(Color.GREEN);
display2.setForeground(Color.BLACK);
display2.setOpaque(true);
frame.add(display2);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new CurrencyConverter();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button1) {
int noInDisplay=Integer.parseInt(display.getText())*70;
display2.setText(""+noInDisplay);
}
else if(e.getSource()==button2) {
int noInDisplay=Integer.parseInt(display.getText())/70;
display2.setText(""+noInDisplay);
}
}
}
The main issue why you are not seeing any visible updates on your JLabel is that the ActionListener is never added on the buttons, hence the actionPerformed() is never called.
To fix this, you should add these two lines in the CurrencyConverter() constructor, to add the ActionListener on your buttons:
button1.addActionListener(this);
button2.addActionListener(this);
Some sidenotes on your code:
It is generally not recommended to use null layout in swing. Have a look at the Visual Guide to Layout Managers for an overview on swing layout managers. Using a layout manager will do the work of sizing and laying out the components for you. So you don't have to manually set the size and bounds for each component yourself.
Instead of checking for the source of the action in actionPerformed() you could implement an anonymous ActionListener for each JButton. This way, you have a clear mapping between component and action. E.g.
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int noInDisplay = Integer.parseInt(display.getText()) * 70;
display2.setText("" + noInDisplay);
}
});
Some kind of input validation should be considered in the next step.
I have a JFrame with a JButton , this button open a new JFrame where there should be a text box ( JTextField ) that I will use for a search , the problem is that I don't know how to insert it . I came up with this :
N.B I'm a beginner, sorry in advance for the easy question :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainWindow {
// Seconda Finestra
public static void NuovaFinestra (JPanel panel) {
panel.setLayout(null);
JButton Ricerca = new JButton("Ricerca");
Ricerca.setBounds(100, 100, 200, 50);
panel.add(Ricerca);
Ricerca.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame FinestradiRicerca = new JFrame("Finestra di Ricerca");
FinestradiRicerca.setBounds(300, 300, 500, 500);
FinestradiRicerca.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel riquadroRicerca = new JPanel();
FinestradiRicerca.add(riquadroRicerca);
FinestradiRicerca.setVisible(true);
JTextField ciao;
ciao = new JTextField ();
}
});
}
//Main
public static void main(String[] args) {
//Finestra Principale
JFrame finestra = new JFrame("Finestra principale");
finestra.setSize(500, 500);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel della finestra principale
JPanel riquadro = new JPanel();
finestra.add(riquadro);
finestra.setVisible(true);
NuovaFinestra(riquadro);
}
}
You needed to add your new elements to riquadroRicerca BEFORE adding the Panel to FinestradiRicerca, I recommend you NOT to use null layout but a Layout Manager or combinations of them. If you insist on keeping null layout then see below example. But for this kind of app I'd suggest a CardLayout.
I also suggest not using multiple JFrames since they will open multiple windows on task bar which is user unfriendly. See: Use of multiple JFrames, Good / Bad Practice
As an aside note, follow Java naming conventions. For example you called a JFrame as FinestradiRicerca instead rename it to: finestradiRicerca (1st letter of a variable in lowercase).
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainWindow {
// Seconda Finestra
public static void NuovaFinestra (JPanel panel) {
panel.setLayout(null);
JButton Ricerca = new JButton("Ricerca");
Ricerca.setBounds(100, 100, 200, 50);
panel.add(Ricerca);
Ricerca.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame FinestradiRicerca = new JFrame("Finestra di Ricerca");
FinestradiRicerca.setBounds(300, 300, 500, 500);
//If you don't want to close whole app when closing this windo change it to: JFrame.DISPOSE_ON_CLOSE
FinestradiRicerca.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel riquadroRicerca = new JPanel();
JTextField ciao;
JLabel myLabel = new JLabel("Here goes your label text");
ciao = new JTextField ();
ciao.setColumns(20);
riquadroRicerca.add(myLabel);
riquadroRicerca.add(ciao);
FinestradiRicerca.add(riquadroRicerca);
FinestradiRicerca.setVisible(true);
}
});
}
//Main
public static void main(String[] args) {
//Finestra Principale
JFrame finestra = new JFrame("Finestra principale");
finestra.setSize(500, 500);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel della finestra principale
JPanel riquadro = new JPanel();
finestra.add(riquadro);
finestra.setVisible(true);
NuovaFinestra(riquadro);
}
}
So, your code after a few modifications, to make JLabel and JTextField visible gives the following output:
However, please follow my above recomendations.
Add the JTextField to your new JFrame like this. You also have to initialize your textfield. It is basically the same as you have done with the initial JFrame.
JTextField ciao = new JTextField();
FinestradiRicerca.add(ciao);
I want to put value in txtf1 at output screen and get it. How can we put value on text field on output screen?
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class demog extends JPanel implements ActionListener{
private TextField textf, txtf1;
public void jhand(){
textf = new TextField();
textf.setSize(40, 40);
textf.setText("20");
textf.setEditable(false);
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
//textf.setHorizontalAlignment(SwingConstants.CENTER);
textf.setLocation(15, 15);
//textf.addActionListener(this);
txtf1 = new TextField();
txtf1.setSize(40, 40);
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
//txtf1.setHorizontalAlignment(SwingConstants.CENTER);
txtf1.setLocation(50, 50);
JFrame frame = new JFrame("demo");
JPanel p = new JPanel();
p.setOpaque(true);
p.setBackground(Color.WHITE);
p.setLayout(null);
frame.setContentPane(p);
frame.setSize(500,500);
frame.setVisible(true);
p.add(textf);
p.add(txtf1);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
System.out.println(text);
}
public static void main(String... args){
demog g = new demog();
g.jhand();
}
}
You have to change some of your code in order to work. You had some problem in your code which I resolved them for you in the following code. See the comments to learn some in swing ;-)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
// Use upper Case in the start of you class names:
public class Demog extends JPanel implements ActionListener {
private JTextField textf, txtf1;
public Demog() {
jhand();
}
public void jhand() {
setLayout(new FlowLayout()); // Always set the layout before you add components
// you can use null layout, but you have to use setBounds() method
// for placing the components. For an advanced layout see the
// tutorials for GridBagLayout and mixing layouts with each other.
textf = new JTextField(); // Do not mix AWT component with
// Swing (J components. See the packages)
//textf.setSize(40, 40); // Use setPreferredSize instead
textf.setPreferredSize(new Dimension(40, 40));
textf.setText("20");
textf.setEditable(false); // Text fields are for getting data from user
// If you need to show something to user
// use JLabel instead.
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
add(textf);
txtf1 = new JTextField();
//txtf1.setSize(40, 40); Use setPreferredSize instead
txtf1.setPreferredSize(new Dimension(40, 40));
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
add(txtf1);
JButton b = new JButton("Click ME!");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
JOptionPane.showMessageDialog(Demog.this, "\"textf\" text is: "+text);
}
public static void main(String[] args) {
JFrame frame = new JFrame("demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Demog p = new Demog();
p.setBackground(Color.WHITE);
frame.setContentPane(p);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Good Luck.
I want to add a jPanel which is semi transparent. But other components which are placed inside the jPanel such as buttons and labels should be displayed with 100% opacity. I am using netbeans to design the GUIs. Normally i drag and drop the swing components in the palette to design the GUI(I don't code them). I can't see any property in properties window to achieve this. Please help me. As I am quite new to java please give me a detailed answer. Thanks in advance.
You can use
JPanel.setBackground(Color bg);
to make the panel semi-transparent. What matter is the color's property.
You can construct a color with alpha values to set the transparent degree of the color.
panel.setBackground(new Color(213, 134, 145, 123));
The last parameter is actual the alpha value and you can adjust it to see the effect.
Here is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PanelTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
PanelTest test = new PanelTest();
test.createUI();
}
};
SwingUtilities.invokeLater(runnable);
}
public void createUI(){
JFrame frame = new JFrame("Panel Test");
JPanel panel = new JPanel();
panel.setBackground(new Color(213, 134, 145, 123));
JButton button = new JButton("I am a button");
JLabel label = new JLabel("I am a label");
label.setFont(new Font("Arial", Font.BOLD, 15));
JTextField textField = new JTextField();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(Box.createVerticalStrut(20));
panel.add(label);
panel.add(Box.createVerticalStrut(20));
panel.add(textField);
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
BottomPanel buttomPanel = new BottomPanel();
buttomPanel.add(panel);
frame.add(buttomPanel,BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class BottomPanel extends JPanel{
#Override
protected void paintComponent(Graphics g) {
for (int y = 0; y < 200; y = y + 20) {
g.drawString("I am the string on the bottom", 5, y);
}
}
}
}
Here is the effect and hope it can help you.
You can simply create your jPanel using drag and drop, as you always do and then for changing the panel's color and making it transparent or semi-transparent you can use this code:
panel.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));
You can change the color by changing first three parameters of Color constructor, which represent RGB and you can change transparency by changing fourth parameter, which is the alpha value of color.
I am a beginner, starting a simple project on GUI. The RectangleComponent should draw a Rectangle on the form with a button click. A rectangle won't draw with the following code, but if I put the same 2 lines of code outside the listener, it certainly works. I would appreciate any help.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EllipseRectViewer {
/**
* #param args
*/
public static void main(String[] args)
{
final JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Rectangle and Ellipse Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.NORTH);
class RectangleDrawListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
RectangleComponent r2 = new RectangleComponent();
frame.add(r2);
}
}
JButton rectButton = new JButton("Rectangle");
ActionListener rectDrawListener = new RectangleDrawListener();
rectButton.addActionListener(rectDrawListener);
panel.add(rectButton);
frame.setVisible(true);
}
}
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class RectangleComponent extends JComponent
{
Rectangle rect;
public RectangleComponent()
{
rect = new Rectangle(20, 20, 30, 30);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
Thank you.
After adding the RectangleComponent to the frame, either revalidate the newly added component or the frame's root pane:
public void actionPerformed(ActionEvent event) {
RectangleComponent r2 = new RectangleComponent();
frame.add(r2);
// Option 1
r2.revalidate();
// Option 2
frame.getRootPane().revalidate();
}
Note1: the frame itself can't be revalidated (upto JDK 1.6)
Note2: the frame itself can be revalidated (JDK 1.7+)
i think you need to revalidate() the frame.
frame.revalidate();
put it like this:
public void actionPerformed(ActionEvent event)
{
RectangleComponent r2 = new RectangleComponent();
frame.add(r2);
frame.revalidate();
}
Try to use LineBorder. Create a JPanel with LineBorder and add the JButton to the JPanel.
rect = new Rectangle(20, 20, 30, 30);
A second problem is that your component doesn't have a preferred size. Your component displays in a simple frame because you add the comonent to the center of a BorderLayout so the preferred size of the component is ignored. However, this won't work if you try to use the component when using other layout managers.
You should also override the getPreferredSize() method to return the preferred size of your component at a minimum you need to use:
return new Dimension(50, 50);
to accomodate the size and location of the painted rectangle.