Java Swing Applet- Cant set background color - java

Im new to Swing, first of all. Im trying to set the background color of an audio recording applet to make it blend with my webpage (white instead of the default grey), but the change never seems to take. Heres the applet initialization...
public void init()
{
setLayout(null);
setBackground(Color.white);
JLabel recorder = new JLabel("Record");
JLabel fileName = new JLabel("Please Enter File Name");
JLabel status = new JLabel("Status...");
fnametxt = new JTextField("FileNameHere");
statustxt = new JTextField("");
record = new JButton("Record");
play = new JButton("Play");
pause = new JButton("Pause");
stop = new JButton("Stop");
send = new JButton("Upload");
listen = new JButton("Listen");
save = new JButton("Save and Submit");
//A bunch of other stuff, event listeners and whatnot.
Im using no layout managers, Im setting all the positions manually. Any ideas?

You set (presumably) the background of the Applet, but that background will only show where it is not obstructed by another component.
Depending on how you structured your GUI, there may be inner panels or other components covering the area. You need to change the color of those components, too (or alternately set them to be transparent using setOpaque(false)).
Edit: setOpaque() is only available for Swing components, not the Applet itself (since that is plain old AWT).

You probably should set the background color of the content pane.

If you're using a JPanel in your applet, you'll have to color the JPanel's content pane as well. The following code sets the background of the JPanel itself AND its content pane to white:
setBackground(Color.white);
getContentPane().setBackground(Color.white); //Color JPanel

Related

How to display a JLabel on top of another JLabel, with specified coordinate?

I'm working on a GUI for a Tic Tac Toe project, in which I want to get an image (the player's move) to show up when clicking the corresponding area. However, I can't figure out how to display a JLabel (the move) on top of another JLabel (the background).
I have searched and tried to use layeredpanes, but it just fails to show the entire frame when I run it. I am new to GUI, so I am not quite sure if I implemented it correctly.
layer = new JLayeredPane();
//set up the board as background
String path = "sampleUrl";
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
bg4 = new JLabel(new ImageIcon(image));
layer.add(bg4, new Integer(-1));
frame.add(layer);
frame.pack();
frame.addMouseListener(new MouseListener4());
String xPath = "sampleUrl";
URL xUrl = new URL(xPath);
BufferedImage x = ImageIO.read(xUrl);
icon = new JLabel(new ImageIcon(x));
layer.add(icon);
It just shows up a window with minimum width and height, without displaying the background. Is there something wrong with this code, or any other ways for me to put a JLabel on top of another JLabel?
You can add one label object into another, as JLabel is a container. Try something like this.
JLabel parentLabel = new JLabel("Parent");
JLabel childLabel = new JLabel("Child");
parentLabel.add(childLabel );
I highly recommend you to read about javafx if you are new in GUI.you can merge nodes in any way you need.you can put labels on each other using stackpane,and display them top and down of each other using gridpane very easily.
more information on:
https://docs.oracle.com/javafx/2/

Java Applet gridlayout issue

