Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Basically, the problem is that when I either click or hover the mouse over a JComboBox my program's appearance gets all glitched.
Here is how my program look like right after I load it (how it should always look):
And here is what happens after a while of clicking one of the JComboBox'es a few times:
I was researching around for similar problems, and in this page someone was suggesting not to use absolute positioning; but I am not doing that in my program so I'm out of ideas.
Here is the the part of my code where I construct the layout and combo-boxes for my program, which goes in the constructor of my class, and which I launch from main by using: EventQueue.invokeLater(() -> new DownloadCalculator());.
<EDIT: Code replaced with a runnable example. See update #1 below.>
UPDATE 1:
Here is a runnable demo to illustrate the problem. The exact same problem will occur with the combo boxes after a while of fiddling with them. Only the code necessary to reproduce the glitch is included, the functional part that does the main calculations has been removed because it is unrelated to the problem:
import java.awt.*;
import javax.swing.*;
public class RunnableExample
{
private final JFrame mainframe;
private JTextField downloadSize, downloadSpeed, answerBox;
private JComboBox<String> byteTypeSize, byteTypeSpeed, answerTimeUnit;
public RunnableExample()
{
mainframe = new JFrame("Download Calculator");
mainframe.setLayout(new BoxLayout(mainframe.getContentPane(), BoxLayout.Y_AXIS));
mainframe.setSize(new Dimension(600, 300));
mainframe.setResizable(false);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setLocationRelativeTo(null);
initLook();
mainframe.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() -> new RunnableExample());
}
private void calculateDownloadTime(String size, int sizeUnitType, String speed,
int speedUnitType)
{
return; // program's core logic goes here
}
private void initLook()
{
JPanel subLine1 = new JPanel(), subLine2 = new JPanel(), subLine3 = new JPanel();
JLabel question1 = new JLabel("File size to be downloaded:");
downloadSize = new JTextField(10);
byteTypeSize = new JComboBox<>(new String[]{"Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes"});
byteTypeSize.setSelectedIndex(3);
JLabel question2 = new JLabel("Average download speed:");
downloadSpeed = new JTextField(10);
byteTypeSpeed = new JComboBox<>(new String[]{"Bytes / s", "Kilobytes / s", "Megabytes / s", "Gigabytes / s", "Terabytes / s"});
byteTypeSpeed.setSelectedIndex(1);
JButton buttonCalc = new JButton("Calculate");
answerTimeUnit = new JComboBox<>(new String[]{"Seconds", "Minutes", "Hours", "Days"});
answerTimeUnit.setSelectedIndex(2);
buttonCalc.addActionListener((e) -> new Thread(() -> calculateDownloadTime(downloadSize.getText(), byteTypeSize.getSelectedIndex(), downloadSpeed.getText(), byteTypeSpeed.getSelectedIndex())).start());
answerBox = new JTextField("Hit \"Calculate\" button to see answer here.", 25);
answerBox.setEnabled(true);
subLine1.setLayout(new FlowLayout(FlowLayout.CENTER));
subLine2.setLayout(new FlowLayout(FlowLayout.CENTER));
subLine3.setLayout(new FlowLayout(FlowLayout.CENTER));
subLine1.add(question1);
subLine1.add(downloadSize);
subLine1.add(byteTypeSize);
subLine2.add(question2);
subLine2.add(downloadSpeed);
subLine2.add(byteTypeSpeed);
subLine3.add(answerBox);
subLine3.add(answerTimeUnit);
subLine3.add(buttonCalc);
mainframe.getContentPane().add(subLine1);
mainframe.getContentPane().add(subLine2);
mainframe.getContentPane().add(subLine3);
mainframe.pack();
}
}
UPDATE 2:
It seems the graphics work fine as long as I don't click/change any of the combo-boxes. As soon as I click on any of the combo-boxes and then move the mouse outside the area of the combo-box I clicked, then it starts painting those weird glitched graphics. From the feedback I've received, it seems this problem might be platform-specific.
UPDATE 3:
I thought I would share what I found in the end so others with similar problems can try it too: After reinstalling Java and rebooting, the problem seems to have gone away. Thanks to everyone who suggested this and all the other suggestions too!
Related
So I have about a year a 5/12 months experience playing around with java but I have never been able to make anything outside of skeletons. I would really appreciate it if someone could help me understand how I can make an image from my computer visible using swing.
I have gone between different websites trying to find answers but none of the example codes I've tried have worked out. Stackoverflow has helped in the past to learn java through various questions other people asked so I have made an account to ask a question myself. I'm probably being very dumb but my image never appears despite what I've tried. I come back to trying to understand swing every few months after giving up on it previously and while I feel I have a grasp on some basic concepts such as something should be set as visible, how to make/add a JFrame, etc, it's always this that messes me up.
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("main");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
ImageIcon ii = new ImageIcon("C:\\Users\\plasm\\IdeaProjects\\Shdo\\src\\mario.jpg");
JLabel lable = new JLabel(ii);
JScrollPane jsp = new JScrollPane(lable);
frame.getContentPane().add(jsp);
frame. setSize(1000, 700);
JButton button = new JButton();
button.setSize(new Dimension(300, 300));
button.setLocation(500, 350);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}
The code above is copy-pasted from https://www.daniweb.com/programming/software-development/threads/379864/add-image-and-button-to-jframe aside from the pathway, however, it only shows a basic white JFrame at the set dimensions.
frame.getContentPane().add(jsp); // problem
frame. setSize(1000, 700);
JButton button = new JButton();
button.setSize(new Dimension(300, 300)); // does nothing
button.setLocation(500, 350); // does nothing
frame.getContentPane().add(button); //problem
The problem is that the default layout manager for the content pane of the JFrame is a BorderLayout. You are attempting to add two compnents to the CENTER of the BorderLayout which won't work. The button replaces the scroll pane.
Instead you should be using:
frame.getContentPane().add(jsp, BorderLayout.CENTER);
frame. setSize(1000, 700);
JButton button = new JButton("Testing");
frame.getContentPane().add(button, BorderLayout.PAGE_END);
Read the section from the Swing tutorial on Layout Manager for more information and working example of a BorderLayout.
As mentioned in the first comment. There is no need for the getContentPane(). The frame will automatically add the component to the content pane.
Also, when doing testing it is better to do something like:
JLabel label = new JLabel("Icon label");
label.setIcon(ii);
This way if you specify the wrong path for the image, you will at least see the text of the label and you will know the problem is in the path, not with the layout code.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've been looking but have not been able to find something in simple enough terms for me to understand. I currently have a program running on a java console, and I make options available through text. I now want to make this into a window program that uses buttons instead of a text option.
I found info on how to create a JFrame, but I am having issues finding info on how to make a button that calls a method, and have text that changes to show updates.
Any links or info would be much appreciated, I dont know where to go and any nudge is a help!
You can put something like the following code into your "public static void main(String[] args)" method.
JFrame frmMain = new JFrame(); // Create our JFrame
// Set the layout for main frame. This controls how things get arranged on the screen
frmMain.setLayout(new BorderLayout());
// panels are what you put everything else on
JPanel panel1 = new JPanel(new FlowLayout()); // another layout
JPanel panel2 = new JPanel();
BoxLayout box = new BoxLayout(panel2, BoxLayout.PAGE_AXIS); // another layout
panel2.setLayout(box);
// here are a couple of buttons
JButton btnAdd = new JButton("Add");
JButton btnRemove = new JButton("Remove");
// here are a couple of textboxes. They accept typed in information
JTextField txtFirstName = new JTextField();
JTextField txtMiddleInitial = new JTextField();
JTextField txtLastName = new JTextField();
// add our buttons to panel1. It has a FlowLayout, so they will be centered left to right as we add them
panel1.add(btnAdd);
panel1.add(btnRemove);
// Create a panel to hold First Name
JPanel pnlFirstName = new JPanel(new BorderLayout()); // also set its layout
// here we add a JLabel.class they just display text, they don't allow input
pnlFirstName.add(new JLabel("first name"), BorderLayout.WEST);
// here we put our text box onto the First name panel
pnlFirstName.add(txtFirstName, BorderLayout.CENTER);
// repeat for middle initial panel
JPanel pnlMiddleInitial = new JPanel(new BorderLayout());
pnlMiddleInitial.add(new JLabel("M.I."), BorderLayout.WEST);
pnlMiddleInitial.add(txtMiddleInitial, BorderLayout.CENTER);
// repeat for last name panel
JPanel pnlLastName = new JPanel(new BorderLayout());
pnlLastName.add(new JLabel("last name"), BorderLayout.WEST);
pnlLastName.add(txtLastName, BorderLayout.CENTER);
// put a 3 pixel border arounnd panel 2 to keep things away from the edge
panel2.setBorder(new EmptyBorder(3, 3, 3, 3));
// add all of our input panels to panel 2, according to BoxLayout (up above)
panel2.add(pnlFirstName);
panel2.add(pnlMiddleInitial);
panel2.add(pnlLastName);
// add panel1 and panel2 to the Frame. You have to add to the .getContentPane(), or you might mess things up.
frmMain.getContentPane().add(panel1, BorderLayout.NORTH);
frmMain.getContentPane().add(panel2, BorderLayout.CENTER);
// This is how we tell the program what to do when the user presses the "Add" button.
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtFirstName.setText("My First Name");
}
});
// This is how we tell the program what to do when the user presses the "Remove" button.
btnRemove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtFirstName.setText("");
}
});
// pack just makes everything take up it's proper space on the screen in as tight of a package as possible
frmMain.pack();
// if you don't set visible to true, you won't see your Frame
frmMain.setVisible(true);
// what to do when the user clicks the "X" to close or used "Close" from the context menu
frmMain.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Go to bellow link here is the full example how to use button in java using Frame.
Here you got all the details about the Example.
http://www.javatpoint.com/java-jbutton
write your code in actionPerformed() method which you want to do on button click.
going to file menu and export your project in runnable JAR file
than you have a jar file to start in windows
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
is it possible to create a (new)panel inside a tab when you press a button inside the (current)panel?So that the layout is different to the (current) panel? For example the button is just "next".
i can't find anything on google, i have the feeling that my approach is not possible. I tried to illustrate it which a picture but i don't have enough points.
Yes this is definitely possible as Tim B described using a CardLayout. Take a look and maybe this example will help out a bit.
public class JavaApplication2 extends JFrame {
private JPanel mainPanel, cpOne, cpTwo;
private JButton btnContine, btnGoBack;
private CardLayout c1;
public JavaApplication2()
{
super("Card Layout");
mainPanel = new JPanel(new CardLayout());
mainPanel.add(cardOne(), "card1");
mainPanel.add(cardTwo(), "card2");
c1 = (CardLayout) (mainPanel.getLayout());
add(mainPanel);
setSize(200,200);
setVisible(true);
btnContine.addActionListener((ActionEvent e) -> {
c1.show(mainPanel,"card2");
});
btnGoBack.addActionListener((ActionEvent e) -> {
c1.show(mainPanel,"card1");
});
}
private JPanel cardOne()
{
cpOne = new JPanel();
btnContine = new JButton("Next Panel");
cpOne.add(btnContine);
cpOne.add(new JLabel("First Panel"));
return cpOne;
}
private JPanel cardTwo()
{
cpTwo = new JPanel();
btnGoBack = new JButton("Previous Panel");
cpTwo.add(btnGoBack);
cpTwo.add(new JLabel("SECOND PANEL!!!"));
return cpTwo;
}
public static void main(String[] args) {
JavaApplication2 jp = new JavaApplication2();
}
}
If you look at my example we are just creating a frame and adding one main panel to this frame. To that main panel we are setting a CARD LAYOUT as the layout manager. From here we can add as many cards as our heart desires! So there are just some little methods to make our panels with buttons. We add them to the main panel as mainPanel.add(cardOne,"card1") by showing the method as what to add as the card and then naming it card1. When we run the above program you get something like this:
and after clicking the button we get this:
Yes, you can easily do this. Use a CardLayout, place all the panels you want inside that layout, and then switch between them when they press the button.
See this for more information: https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm new to java and programming in general, and I am writing a program that has a menu in it. (It is a JFrame in java) What it does is when you hit a JButton, it shows an applet on the screen. When the applet is done, it goes to a screen where you can choose to run the applet again or go back to the main menu when you hit a button. The problem is that when you hit the button to go back to the menu, it doesn't. All it does is make neither button clickable.
This is the method I use to draw the menu:
public static void drawMenu()
{
f.add(BOption1);
f.add(BOption2);
}
The two jbuttons are already declared and such in the constructor, and they work fine the first time I run the menu. Then, when you hit one of the buttons, it removes both buttons from the screen with f.remove(...). Does anyone know why it won't work when I call this method a second time?
Edit:
Sorry, I meant to say canvas, not applet.
Edit Edit:
I found the solution to my problem, but thanks anyway.
Here is the code for your main class, Frame:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame extends JFrame {
static OnePlayer onePlayer;
static TwoPlayer twoPlayer;
static Frame f;
static JButton BOnePlayer = new JButton("Single Player");
static JButton BTwoPlayer = new JButton("Multiplayer");
static JButton BInstructions = new JButton("Instructions");
static JButton toMenu;
static JButton replay;
public Frame(String name) {
super(name);
this.setTitle(name);
this.setVisible(true);
this.setSize(640, 673);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setLayout(null);
this.setBackground(Color.GRAY);
BOnePlayer.setBounds(120, 150, 400, 100);
BTwoPlayer.setBounds(120, 250, 400, 100);
BInstructions.setBounds(120, 350, 400, 100);
BOnePlayer.setFont(new Font("Comic Sans MS", Font.ITALIC, 20));
BTwoPlayer.setFont(new Font("Comic Sans MS", Font.ITALIC, 20));
BInstructions.setFont(new Font("Comic Sans MS", Font.ITALIC, 20));
BOnePlayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container onePane = f.getContentPane();
onePane.setLayout(new GridLayout(1, 1));
onePlayer = new OnePlayer();
onePane.add(onePlayer);
onePlayer.init();
f.remove(BOnePlayer);
f.remove(BTwoPlayer);
f.remove(BInstructions);
}
});
BTwoPlayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container twoPane = f.getContentPane();
twoPane.setLayout(new GridLayout(1, 1));
twoPlayer = new TwoPlayer();
twoPane.add(twoPlayer);
twoPlayer.init();
f.remove(BOnePlayer);
f.remove(BTwoPlayer);
f.remove(BInstructions);
}
});
BInstructions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
public static void main(String[] args) {
f = new Frame("Snake");
drawMenu();
}
public static void OnePlayerDone(int score) {
}
public static void TwoPlayerDone(int winner, int p1score, int p2score) {
f.remove(twoPlayer);
replay = new JButton("Play Again");
toMenu = new JButton("Return to Menu");
replay.setBounds(120, 100, 400, 100);
toMenu.setBounds(120, 500, 400, 100);
replay.setFont(new Font("Comic Sans MS", Font.ITALIC, 20));
toMenu.setFont(new Font("Comic Snas MS", Font.ITALIC, 20));
f.add(replay);
f.add(toMenu);
replay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container twoPane = f.getContentPane();
twoPane.setLayout(new GridLayout(1, 1));
twoPlayer = new TwoPlayer();
twoPane.add(twoPlayer);
twoPlayer.init();
}
});
toMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawMenu();
}
});
}
public static void drawMenu() {
f.add(BOnePlayer);
f.add(BTwoPlayer);
f.add(BInstructions);
}
}
Suggestions:
First off, rename your class to something other than Frame. This is the name of a closely related core Java class, the AWT equivalent of JFrame, and your giving it the same name can confuse many. Perhaps call it SnakeFrame.
All of your static variables should instead be instance variables.
You shouldn't even have a SnakeFrame variable (your variable f). Instead you should use the current SnakeFrame instance, the this if you will.
Don't mix AWT with Swing components unnecessarily and without need. For instance you should use no Canvas-derived objects but rather JPanel-derived objects.
Your code should follow Java naming conventions so that others (us for instance) can understand it. Variable and method names should all begin with a lower case.
You will want to read up on and use the layout managers to help you place your GUI components on your GUI rather than use null layout and setBounds(...).
Most important, to swap views as you're trying to do, read up on and use a CardLayout as this was built for just this purpose.
This is not an answer and will be deleted, but I needed to post a more complex comment:
I am writing a program that has a menu in it. (It is a JFrame in java) What it does is when you hit a JButton, it shows an applet on the screen.
Can you explain why you're doing this? It is most unusual and difficult for a JFrame to display an applet as an applet. Are you doing this by launching the applet using some stand-alone applet viewer? Perhaps you're doing something else, such as displaying a dialog or another JFrame, but using the wrong terms to describe it?
When the applet is done, it goes to a screen where you can choose to run the applet again or go back to the main menu when you hit a button.
How do you achieve this? What code do you use?
The problem is that when you hit the button to go back to the menu, it doesn't. All it does is make neither button clickable. This is the method I use to draw the menu:
public static void drawMenu()
{
f.add(BOption1);
f.add(BOption2);
}
Does anyone know why it won't work when I call this method a second time?
Somehow your code is changing the state of your program and thereby makes your JButtons unresponsive. How it's doing this -- you haven't told us enough for us to say.
I'm not sure that we have enough information to answer your question yet. Please show more code and give us more detailed and precise description of what is going on. Best would be if you could post an sscce.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Unfortunately, our team leader has decided that we'll use Swing for this light desktop app. I have no previous experience in working with Swing. I will be working on the GUI side of the project. I've already created a frame with elements within it and wrote the logic in the event listeners. Now I want to redirect the user to a new frame after he's logged in.
How do I do that? Thanks
P.S. I'd appreciate if you could point me to a good tutorial for beginners
It sounds like you have your terminology mixed up. When we hear "Frame" we think JFrame which is equivalent to "Window". So most of the time we'd recommend not using multiple windows, but changing the content of the window. The content is generally made with a "JPanel".
So generally, you set up your JFrame, you set the content with this:
JPanel loginPanel = new JPanel();
frame.setContentPane(loginPanel);
If you want to replace your login panel with a new panel, just pass the new panel to that function:
JPanel mainMenuPanel = new JPanel();
frame.setContentPane(mainMenuPanel);
(of course you want some content in those panels)
Here's a simple example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelRetriever{
Box panel1;
JPanel panel2;
public PanelRetriever(final JFrame frame){
//Build the first login panel
panel1 = Box.createVerticalBox();
panel1.setBackground(Color.orange);
panel1.setOpaque(true);
panel1.add(Box.createVerticalGlue());
panel1.add(new JTextField(10));
JButton login = new JButton("Login");
login.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setContentPane(getPanel2());
frame.validate();
}});
panel1.add(login);
panel1.add(Box.createVerticalGlue());
//Build second panel
panel2 = new JPanel();
panel2.setBackground(Color.blue);
panel2.setOpaque(true);
JButton logout = new JButton("Logout");
logout.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(getPanel1());
frame.validate();
}});
panel2.add(logout, BorderLayout.CENTER);
}
public Container getPanel1(){
return panel1;
}
public Container getPanel2(){
return panel2;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
PanelRetriever pr = new PanelRetriever(frame);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(pr.getPanel1());
frame.setPreferredSize(new Dimension(500, 400));
frame.pack();
frame.setVisible(true);
}
});
}
}
Your frame should stay the same, just create and show new JPanel instead old one.
See below JPanel painting process:
As #Gilbert Le Blanc has pointed out (+1 to him). In Swing it is bad practice to use multiple JFrames.
To accomplish what you want:
Use CardLayout which allows dynamic switching of components
Or use JFrame#removeAll() and add a new JPanel (+1 Fess)
Try using JDialog/JOptionPane and then redirect to main JFrame
here is a good link on the topic: How to Make Dialogs
In Swing, you have one JFrame. You use JDialogs to get user id and password input from the user.
Here's a link to the Oracle Swing Tutorial.
You can just create a new frame in much the same way as you already have;
MyFrame f = new MyFrame(); //MyFrame extends javax.swing.JFrame
And then bring it to the front with;
f.setVisible(true);
f.toFront();