im having a little issue with my code. I have created a gridlayout of 5,1,0,0. I have a textfield, 3 buttons and a label where the result analysis of whatever the user had input is displayed at the bottom. Now the results can come on multiple lines depending on how big words are in the sentence, my problem is when multiple lines of results are displayed, the layout of my program changes and i dont know how to keep it the same but just the label or Applet window itself resize if need be?
public class assignment_tauqeer_abbasi extends JApplet implements ActionListener {
JTextArea textInput; // User Input.
JLabel wordCountLabel; // To display number of words.
public void init() {
// This code from here is the customisation of the Applet, this includes background colour, text colour, text back ground colour, labels and buttons
setBackground(Color.black);
getContentPane().setBackground(Color.black);
textInput = new JTextArea();
textInput.setBackground(Color.white);
JPanel south = new JPanel();
south.setBackground(Color.darkGray);
south.setLayout( new GridLayout(5,1,0,0) );
/* Creating Analyze and Reset buttons */
JButton countButton = new JButton("Analyze");
countButton.addActionListener(this);
south.add(countButton);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
south.add(resetButton);
JButton fileButton = new JButton("Analyze Text File");
fileButton.addActionListener(this);
south.add(fileButton);
/* Labels telling the user what to do or what the program is outputting */
wordCountLabel = new JLabel(" No. of words:");
wordCountLabel.setBackground(Color.black);
wordCountLabel.setForeground(Color.red);
wordCountLabel.setOpaque(true);
south.add(wordCountLabel);
/* Border for Applet. */
getContentPane().setLayout( new BorderLayout(2,2) );
/* Scroll bar for the text area where the user will input the text they wish to analyse. */
JScrollPane scroller = new JScrollPane( textInput );
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(south, BorderLayout.SOUTH);
} // end init();
public Insets getInsets() {
// Border size around edges.
return new Insets(2,2,2,2);
}
// end of Applet customisation
This is my code for the layout. Any help would be apprecited!
A GridLayout will size every cell according to the content of the largest cell. Consider using a different layout, or a combination of layouts instead.
The gridLayout that you have used would possibly complicate the five contents that you have used. Try using flow Layout instead this would automatically make space for the new contents that are being entered.

Why does my JButton appear the full size of the JFrame?

I am a newbie, I have a question. I am trying to use Eclipse to write a Java windows application, in which I will have a main window, which will contain several things, like a dashboard sort of thing, and it will have buttons, for example to add a record to a database, and this button when pressed, will open a new relevant window on top.
I tried to start, I wrote this code in Java, and for some reason, the button is in the size of the frame...full screen ! How do I fix it ?
Can you suggest me better ideas for a design than what I specified ?
Thank you
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame jfrm = new JFrame("Frame1");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jfrm.setSize(screenSize.width, screenSize.height);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Hello");
jfrm.add(jlab);
JButton button = new JButton("Button");
button.setSize(new Dimension(50, 50));
button.setLocation(500, 350);
jfrm.getContentPane().add(button);
jfrm.setVisible(true);
}
Add a layout to the JFrame first. For example FlowLayout:
jfrm.setLayout(new FlowLayout());
"I tried to start, I wrote this code in Java, and for some reason, the button is in the size of the frame...full screen ! How do I fix it ?"
The reason the button stretches is because JFrame has a default BorderLayout that does not respect the preferred sizes of child components.
The solution is to set the Layout Manager to layout that does respect preferred sizes. The image blow from this example shows the most common Layout Managers and show visually which one respect the preferred size of child components.
Also, the BorderLayout is also the reason your JLabel does not show. By default, every component that is added to a BorderLayout without a position specified e.g. BorderLayout.SOUTH, will automatically be placed in the BorderLayout.CENTER position. Each position may only have one component. So when you add the JLabel it goes to the CENTER, but when you add the JButton, it also goes the CENTER, kicking out the JLabel.
If you've never encountered Layout Managers, this is probably all confusing to you. You should take the time to go over How to Layout Components Within a Container
You need to use some form of layoutmanager, you can use this information: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
You must use Layout manager.
Use this code..
public static void main(String[] args)
{
JFrame jfrm = new JFrame("Frame1");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jfrm.setSize(screenSize.width, screenSize.height);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Hello");
jfrm.add(jlab);
JButton button = new JButton("Button");
button.setSize(new Dimension(50, 50));
button.setLocation(500, 350);
jfrm.add(button);
jfrm.setVisible(true);
jfrm.setLayout(new FlowLayout());
jfrm.pack();
you forgot to add pack(). so use this code to get Jlabel and JButtion side by side.
Thanks...

Java Swing panel layered on top with centered text

I'm making a simple Jeopardy-esque game:
using Java Swing. It's obviously a JFrame with a JPanel in it and buttons in rows.
Now what I need is to add a layered panel with a centered and wrapped text in it:
Which I can remove later. I already tried using JTextPane and JTextArea and JPanel, none of those want to even display. The best effect I have achieved with AWT Panel, it does display but I can't center or wrap text in it.
Here's some code for which I appologise, I would usually try to make it short and readable but since it's not working I don't know what to do with it to make ti look better:
JLabel questionLabel = new JLabel(questionList.get(randomNumber).getQuestion(), SwingConstants.CENTER);
Font font = new Font("Arial", Font.PLAIN, 20);
//------------------JTextPane--------------------
JTextPane questionPane = new JTextPane();
questionPane.setForeground(Color.WHITE);
questionPane.setSize(gameWidth, gameHeight);
questionPane.setText(questionList.get(randomNumber).getQuestion());
questionPane.setFont(font);
questionPane.setEditable(false);
//------------------AWT panel--------------------
Panel awtPanel = new Panel();
awtPanel.setBackground(Color.blue);
awtPanel.setSize(game.getWidth(),game.getHeight());
Label labelQuestion = new Label("<html>" + questionList.get(randomNumber).getQuestion() + "</html>", Label.CENTER);
labelQuestion.setFont(font);
awtPanel.setForeground(Color.white);
awtPanel.add(labelQuestion);
//------------------JPanel-----------------------
JPanel layeredPanel = new JPanel();
layeredPanel.setBackground(Color.blue);
layeredPanel.setSize(game.getWidth(),game.getHeight());
JLabel jLabelQuestion = new JLabel("<html>" + questionList.get(randomNumber).getQuestion() + "</html>", SwingConstants.CENTER);
jLabelQuestion.setFont(font);
layeredPanel.setForeground(Color.WHITE);
layeredPanel.add(jLabelQuestion, BorderLayout.CENTER);
game.getLayeredPane().add(layeredPanel, JLayeredPane.DEFAULT_LAYER);
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
button.setEnabled(false);
font = new Font("Arial", Font.PLAIN, 16);
button.add(jLabelQuestion, BorderLayout.CENTER);
button.setDisabledIcon(new ImageIcon(source.getScaledInstance(gameWidth/4, gameHeight/5, java.awt.Image.SCALE_SMOOTH)));
questionList.remove(randomNumber);
logger.info(questionList.size());
game.getLayeredPane().remove(layeredPanel);
UPDATE: I chnaged to SWT rather than Swing, and I use the StackLayout with a few Composites in it, and just change between them as I see fit.
You can generally solve issues like this with a JLabel.
I would recommend encapsulating the above grid in the BorderLayout.CENTER of another pane, perhaps a new content pane. Then, add the caption to BorderLayout.NORTH.
As a more tangible example,
private void createContent() {
this.getContentPane().setLayout(new BorderLayout());
//establish the panel currently set as center, here labeled "everythingElse"
this.getContentPane().add(everythingElse, BorderLayout.CENTER);
//Create a JLabel with your caption
JLabel jlbl = new JLabel("Question");
//format that caption, most details being rather obvious, but most importantly:
jlbl.setHorizontalAlignment(SwingConstants.CENTER); //keeps text centered
this.getContentPane().add(jlbl, BorderLayout.NORTH); //add it to the top of the panel
//...other cleanup operations...
}
The issue with grid panes is that they have a limited tolerance for the number of components visible in them. If you overload one, it won't show. For BorderLayout panes, you can easily swap new items into and out of them.
For efficiency's sake, I might recommend compiling this JLabel as a final somewhere else in your code, and holding onto it for when you need it. This way, you will also dodge overhead from repeatedly creating the label object.
Lastly, avoid AWT whenever you can. It's been deprecated for an excess of ten years, and if you do use it you will run into numerous critical problems involving heavyweight and lightweight component incompatibilities. If you intend to use another windowing kit, consider implementing the new standard, JavaFX, with a JFXPane-- it's much more tolerant of HTML syntax, as well.

Buttons overwriting each other

So my buttons are overwriting each other, instead of all going up North like a tool bar..
I'm trying to get the buttons to go up North if that makes sense. I know my GUI is awful, and I'll rewire it once I get this prototype done.
// panels
mainPuzzlerPanel = new Panel();
mainPuzzlerPanel.setLayout(new BorderLayout());
puzzlePanel = new Panel();
//mainPuzzlerPanel.setLayout(null);
puzzlePanel.setLocation(100, 120);
// text fields
debugTxt = new TextArea(null,6,40,1);
debugTxt.setEditable(false);
mainPuzzlerPanel.add(debugTxt,BorderLayout.NORTH);
// buttons
Button newPuzzle = new Button("New Puzzle");
Button loadImage = new Button("Load Image");
Button assignLocation = new Button("Assign Location");
Button assignTimestamp = new Button("Assign Timestamp");
Button savePuzzle = new Button("Save Puzzle");
Button clearPuzzleCreator = new Button("Clear");
newPuzzle.addActionListener(this);
loadImage.addActionListener(this);
assignLocation.addActionListener(this);
assignTimestamp.addActionListener(this);
savePuzzle.addActionListener(this);
clearPuzzleCreator.addActionListener(this);
mainPuzzlerPanel.add(assignLocation,BorderLayout.NORTH);
mainPuzzlerPanel.add(assignTimestamp,BorderLayout.NORTH);
mainPuzzlerPanel.add(loadImage,BorderLayout.NORTH);
mainPuzzlerPanel.add(savePuzzle,BorderLayout.NORTH);
mainPuzzlerPanel.add(clearPuzzleCreator,BorderLayout.NORTH);
mainPuzzlerPanel.add(newPuzzle,BorderLayout.NORTH);
mainPuzzlerPanel.add(puzzlePanel,BorderLayout.CENTER);
add(mainPuzzlerPanel, "Controls");
setSize(1200, 700);
setVisible(true);
You can't add all the components BorderLayout.NORTH, makes no sense. Instead, add the JButtons to a JPanel that uses a different layout, say GridLayout, and then add that JPanel BorderLayout.NORTH. But most important -- read a tutorial on how to use the layout managers. It looks like you're guessing at this and that's not an efficient way to learn how to use these complex tools.
Regading,
I know my GUI is awful, and I'll rewire it once I get this prototype done.
Also not a good plan. It's much easier to write it well the first time through.
e.g.,
// after creating all of your JButtons, put them in an array...
JButton[] btnArray = {newPuzzle, loadImage, assignLocation, assignTimestamp,
savePuzzle, clearPuzzleCreator};
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
for (JButton btn : btnArray) {
buttonPanel.add(btn);
}
mainPuzzlerPanel.add(buttonPanel, BorderLayout.NORTH);
Edit: Oops, I notice now you're using Buttons and Panels, not JButtons and JPanels. I urge you to change your app to be a Swing app not an AWT app.
Layout manager tutorial: Laying Out Components Within a Container

Categories

Resources